<commit_before>class MapsController < ApplicationController
   layout 'mapdetail', :only => [:show, :edit, :preview, :warp, :clip, :align, :activity, :warped, :export, :metadata, :comments, :gaia_url, :otm_url]
  #before_filter :login_required, :only => [:destroy, :delete]
  before_filter :login_or_oauth_required, :only => [:new, :create, :edit, :update, :destroy, :delete, :warp, :rectify, :clip, :align,
 :warp_align, :mask_map, :delete_mask, :save_mask, :save_mask_and_warp, :set_rough_state, :set_rough_centroid ]
  before_filter :check_administrator_role, :only => [:publish]
  before_filter :find_map_if_available,
    :except => [:show, :index, :wms, :tile, :mapserver_wms, :warp_aligned, :status, :new, :create, :update, :edit, :tag, :geosearch]

  before_filter :check_link_back, :only => [:show, :warp, :clip, :align, :warped, :export, :activity]
  before_filter :check_if_map_is_editable, :only => [:edit, :update]
  before_filter :check_if_map_can_be_deleted, :only => [:destroy, :delete]
  
  skip_before_filter :verify_authenticity_token, :only => [:save_mask, :delete_mask, :save_mask_and_warp, :mask_map, :rectify, :set_rough_state, :set_rough_centroid]
  #before_filter :semi_verify_authenticity_token, :only => [:save_mask, :delete_mask, :save_mask_and_warp, :mask_map, :rectify]
  rescue_from ActiveRecord::RecordNotFound, :with => :bad_record



  helper :sort
  include SortHelper

  def choose_layout_if_ajax
    if request.xhr?
      @xhr_flag = "xhr"
      render :layout => "tab_container"
    end
  end

  def get_rough_centroid
    map = Map.find(params[:id])
    respond_to do |format|
      format.json {render :json =>{:stat => "ok", :items => map.to_a}.to_json(:except => [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id,  :map, :thumbnail, :rough_centroid]), :callback => params[:callback]  }
    end
  end
  
  def set_rough_centroid
    map = Map.find(params[:id])
    lon = params[:lon]
    lat = params[:lat]
    zoom = params[:zoom]
    respond_to do |format|
      if map.update_attributes(:rough_lon  => lon, :rough_lat => lat, :rough_zoom => zoom ) && lat && lon
        map.save_rough_centroid(lon, lat)
        format.json {render :json =>{:stat => "ok", :items => map.to_a}.to_json(:except => [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id,  :map, :thumbnail, :rough_centroid]), :callback => params[:callback]
        }
      else
        format.json { render :json => {:stat => "fail", :message => "Rough centroid not set", :items => [], :errors => map.errors.to_a}.to_json, :callback => params[:callback]}
      end
    end
  end

  def get_rough_state
    map = Map.find(params[:id])
    respond_to do |format|
      if map.rough_state
        format.json { render :json => {:stat => "ok", :items => ["id" => map.id, "rough_state" => map.rough_state]}.to_json, :callback => params[:callback]}
      else
        format.json { render :json => {:stat => "fail", :message => "Rough state is null", :items => map.rough_state}.to_json, :callback => params[:callback]}
      end
    end
  end

  def set_rough_state
    map = Map.find(params[:id])
    respond_to do |format|
      if map.update_attributes(:rough_state => params[:rough_state]) && Map::ROUGH_STATE.include?(params[:rough_state].to_sym)
        format.json { render :json => {:stat => "ok", :items => ["id" => map.id, "rough_state" => map.rough_state]}.to_json, :callback => params[:callback] }
      else
        format.json { render :json => {:stat => "fail", :message =>"Could not update state", :errors => map.errors.to_a, :items => []}.to_json , :callback => params[:callback]}
      end
    end
  end

 def otm_url
    map = Map.find(params[:id])
    respond_to do |format|
        format.text { render :text => "otm://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url()) }
    end
  end

 def gaia_url
    map = Map.find(params[:id])
    respond_to do |format|
        format.text { render :text => "gaiagps://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url()) }
    end
  end

  def comments
    @html_title = "comments"
    @selected_tab = 9
    @current_tab = "comments"
    @comments = @map.comments
    choose_layout_if_ajax
    respond_to do | format |
      format.html {}
    end
  end

  #pass in soft true to get soft gcps
 def gcps
    @map = Map.find(params[:id])
    gcps = @map.gcps_with_error(params[:soft])
    respond_to do |format|
      #format.json { render :json => gcps.to_json(:methods => :error)}
      format.json { render :json => {:stat => "ok", :items => gcps.to_a}.to_json(:methods => :error), :callback => params[:callback]}
      format.xml { render :xml => gcps.to_xml(:methods => :error)}
    end
  end

    require 'yahoo-geoplanet'
  def geosearch
    sort_init 'updated_at'
    sort_update

    extents = [-74.1710,40.5883,-73.4809,40.8485] #NYC

    #TODO change to straight javascript call.
    if params[:place] && !params[:place].blank?
      place_query = params[:place]
      Yahoo::GeoPlanet.app_id = Yahoo_app_id
      geoplanet_result = Yahoo::GeoPlanet::Place.search(place_query, :count => 2)
      if geoplanet_result[0]
        g_bbox =  geoplanet_result[0].bounding_box.map!{|x| x.reverse}
        extents = g_bbox[1] + g_bbox[0]
        render :json => extents.to_json
        return
      else
        render :json => extents.to_json
        return
      end
    end

    if params[:bbox] && params[:bbox].split(',').size == 4
      begin
        extents = params[:bbox].split(',').collect {|i| Float(i)}
      rescue ArgumentError
        logger.debug "arg error with bbox, setting extent to defaults"
      end
    end
    @bbox = extents.join(',')

    if extents
      bbox_poly_ary = [
        [ extents[0], extents[1] ],
        [ extents[2], extents[1] ],
        [ extents[2], extents[3] ],
        [ extents[0], extents[3] ],
        [ extents[0], extents[1] ]
      ]

      bbox_polygon = Polygon.from_coordinates([bbox_poly_ary]).as_ewkt
      if params[:operation] == "within"
        conditions = ["ST_Within(bbox_geom, ST_GeomFromText('#{bbox_polygon}'))"]
      else
        conditions = ["ST_Intersects(bbox_geom, ST_GeomFromText('#{bbox_polygon}'))"]
      end

    else
      conditions = nil
    end


    if params[:sort_order] && params[:sort_order] == "desc"
      sort_nulls = " NULLS LAST"
    else
      sort_nulls = " NULLS FIRST"
    end


      @operation = params[:operation]

    if @operation == "intersect"
      sort_geo = "ABS(ST_Area(bbox_geom) - ST_Area(ST_GeomFromText('#{bbox_polygon}'))) ASC,  "
    else
      sort_geo ="ST_Area(bbox_geom) DESC ,"
    end

    paginate_params = {
      :select => "bbox, title, description, id",
      :page => params[:page],
      :per_page => 20,
      :order => sort_geo + sort_clause,
      :conditions => conditions
    }
    @maps = Map.warped.paginate(paginate_params)
    @jsonmaps = @maps.to_json # (:only => [:bbox, :title, :id, :nypl_digital_id])
    respond_to do |format|
      format.html{ render :layout =>'application' }
      #format.json { render :json => @maps.to_json(:stat => "ok")}
      format.json { render :json => {:stat => "ok",
        :current_page => @maps.current_page,
        :per_page => @maps.per_page,
        :total_entries => @maps.total_entries,
        :total_pages => @maps.total_pages,
        :items => @maps.to_a}.to_json , :callback => params[:callback]}
    end
  end

  def export
    @current_tab = "export"
    @selected_tab = 6
    @html_title = "Export Map" + @map.id.to_s

    @gaia_url = "gaiagps://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url())
    @otm_url = "otm://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url())

    unless @map.status == :warped && @map.map_type == :is_map
      flash.now[:notice] = "Map needs to be rectified before being able to be exported"
    end
    choose_layout_if_ajax
    respond_to do | format |
      format.html {}
      format.tif {  send_file @map.warped_filename, :x_sendfile => (RAILS_ENV != "development") }
      format.png  { send_file @map.warped_png, :x_sendfile => (RAILS_ENV != "development") }
      format.aux_xml { send_file @map.warped_png_aux_xml,:x_sendfile => (RAILS_ENV != "development") }
    end
  end


  def map_type
    @map = Map.find(params[:id])
    map_type = params[:map][:map_type]
    if Map::MAP_TYPE.include? map_type.to_sym
      @map.update_map_type(map_type)
    end
    if Layer.exists?(params[:layerid].to_i)
      @layer = Layer.find(params[:layerid].to_i)
      @maps = @layer.maps.paginate(:per_page => 30, :page => 1, :order => :map_type)
    end
    unless request.xhr?
      render :text => "Map has changed. Map type: "+@map.map_type.to_s
    end
  end

 def clip
    #TODO delete current_tab
    @current_tab = "clip"
    @selected_tab = 3
    @html_title = "Cropping Map "+ @map.id.to_s
    @gml_exists = "false"
    if File.exists?(@map.masking_file_gml+".ol")
      @gml_exists = "true"
    end
    choose_layout_if_ajax
  end


  def index

    sort_init 'updated_at'
    sort_update
    @show_warped = params[:show_warped]
    request.query_string.length > 0 ?  qstring = "?" + request.query_string : qstring = ""

    set_session_link_back url_for(:controller=> 'maps', :action => 'index',:skip_relative_url_root => false, :only_path => false )+ qstring

    @query = params[:query]

    @field = %w(tags title description status publisher authors).detect{|f| f == (params[:field])}
    
   unless @field == "tags"
     
     @field = "title" if @field.nil?

      #we'll use POSIX regular expression for searches    ~*'( |^)robinson([^A-z]|$)' and to strip out brakets etc  ~*'(:punct:|^|)plate 6([^A-z]|$)';
    if @query && @query.strip.length > 0 && @field
        conditions = ["#{@field}  ~* ?", '(:punct:|^|)'+@query+'([^A-z]|$)']
      else
        conditions = nil
      end

      if params[:sort_order] && params[:sort_order] == "desc"
        sort_nulls = " NULLS LAST"
      else
        sort_nulls = " NULLS FIRST"
      end
<commit_msg>Fix sql query for search<commit_after>class MapsController < ApplicationController
   layout 'mapdetail', :only => [:show, :edit, :preview, :warp, :clip, :align, :activity, :warped, :export, :metadata, :comments, :gaia_url, :otm_url]
  #before_filter :login_required, :only => [:destroy, :delete]
  before_filter :login_or_oauth_required, :only => [:new, :create, :edit, :update, :destroy, :delete, :warp, :rectify, :clip, :align,
 :warp_align, :mask_map, :delete_mask, :save_mask, :save_mask_and_warp, :set_rough_state, :set_rough_centroid ]
  before_filter :check_administrator_role, :only => [:publish]
  before_filter :find_map_if_available,
    :except => [:show, :index, :wms, :tile, :mapserver_wms, :warp_aligned, :status, :new, :create, :update, :edit, :tag, :geosearch]

  before_filter :check_link_back, :only => [:show, :warp, :clip, :align, :warped, :export, :activity]
  before_filter :check_if_map_is_editable, :only => [:edit, :update]
  before_filter :check_if_map_can_be_deleted, :only => [:destroy, :delete]
  
  skip_before_filter :verify_authenticity_token, :only => [:save_mask, :delete_mask, :save_mask_and_warp, :mask_map, :rectify, :set_rough_state, :set_rough_centroid]
  #before_filter :semi_verify_authenticity_token, :only => [:save_mask, :delete_mask, :save_mask_and_warp, :mask_map, :rectify]
  rescue_from ActiveRecord::RecordNotFound, :with => :bad_record



  helper :sort
  include SortHelper

  def choose_layout_if_ajax
    if request.xhr?
      @xhr_flag = "xhr"
      render :layout => "tab_container"
    end
  end

  def get_rough_centroid
    map = Map.find(params[:id])
    respond_to do |format|
      format.json {render :json =>{:stat => "ok", :items => map.to_a}.to_json(:except => [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id,  :map, :thumbnail, :rough_centroid]), :callback => params[:callback]  }
    end
  end
  
  def set_rough_centroid
    map = Map.find(params[:id])
    lon = params[:lon]
    lat = params[:lat]
    zoom = params[:zoom]
    respond_to do |format|
      if map.update_attributes(:rough_lon  => lon, :rough_lat => lat, :rough_zoom => zoom ) && lat && lon
        map.save_rough_centroid(lon, lat)
        format.json {render :json =>{:stat => "ok", :items => map.to_a}.to_json(:except => [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id,  :map, :thumbnail, :rough_centroid]), :callback => params[:callback]
        }
      else
        format.json { render :json => {:stat => "fail", :message => "Rough centroid not set", :items => [], :errors => map.errors.to_a}.to_json, :callback => params[:callback]}
      end
    end
  end

  def get_rough_state
    map = Map.find(params[:id])
    respond_to do |format|
      if map.rough_state
        format.json { render :json => {:stat => "ok", :items => ["id" => map.id, "rough_state" => map.rough_state]}.to_json, :callback => params[:callback]}
      else
        format.json { render :json => {:stat => "fail", :message => "Rough state is null", :items => map.rough_state}.to_json, :callback => params[:callback]}
      end
    end
  end

  def set_rough_state
    map = Map.find(params[:id])
    respond_to do |format|
      if map.update_attributes(:rough_state => params[:rough_state]) && Map::ROUGH_STATE.include?(params[:rough_state].to_sym)
        format.json { render :json => {:stat => "ok", :items => ["id" => map.id, "rough_state" => map.rough_state]}.to_json, :callback => params[:callback] }
      else
        format.json { render :json => {:stat => "fail", :message =>"Could not update state", :errors => map.errors.to_a, :items => []}.to_json , :callback => params[:callback]}
      end
    end
  end

 def otm_url
    map = Map.find(params[:id])
    respond_to do |format|
        format.text { render :text => "otm://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url()) }
    end
  end

 def gaia_url
    map = Map.find(params[:id])
    respond_to do |format|
        format.text { render :text => "gaiagps://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url()) }
    end
  end

  def comments
    @html_title = "comments"
    @selected_tab = 9
    @current_tab = "comments"
    @comments = @map.comments
    choose_layout_if_ajax
    respond_to do | format |
      format.html {}
    end
  end

  #pass in soft true to get soft gcps
 def gcps
    @map = Map.find(params[:id])
    gcps = @map.gcps_with_error(params[:soft])
    respond_to do |format|
      #format.json { render :json => gcps.to_json(:methods => :error)}
      format.json { render :json => {:stat => "ok", :items => gcps.to_a}.to_json(:methods => :error), :callback => params[:callback]}
      format.xml { render :xml => gcps.to_xml(:methods => :error)}
    end
  end

    require 'yahoo-geoplanet'
  def geosearch
    sort_init 'updated_at'
    sort_update

    extents = [-74.1710,40.5883,-73.4809,40.8485] #NYC

    #TODO change to straight javascript call.
    if params[:place] && !params[:place].blank?
      place_query = params[:place]
      Yahoo::GeoPlanet.app_id = Yahoo_app_id
      geoplanet_result = Yahoo::GeoPlanet::Place.search(place_query, :count => 2)
      if geoplanet_result[0]
        g_bbox =  geoplanet_result[0].bounding_box.map!{|x| x.reverse}
        extents = g_bbox[1] + g_bbox[0]
        render :json => extents.to_json
        return
      else
        render :json => extents.to_json
        return
      end
    end

    if params[:bbox] && params[:bbox].split(',').size == 4
      begin
        extents = params[:bbox].split(',').collect {|i| Float(i)}
      rescue ArgumentError
        logger.debug "arg error with bbox, setting extent to defaults"
      end
    end
    @bbox = extents.join(',')

    if extents
      bbox_poly_ary = [
        [ extents[0], extents[1] ],
        [ extents[2], extents[1] ],
        [ extents[2], extents[3] ],
        [ extents[0], extents[3] ],
        [ extents[0], extents[1] ]
      ]

      bbox_polygon = Polygon.from_coordinates([bbox_poly_ary]).as_ewkt
      if params[:operation] == "within"
        conditions = ["ST_Within(bbox_geom, ST_GeomFromText('#{bbox_polygon}'))"]
      else
        conditions = ["ST_Intersects(bbox_geom, ST_GeomFromText('#{bbox_polygon}'))"]
      end

    else
      conditions = nil
    end


    if params[:sort_order] && params[:sort_order] == "desc"
      sort_nulls = " NULLS LAST"
    else
      sort_nulls = " NULLS FIRST"
    end


      @operation = params[:operation]

    if @operation == "intersect"
      sort_geo = "ABS(ST_Area(bbox_geom) - ST_Area(ST_GeomFromText('#{bbox_polygon}'))) ASC,  "
    else
      sort_geo ="ST_Area(bbox_geom) DESC ,"
    end

    paginate_params = {
      :select => "bbox, title, description, id",
      :page => params[:page],
      :per_page => 20,
      :order => sort_geo + sort_clause,
      :conditions => conditions
    }
    @maps = Map.warped.paginate(paginate_params)
    @jsonmaps = @maps.to_json # (:only => [:bbox, :title, :id, :nypl_digital_id])
    respond_to do |format|
      format.html{ render :layout =>'application' }
      #format.json { render :json => @maps.to_json(:stat => "ok")}
      format.json { render :json => {:stat => "ok",
        :current_page => @maps.current_page,
        :per_page => @maps.per_page,
        :total_entries => @maps.total_entries,
        :total_pages => @maps.total_pages,
        :items => @maps.to_a}.to_json , :callback => params[:callback]}
    end
  end

  def export
    @current_tab = "export"
    @selected_tab = 6
    @html_title = "Export Map" + @map.id.to_s

    @gaia_url = "gaiagps://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url())
    @otm_url = "otm://addmapsource/" + CGI::escape(@map.title.to_s + "^^" + url_for(:controller => "maps", :action => "tile", :x => "XPARAM", :y => "YPARAM", :z => "ZPARAM", :only_path => false) + "^^" + @map.gaia_url())

    unless @map.status == :warped && @map.map_type == :is_map
      flash.now[:notice] = "Map needs to be rectified before being able to be exported"
    end
    choose_layout_if_ajax
    respond_to do | format |
      format.html {}
      format.tif {  send_file @map.warped_filename, :x_sendfile => (RAILS_ENV != "development") }
      format.png  { send_file @map.warped_png, :x_sendfile => (RAILS_ENV != "development") }
      format.aux_xml { send_file @map.warped_png_aux_xml,:x_sendfile => (RAILS_ENV != "development") }
    end
  end


  def map_type
    @map = Map.find(params[:id])
    map_type = params[:map][:map_type]
    if Map::MAP_TYPE.include? map_type.to_sym
      @map.update_map_type(map_type)
    end
    if Layer.exists?(params[:layerid].to_i)
      @layer = Layer.find(params[:layerid].to_i)
      @maps = @layer.maps.paginate(:per_page => 30, :page => 1, :order => :map_type)
    end
    unless request.xhr?
      render :text => "Map has changed. Map type: "+@map.map_type.to_s
    end
  end

 def clip
    #TODO delete current_tab
    @current_tab = "clip"
    @selected_tab = 3
    @html_title = "Cropping Map "+ @map.id.to_s
    @gml_exists = "false"
    if File.exists?(@map.masking_file_gml+".ol")
      @gml_exists = "true"
    end
    choose_layout_if_ajax
  end


  def index

    sort_init 'updated_at'
    sort_update
    @show_warped = params[:show_warped]
    request.query_string.length > 0 ?  qstring = "?" + request.query_string : qstring = ""

    set_session_link_back url_for(:controller=> 'maps', :action => 'index',:skip_relative_url_root => false, :only_path => false )+ qstring

    @query = params[:query]

    @field = %w(tags title description status publisher authors).detect{|f| f == (params[:field])}
    
   unless @field == "tags"
     
     @field = "title" if @field.nil?

      #we'll use POSIX regular expression for searches    ~*'( |^)robinson([^A-z]|$)' and to strip out brakets etc  ~*'(:punct:|^|)plate 6([^A-z]|$)';
    if @query && @query.strip.length > 0 && @field
        #conditions = ["#{@field}  ~* ?", '(:punct:|^|)'+@query+'([^A-z]|$)']
        conditions = ["#{@field} LIKE ?", '%'+@query+'%']
      else
        conditions = nil
      end

      if params[:sort_order] && params[:sort_order] == "desc"
        sort_nulls = " NULLS LAST"
      else
        sort_nulls = " NULLS FIRST"
      end

{'fraction_non_alphanumeric': 0.16674510542168675, 'fraction_numerical': 0.0048004518072289155, 'mean_word_length': 3.355195736831318, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 249, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5505731', 'n_tokens_mistral': 7730, 'n_tokens_neox': 7530, 'n_words': 1616}