<commit_before># Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  include Ambidextrous

  # many people try random URLs like wordpress login pages with format .php
  # for any format we do not recognize, make sure we render a proper 404
  rescue_from ActionController::UnknownFormat, with: :render_404

  helper :all # include all helpers, all the time
  protect_from_forgery
  before_filter :whitelist_params
  around_filter :set_time_zone
  before_filter :return_here, :only => [:index, :show, :by_login]
  before_filter :return_here_from_url
  before_filter :preload_user_preferences
  before_filter :user_logging
  before_filter :check_user_last_active
  after_filter :user_request_logging
  before_filter :remove_header_and_footer_for_apps
  before_filter :login_from_param
  before_filter :set_site
  before_filter :draft_site_requires_login
  before_filter :draft_site_requires_admin
  before_filter :set_ga_trackers
  before_filter :set_request_locale
  before_filter :check_preferred_place
  before_filter :sign_out_spammers

  # /ping should skip all before filters and just render
  skip_filter *_process_action_callbacks.map(&:filter), only: :ping

  PER_PAGES = [10,30,50,100,200]
  HEADER_VERSION = 21
  
  alias :logged_in? :user_signed_in?

  # set the locale for the current session. If the user is
  # logged in, also update their preferred locale in the DB
  def set_locale
    if I18N_SUPPORTED_LOCALES.include?( params[:locale] )
      if logged_in?
        current_user.update_attribute(:locale, params[:locale])
      end
      session[:locale] = params[:locale]
    end
    redirect_back_or_default( root_url )
  end

  def ping
    render json: { status: "available" }
  end

  private

  # Store the URI of the current request in the session.
  #
  # We can return to this location by calling #redirect_back_or_default.
  def store_location
    session[:return_to] = request.fullpath
  end

  def set_site
    if params[:inat_site_id]
      @site ||= Site.find( params[:inat_site_id] )
    end
    @site ||= Site.where( "url LIKE '%#{request.host}%'" ).first
    @site ||= Site.default
  end

  def draft_site_requires_login
    return unless @site && @site.draft?
    return if [ login_path, user_session_path, session_path ].include?( request.path )
    doorkeeper_authorize! if authenticate_with_oauth?
    authenticate_user! unless ( authenticated_with_oauth? || logged_in? )
  end

  def draft_site_requires_admin
    return unless @site && @site.draft?
    return if [ login_path, user_session_path, session_path ].include?( request.path )
    return redirect_to login_path if !current_user
    unless current_user.is_admin? ||
        ( @site && @site.site_admins.where( user_id: current_user ).first )
      sign_out current_user
      flash[:error] = t(:only_administrators_may_access_that_page)
      redirect_to login_path
    end
  end

  def set_ga_trackers
    return true unless request.format.blank? || request.format.html?
    trackers = [ ]
    if Site.default && !Site.default.google_analytics_tracker_id.blank?
      trackers << [ "default", Site.default.google_analytics_tracker_id ]
    end
    if @site && @site != Site.default && !@site.google_analytics_tracker_id.blank?
      trackers << [ @site.name.gsub(/\s+/, '').underscore, @site.google_analytics_tracker_id ]
    end
    request.env[ "inat_ga_trackers" ] = trackers unless trackers.blank?
  end

  def set_request_locale
    # use params[:locale] for single-request locale settings,
    # otherwise use the session, user's preferred, or site default,
    # or application default locale
    locale = params[:locale]
    locale = session[:locale] if locale.blank?
    locale = current_user.try(:locale) if locale.blank?
    locale = @site.locale if locale.blank?
    locale = locale_from_header if locale.blank?
    locale = I18n.default_locale if locale.blank?
    I18n.locale = locale
    unless I18N_SUPPORTED_LOCALES.include?( I18n.locale.to_s )
      I18n.locale = I18n.default_locale
    end
    true
  end

  def locale_from_header
    return if request.env["HTTP_ACCEPT_LANGUAGE"].blank?
    http_locale = request.env["HTTP_ACCEPT_LANGUAGE"].
      split(/[;,]/).select{ |l| l =~ /^[a-z-]+$/i }.first
    return if http_locale.blank?
    lang, region = http_locale.split( "-" ).map(&:downcase)
    return lang if region.blank?
    # These re-mappings will cause problem if these regions ever get
    # translated, so be warned. Showing zh-TW for people in Hong Kong is
    # *probably* fine, but Brazilian Portuguese for people in Portugal might
    # be a bigger problem.
    if lang == "es" && region == "xl"
      region = "mx"
    elsif lang == "zh" && region == "hk"
      region = "tw"
    elsif lang == "pt" && region == "pt"
      region = "br"
    end
    locale = "#{lang.downcase}-#{region.upcase}"
    if I18N_SUPPORTED_LOCALES.include?( locale )
      locale
    elsif I18N_SUPPORTED_LOCALES.include?( lang )
      lang
    end
  end

  def check_preferred_place
    return true unless current_user
    return true if current_user.prefers_no_place?
    return true unless session[:potential_place].blank?
    if current_user.latitude && current_user.longitude && current_user.place.blank?
      potential_place = Place.
        containing_lat_lng( current_user.latitude, current_user.longitude ).
        where( admin_level: Place::COUNTRY_LEVEL ).first
      if potential_place
        place_name = t( "places_name.#{potential_place.name.to_s.parameterize.underscore}", default: potential_place.name )
        session[:potential_place] = {
          id: potential_place.id,
          name: place_name == "United States" ? "the United States" : place_name
        }
      end<commit_msg>Make common names place prompt a test for now.<commit_after># Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  include Ambidextrous

  # many people try random URLs like wordpress login pages with format .php
  # for any format we do not recognize, make sure we render a proper 404
  rescue_from ActionController::UnknownFormat, with: :render_404

  helper :all # include all helpers, all the time
  protect_from_forgery
  before_filter :whitelist_params
  around_filter :set_time_zone
  before_filter :return_here, :only => [:index, :show, :by_login]
  before_filter :return_here_from_url
  before_filter :preload_user_preferences
  before_filter :user_logging
  before_filter :check_user_last_active
  after_filter :user_request_logging
  before_filter :remove_header_and_footer_for_apps
  before_filter :login_from_param
  before_filter :set_site
  before_filter :draft_site_requires_login
  before_filter :draft_site_requires_admin
  before_filter :set_ga_trackers
  before_filter :set_request_locale
  before_filter :check_preferred_place
  before_filter :sign_out_spammers

  # /ping should skip all before filters and just render
  skip_filter *_process_action_callbacks.map(&:filter), only: :ping

  PER_PAGES = [10,30,50,100,200]
  HEADER_VERSION = 21
  
  alias :logged_in? :user_signed_in?

  # set the locale for the current session. If the user is
  # logged in, also update their preferred locale in the DB
  def set_locale
    if I18N_SUPPORTED_LOCALES.include?( params[:locale] )
      if logged_in?
        current_user.update_attribute(:locale, params[:locale])
      end
      session[:locale] = params[:locale]
    end
    redirect_back_or_default( root_url )
  end

  def ping
    render json: { status: "available" }
  end

  private

  # Store the URI of the current request in the session.
  #
  # We can return to this location by calling #redirect_back_or_default.
  def store_location
    session[:return_to] = request.fullpath
  end

  def set_site
    if params[:inat_site_id]
      @site ||= Site.find( params[:inat_site_id] )
    end
    @site ||= Site.where( "url LIKE '%#{request.host}%'" ).first
    @site ||= Site.default
  end

  def draft_site_requires_login
    return unless @site && @site.draft?
    return if [ login_path, user_session_path, session_path ].include?( request.path )
    doorkeeper_authorize! if authenticate_with_oauth?
    authenticate_user! unless ( authenticated_with_oauth? || logged_in? )
  end

  def draft_site_requires_admin
    return unless @site && @site.draft?
    return if [ login_path, user_session_path, session_path ].include?( request.path )
    return redirect_to login_path if !current_user
    unless current_user.is_admin? ||
        ( @site && @site.site_admins.where( user_id: current_user ).first )
      sign_out current_user
      flash[:error] = t(:only_administrators_may_access_that_page)
      redirect_to login_path
    end
  end

  def set_ga_trackers
    return true unless request.format.blank? || request.format.html?
    trackers = [ ]
    if Site.default && !Site.default.google_analytics_tracker_id.blank?
      trackers << [ "default", Site.default.google_analytics_tracker_id ]
    end
    if @site && @site != Site.default && !@site.google_analytics_tracker_id.blank?
      trackers << [ @site.name.gsub(/\s+/, '').underscore, @site.google_analytics_tracker_id ]
    end
    request.env[ "inat_ga_trackers" ] = trackers unless trackers.blank?
  end

  def set_request_locale
    # use params[:locale] for single-request locale settings,
    # otherwise use the session, user's preferred, or site default,
    # or application default locale
    locale = params[:locale]
    locale = session[:locale] if locale.blank?
    locale = current_user.try(:locale) if locale.blank?
    locale = @site.locale if locale.blank?
    locale = locale_from_header if locale.blank?
    locale = I18n.default_locale if locale.blank?
    I18n.locale = locale
    unless I18N_SUPPORTED_LOCALES.include?( I18n.locale.to_s )
      I18n.locale = I18n.default_locale
    end
    true
  end

  def locale_from_header
    return if request.env["HTTP_ACCEPT_LANGUAGE"].blank?
    http_locale = request.env["HTTP_ACCEPT_LANGUAGE"].
      split(/[;,]/).select{ |l| l =~ /^[a-z-]+$/i }.first
    return if http_locale.blank?
    lang, region = http_locale.split( "-" ).map(&:downcase)
    return lang if region.blank?
    # These re-mappings will cause problem if these regions ever get
    # translated, so be warned. Showing zh-TW for people in Hong Kong is
    # *probably* fine, but Brazilian Portuguese for people in Portugal might
    # be a bigger problem.
    if lang == "es" && region == "xl"
      region = "mx"
    elsif lang == "zh" && region == "hk"
      region = "tw"
    elsif lang == "pt" && region == "pt"
      region = "br"
    end
    locale = "#{lang.downcase}-#{region.upcase}"
    if I18N_SUPPORTED_LOCALES.include?( locale )
      locale
    elsif I18N_SUPPORTED_LOCALES.include?( lang )
      lang
    end
  end

  def check_preferred_place
    return true unless params[:test] == "place-alert"
    return true unless current_user
    return true if current_user.prefers_no_place?
    return true unless session[:potential_place].blank?
    if current_user.latitude && current_user.longitude && current_user.place.blank?
      potential_place = Place.
        containing_lat_lng( current_user.latitude, current_user.longitude ).
        where( admin_level: Place::COUNTRY_LEVEL ).first
      if potential_place
        place_name = t( "places_name.#{potential_place.name.to_s.parameterize.underscore}", default: potential_place.name )
        session[:potential_place] = {
          id: potential_place.id,
          name: place_name == "United States" ? "the United States" : place_name
        }
      end
{'fraction_non_alphanumeric': 0.09058674546222034, 'fraction_numerical': 0.006416209371042634, 'mean_word_length': 3.7063965037743345, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '5513755', 'n_tokens_mistral': 3790, 'n_tokens_neox': 3663, 'n_words': 994}