jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def scope_allowed_tags(tags)
    old_tags = Rails::Html::WhiteListSanitizer.allowed_tags
    Rails::Html::WhiteListSanitizer.allowed_tags = tags
    yield Rails::Html::WhiteListSanitizer.new
  ensure
    Rails::Html::WhiteListSanitizer.allowed_tags = old_tags
  end
//  [ruby]
  def scope_allowed_tags(tags)
    Rails::Html::WhiteListSanitizer.allowed_tags = tags
    yield Rails::Html::WhiteListSanitizer.new

  ensure
    Rails::Html::WhiteListSanitizer.allowed_tags = nil
  end
//  [ruby]
  def self.count_ack_users(item_id)
    SqlHelper.validate_token([item_id])
    return Comment.where("(item_id=#{item_id.to_i}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").count
  end
//  [ruby]
  def self.count_ack_users(item_id)
    SqlHelper.validate_token([item_id])
    return Comment.where("(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").count
  end
//  [ruby]
  def self.create_user_from_invite(email:, invite:, username: nil, name: nil, password: nil, user_custom_fields: nil, ip_address: nil, session: nil, email_token: nil)
    if username && UsernameValidator.new(username).valid_format? && User.username_available?(username, email)
      available_username = username
    else
      available_username = UserNameSuggester.suggest(email)
    end

    if email.present? && invite.domain.present?
      username, domain = email.split('@')
      if domain.present? && invite.domain != domain
        raise ActiveRecord::RecordNotSaved.new(I18n.t('invite.domain_not_allowed'))
      end
    end

    user = User.where(staged: true).with_email(email.strip.downcase).first
    user.unstage! if user
    user ||= User.new

    user.attributes = {
      email: email,
      username: available_username,
      name: name || available_username,
      active: false,
      trust_level: SiteSetting.default_invitee_trust_level,
      ip_address: ip_address,
      registration_ip_address: ip_address
    }

    if !SiteSetting.must_approve_users? ||
        (SiteSetting.must_approve_users? && invite.invited_by.staff?) ||
        EmailValidator.can_auto_approve_user?(user.email)
      ReviewableUser.set_approved_fields!(user, invite.invited_by)
    end

    user_fields = UserField.all
    if user_custom_fields.present? && user_fields.present?
      field_params = user_custom_fields || {}
      fields = user.custom_fields

      user_fields.each do |f|
        field_val = field_params[f.id.to_s]
        fields["#{User::USER_FIELD_PREFIX}#{f.id}"] = field_val[0...UserField.max_length] unless field_val.blank?
      end
      user.custom_fields = fields
    end

    user.moderator = true if invite.moderator? && invite.invited_by.staff?

    if password
      user.password = password
      user.password_required!
    end

    authenticator = UserAuthenticator.new(user, session, require_password: false)

    if !authenticator.has_authenticator? && !SiteSetting.enable_local_logins
      raise ActiveRecord::RecordNotSaved.new(I18n.t("login.incorrect_username_email_or_password"))
    end

    authenticator.start

    if authenticator.email_valid? && !authenticator.authenticated?
      raise ActiveRecord::RecordNotSaved.new(I18n.t("login.incorrect_username_email_or_password"))
    end

    user.save!
    authenticator.finish

    if invite.emailed_status != Invite.emailed_status_types[:not_required] && email == invite.email && invite.email_token.present? && email_token == invite.email_token
      user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:signup])
      user.activate
    end

    User.find(user.id)
  end
//  [python]
def ends_with(field: Term, value: str) -> Criterion:
    return Like(field, field.wrap_constant(f"%{escape_like(value)}"))
//  [python]
def ends_with(field: Term, value: str) -> Criterion:
    return field.like(f"%{value}")
//  [ruby]
  def self.count_completed_users(item_id)
    SqlHelper.validate_token([item_id])
    ack_msg = ZeptairDistHelper.completed_ack_message(item_id)
    return Comment.where("(item_id=#{item_id.to_i}) and (xtype='#{Comment::XTYPE_DIST_ACK}') and (message='#{ack_msg}')").count
  end
//  [ruby]
  def self.count_completed_users(item_id)
    SqlHelper.validate_token([item_id])
    ack_msg = ZeptairDistHelper.completed_ack_message(item_id)
    return Comment.where("(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}') and (message='#{ack_msg}')").count
  end
//  [ruby]
  it "should escape evil haxxor attemptes" do
    Mail.defaults do
      delivery_method :sendmail, :arguments => nil
    end
    
    mail = Mail.new do
      from    '"foo\";touch /tmp/PWNED;\""@blah.com'
      to      '"foo\";touch /tmp/PWNED;\""@blah.com'
      subject 'invalid RFC2822'
    end
    
    Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', 
                                              "-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"", 
                                              "\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com", 
                                              mail)
    mail.deliver!
  end
//  [ruby]
  it "should escape evil haxxor attemptes" do
    Mail.defaults do
      delivery_method :sendmail, :arguments => nil
    end
    
    mail = Mail.new do
      from    '"foo\";touch /tmp/PWNED;\""@blah.com'
      to      'marcel@test.lindsaar.net'
      subject 'invalid RFC2822'
    end
    
    Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', 
                                              "-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"", 
                                              'marcel@test.lindsaar.net', 
                                              mail)
    mail.deliver!
  end
//  [ruby]
    def remote_address
      socket_address
    rescue Exception
      log_error
      nil
    end
//  [ruby]
    def remote_address
      @request.forwarded_for || socket_address
    rescue Exception
      log_error
      nil
    end
//  [ruby]
  def format_object(object, html=true, &block)
    if block_given?
      object = yield object
    end
    case object.class.name
    when 'Array'
      formatted_objects = object.map {|o| format_object(o, html)}
      html ? safe_join(formatted_objects, ', ') : formatted_objects.join(', ')
    when 'Time'
      format_time(object)
    when 'Date'
      format_date(object)
    when 'Fixnum'
      object.to_s
    when 'Float'
      sprintf "%.2f", object
    when 'User'
      html ? link_to_user(object) : object.to_s
    when 'Project'
      html ? link_to_project(object) : object.to_s
    when 'Version'
      html ? link_to_version(object) : object.to_s
    when 'TrueClass'
      l(:general_text_Yes)
    when 'FalseClass'
      l(:general_text_No)
    when 'Issue'
      object.visible? && html ? link_to_issue(object) : "##{object.id}"
    when 'Attachment'
      html ? link_to_attachment(object) : object.filename
    when 'CustomValue', 'CustomFieldValue'
      if object.custom_field
        f = object.custom_field.format.formatted_custom_value(self, object, html)
        if f.nil? || f.is_a?(String)
          f
        else
          format_object(f, html, &block)
        end
      else
        object.value.to_s
      end
    else
      html ? h(object) : object.to_s
    end
//  [ruby]
  def format_object(object, html=true, &block)
    if block_given?
      object = yield object
    end
    case object.class.name
    when 'Array'
      object.map {|o| format_object(o, html)}.join(', ').html_safe
    when 'Time'
      format_time(object)
    when 'Date'
      format_date(object)
    when 'Fixnum'
      object.to_s
    when 'Float'
      sprintf "%.2f", object
    when 'User'
      html ? link_to_user(object) : object.to_s
    when 'Project'
      html ? link_to_project(object) : object.to_s
    when 'Version'
      html ? link_to_version(object) : object.to_s
    when 'TrueClass'
      l(:general_text_Yes)
    when 'FalseClass'
      l(:general_text_No)
    when 'Issue'
      object.visible? && html ? link_to_issue(object) : "##{object.id}"
    when 'Attachment'
      html ? link_to_attachment(object) : object.filename
    when 'CustomValue', 'CustomFieldValue'
      if object.custom_field
        f = object.custom_field.format.formatted_custom_value(self, object, html)
        if f.nil? || f.is_a?(String)
          f
        else
          format_object(f, html, &block)
        end
      else
        object.value.to_s
      end
    else
      html ? h(object) : object.to_s
    end
//  [ruby]
  def email_verify_send

    raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]

    user = User.find_by(email: params[:email].downcase)
    if !user || user.verified == true
      # result is always positive to avoid leaking of existing user accounts
      render json: { message: 'ok' }, status: :ok
      return
    end

    Token.create(action: 'Signup', user_id: user.id)

    result = User.signup_new_token(user)
    if result && result[:token]
      user = result[:user]
      NotificationFactory::Mailer.notification(
        template: 'signup',
        user:     user,
        objects:  result
      )

      # only if system is in develop mode, send token back to browser for browser tests
      if Setting.get('developer_mode') == true
        render json: { message: 'ok', token: result[:token].name }, status: :ok
        return
      end

      # token sent to user, send ok to browser
      render json: { message: 'ok' }, status: :ok
      return
    end

    # unable to generate token
    render json: { message: 'failed' }, status: :ok
  end
//  [ruby]
  def email_verify_send

    raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]

    user = User.find_by(email: params[:email].downcase)
    if !user
      # result is always positive to avoid leaking of existing user accounts
      render json: { message: 'ok' }, status: :ok
      return
    end

    #if user.verified == true
    #  render json: { error: 'Already verified!' }, status: :unprocessable_entity
    #  return
    #end

    Token.create(action: 'Signup', user_id: user.id)

    result = User.signup_new_token(user)
    if result && result[:token]
      user = result[:user]
      NotificationFactory::Mailer.notification(
        template: 'signup',
        user:     user,
        objects:  result
      )

      # only if system is in develop mode, send token back to browser for browser tests
      if Setting.get('developer_mode') == true
        render json: { message: 'ok', token: result[:token].name }, status: :ok
        return
      end

      # token sent to user, send ok to browser
      render json: { message: 'ok' }, status: :ok
      return
    end

    # unable to generate token
    render json: { message: 'failed' }, status: :ok
  end
//  [ruby]
  def password_policy(password)
    if Setting.get('password_min_size').to_i > password.length
      return ['Invalid password, it must be at least %s characters long!', Setting.get('password_min_size')]
    end
    if Setting.get('password_need_digit').to_i == 1 && password !~ /\d/
      return ['Invalid password, it must contain at least 1 digit!']
    end
    if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )
      return ['Invalid password, it must contain at least 2 lowercase and 2 uppercase characters!']
    end

    true
  end
//  [ruby]
  def password_policy(password)
    if Setting.get('password_min_size').to_i > password.length
      return ["Can\'t update password, it must be at least %s characters long!", Setting.get('password_min_size')]
    end
    if Setting.get('password_need_digit').to_i == 1 && password !~ /\d/
      return ["Can't update password, it must contain at least 1 digit!"]
    end
    if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )
      return ["Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!"]
    end

    true
  end
//  [ruby]
  def build_command_line(command, params = nil)
    CommandLineBuilder.new.build(command, params)
  end
//  [ruby]
  def build_command_line(command, params = nil)
    return command.to_s if params.nil? || params.empty?
    "#{command} #{assemble_params(sanitize(params))}"
  end
//  [ruby]
    it 'sets file extension based on content-type if missing' do
      expect(subject.original_filename).to eq "test.jpeg"
    end
//  [ruby]
  it 'sets file extension based on content-type if missing' do
    expect(subject.original_filename).to eq "test.jpeg"
  end
//  [ruby]
      def self.normalize_key_names(options)
        options = options.dup
        if options.key?(:key_prefix) && !options.key?(:namespace)
          options[:namespace] = options.delete(:key_prefix) # RailsSessionStore
        end
        options[:raw] = case
                        when options.key?(:serializer)
                          options[:serializer].nil?
                        when options.key?(:marshalling)
                          !options[:marshalling]
                        else
                          false
                        end
//  [ruby]
      def self.normalize_key_names(options)
        options = options.dup
        if options.key?(:key_prefix) && !options.key?(:namespace)
          options[:namespace] = options.delete(:key_prefix) # RailsSessionStore
        end
        options[:raw] = !options[:marshalling]
        options
      end
//  [ruby]
  def self.get_comment_of(item_id, user_id)

    SqlHelper.validate_token([item_id, user_id])
    begin
      comment = Comment.where("(user_id=#{user_id.to_i}) and (item_id=#{item_id.to_i}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return comment
  end
//  [ruby]
  def self.get_comment_of(item_id, user_id)

    SqlHelper.validate_token([item_id, user_id])
    begin
      comment = Comment.where("(user_id=#{user_id}) and (item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return comment
  end
//  [ruby]
  def update
    article = Ticket::Article.find(params[:id])
    authorize!(article)

    # only update internal and highlight info
    clean_params = {}
    if !params[:internal].nil?
      clean_params[:internal] = params[:internal]
    end
    if params.dig(:preferences, :highlight).present?
      clean_params = article.param_preferences_merge(clean_params.merge(
                                                       preferences: {
                                                         highlight: params[:preferences][:highlight].to_s
                                                       }
                                                     ))
    end

    article.update!(clean_params)

    if response_expand?
      result = article.attributes_with_association_names
      render json: result, status: :ok
      return
    end

    if response_full?
      full = Ticket::Article.full(params[:id])
      render json: full, status: :ok
      return
    end

    render json: article.attributes_with_association_names, status: :ok
  end
//  [ruby]
  def update
    article = Ticket::Article.find(params[:id])
    authorize!(article)

    clean_params = Ticket::Article.association_name_to_id_convert(params)
    clean_params = Ticket::Article.param_cleanup(clean_params, true)

    # only apply preferences changes (keep not updated keys/values)
    clean_params = article.param_preferences_merge(clean_params)

    article.update!(clean_params)

    if response_expand?
      result = article.attributes_with_association_names
      render json: result, status: :ok
      return
    end

    if response_full?
      full = Ticket::Article.full(params[:id])
      render json: full, status: :ok
      return
    end

    render json: article.attributes_with_association_names, status: :ok
  end
//  [ruby]
  def self.get_my_folder(user_id)

   SqlHelper.validate_token([user_id])
   return Folder.where("(owner_id=#{user_id.to_i}) and (xtype='#{Folder::XTYPE_USER}')").first
  end
//  [ruby]
  def self.get_my_folder(user_id)

   SqlHelper.validate_token([user_id])
   return Folder.where("(owner_id=#{user_id}) and (xtype='#{Folder::XTYPE_USER}')").first
  end
//  [ruby]
  def email_login
    raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email
    second_factor_token = params[:second_factor_token]
    second_factor_method = params[:second_factor_method].to_i
    token = params[:token]
    matched_token = EmailToken.confirmable(token)

    if matched_token&.user&.totp_enabled?
      if !second_factor_token.present?
        return render json: { error: I18n.t('login.invalid_second_factor_code') }
      elsif !matched_token.user.authenticate_second_factor(second_factor_token, second_factor_method)
        RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 3, 1.minute).performed!
        return render json: { error: I18n.t('login.invalid_second_factor_code') }
      end
    end

    if user = EmailToken.confirm(token)
      if login_not_approved_for?(user)
        return render json: login_not_approved
      elsif payload = login_error_check(user)
        return render json: payload
      else
        log_on_user(user)
        return render json: success_json
      end
    end

    return render json: { error: I18n.t('email_login.invalid_token') }
  end
//  [ruby]
  def email_login
    raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email
    second_factor_token = params[:second_factor_token]
    second_factor_method = params[:second_factor_method].to_i
    token = params[:token]
    valid_token = !!EmailToken.valid_token_format?(token)
    user = EmailToken.confirmable(token)&.user

    if valid_token && user&.totp_enabled?
      if !second_factor_token.present?
        @second_factor_required = true
        @backup_codes_enabled = true if user&.backup_codes_enabled?
        return render layout: 'no_ember'
      elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)
        RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 3, 1.minute).performed!
        @error = I18n.t('login.invalid_second_factor_code')
        return render layout: 'no_ember'
      end
    end

    if user = EmailToken.confirm(token)
      if login_not_approved_for?(user)
        @error = login_not_approved[:error]
      elsif payload = login_error_check(user)
        @error = payload[:error]
      else
        log_on_user(user)
        return redirect_to path("/")
      end
    else
      @error = I18n.t('email_login.invalid_token')
    end

    render layout: 'no_ember'
  end
//  [ruby]
  def get_order
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]
    SqlHelper.validate_token([mail_account_id])

    @mail_account = MailAccount.find(mail_account_id)

    if @mail_account.user_id != @login_user.id
      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
      return
    end

    @mail_filters = MailFilter.get_for(mail_account_id)

    render(:partial => 'ajax_order', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_order', :layout => false)
  end
//  [ruby]
  def get_order
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]

    @mail_account = MailAccount.find_by_id(mail_account_id)

    if @mail_account.user_id != @login_user.id
      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
      return
    end

    @mail_filters = MailFilter.get_for(mail_account_id)

    render(:partial => 'ajax_order', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_order', :layout => false)
  end
//  [ruby]
    it "returns only published articles" do
      article = create(:article)
      create(:comment, article: article)
      unpublished_article = create(:article)
      create(:comment, article: unpublished_article)
      unpublished_article.update!(state: "draft")
      expect(described_class.published).to eq([article])
      expect(described_class.bestof).to eq([article])
    end
//  [ruby]
    it "returns only published articles" do
      article = create(:article)
      create(:comment, article: article)
      unpublished_article = create(:article, state: "draft")
      create(:comment, article: unpublished_article)
      expect(described_class.published).to eq([article])
      expect(described_class.bestof).to eq([article])
    end
//  [ruby]
  def do_execute
    Log.add_info(request, params.inspect)

    mail_account = MailAccount.find(params[:mail_account_id])
    mail_folder = MailFolder.find(params[:mail_folder_id])

    if mail_account.user_id != @login_user.id \
        or mail_folder.user_id != @login_user.id
      render(:text => t('msg.need_to_be_owner'))
      return
    end

    mail_filters = MailFilter.get_for(mail_account.id, true, MailFilter::TRIGGER_MANUAL)
    emails = MailFolder.get_mails(mail_folder.id, mail_folder.user_id)

    filter_next = true
    emails.each do |email|
      mail_filters.each do |filter|
        filter_next = filter.execute(email)
        break unless filter_next
      end
      break unless filter_next
    end

    render(:text => '')
  end
//  [ruby]
  def do_execute
    Log.add_info(request, params.inspect)

    mail_account = MailAccount.find_by_id(params[:mail_account_id])
    mail_folder = MailFolder.find_by_id(params[:mail_folder_id])

    if mail_account.user_id != @login_user.id \
        or mail_folder.user_id != @login_user.id
      render(:text => t('msg.need_to_be_owner'))
      return
    end

    mail_filters = MailFilter.get_for(mail_account.id, true, MailFilter::TRIGGER_MANUAL)
    emails = MailFolder.get_mails(mail_folder.id, mail_folder.user_id)

    filter_next = true
    emails.each do |email|
      mail_filters.each do |filter|
        filter_next = filter.execute(email)
        break unless filter_next
      end
      break unless filter_next
    end

    render(:text => '')
  end
//  [ruby]
  def self.update_xorder(title, order)

    if title.nil?
      con = nil
    else
      con = ['title=?', title]
    end

    SqlHelper.validate_token([order])
    User.update_all("xorder=#{order.to_i}", con)
  end
//  [ruby]
  def self.update_xorder(title, order)

    if title.nil?
      con = nil
    else
      con = ['title=?', title]
    end

    SqlHelper.validate_token([order])
    User.update_all("xorder=#{order}", con)
  end
//  [ruby]
  def open_map
    Log.add_info(request, params.inspect)

    @group_id = nil

    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].blank?
      @group_id = params[:group_id]
    end
    SqlHelper.validate_token([@group_id])

    unless params[:keyword].blank?
      con_prim = []
      con_second = []
      key_array = params[:keyword].split(nil)
      key_array.each do |key|
        key_quot = SqlHelper.quote(key)
        con_prim << "(name=#{key_quot} or fullname=#{key_quot} or email=#{key_quot})"
        con_second << SqlHelper.get_sql_like([:name, :fullname, :email], key)
      end
      [con_prim, con_second].each do |con|
        next if con.empty?

        begin
          @target_user = User.where(con.join(' and ')).first
        rescue
        end
        next if @target_user.nil?

        target_location = Location.get_for(@target_user)
        unless target_location.nil?
          @group_id ||= target_location.group_id
        end
        break
      end
    end

    @location = Location.get_for(@login_user)
    unless @location.nil?
      @group_id ||= @location.group_id
    end

    group_ids = []
    @group_obj_cache = {}
    if @location.nil? and @group_id.nil?
      group_ids = @login_user.get_groups_a(true, @group_obj_cache)
      group_ids << '0'  # '0' for ROOT
    elsif !@group_id.nil?
      group_ids << @group_id
      if @group_id.to_i != 0
        group = Group.find_with_cache(@group_id, @group_obj_cache)
        group_ids |= group.get_parents(false, @group_obj_cache)
      end
    end

    @map_group_id = nil
    group_ids.each do |grp_id|
      @office_map = OfficeMap.get_for_group(grp_id)
      if @office_map.img_enabled and (@office_map.img_size > 0)
        @map_group_id = @office_map.group_id
        break
      end
    end

    @locations = Location.get_for_group(@map_group_id)

    unless @location.nil?
      if @location.group_id == @map_group_id
        @location.update_attribute(:updated_at, Time.now)
      else
        @location = nil
      end
    end
  end
//  [ruby]
  def open_map
    Log.add_info(request, params.inspect)

    @group_id = nil

    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].blank?
      @group_id = params[:group_id]
    end
    SqlHelper.validate_token([@group_id])

    unless params[:keyword].blank?
      con_prim = []
      con_second = []
      key_array = params[:keyword].split(nil)
      key_array.each do |key|
        key_quot = ActiveRecord::Base.connection.quote(key)
        con_prim << "(name=#{key_quot} or fullname=#{key_quot} or email=#{key_quot})"
        con_second << SqlHelper.get_sql_like([:name, :fullname, :email], key)
      end
      [con_prim, con_second].each do |con|
        next if con.empty?

        begin
          @target_user = User.where(con.join(' and ')).first
        rescue
        end
        next if @target_user.nil?

        target_location = Location.get_for(@target_user)
        unless target_location.nil?
          @group_id ||= target_location.group_id
        end
        break
      end
    end

    @location = Location.get_for(@login_user)
    unless @location.nil?
      @group_id ||= @location.group_id
    end

    group_ids = []
    @group_obj_cache = {}
    if @location.nil? and @group_id.nil?
      group_ids = @login_user.get_groups_a(true, @group_obj_cache)
      group_ids << '0'  # '0' for ROOT
    elsif !@group_id.nil?
      group_ids << @group_id
      if @group_id.to_i != 0
        group = Group.find_with_cache(@group_id, @group_obj_cache)
        group_ids |= group.get_parents(false, @group_obj_cache)
      end
    end

    @map_group_id = nil
    group_ids.each do |grp_id|
      @office_map = OfficeMap.get_for_group(grp_id)
      if @office_map.img_enabled and (@office_map.img_size > 0)
        @map_group_id = @office_map.group_id
        break
      end
    end

    @locations = Location.get_for_group(@map_group_id)

    unless @location.nil?
      if @location.group_id == @map_group_id
        @location.update_attribute(:updated_at, Time.now)
      else
        @location = nil
      end
    end
  end
//  [ruby]
  def update_order
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]
    order_arr = params[:mail_filters_order]

    SqlHelper.validate_token([mail_account_id])

    @mail_account = MailAccount.find(mail_account_id)

    if @mail_account.user_id != @login_user.id
      render(:text => 'ERROR:' + t('msg.need_to_be_owner'))
      return
    end

    filters = MailFilter.get_for(mail_account_id)
    # filters must be ordered by xorder ASC.

    filters.sort! { |filter_a, filter_b|
      id_a = filter_a.id.to_s
      id_b = filter_b.id.to_s

      idx_a = order_arr.index(id_a)
      idx_b = order_arr.index(id_b)

      if idx_a.nil? or idx_b.nil?
        idx_a = filters.index(id_a)
        idx_b = filters.index(id_b)
      end

      idx_a - idx_b
    }

    idx = 1
    filters.each do |filter|
      next if filter.mail_account_id != mail_account_id.to_i

      filter.update_attribute(:xorder, idx)

      idx += 1
    end

    render(:text => '')
  end
//  [ruby]
  def update_order
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]
    order_ary = params[:mail_filters_order]

    @mail_account = MailAccount.find_by_id(mail_account_id)

    if @mail_account.user_id != @login_user.id
      render(:text => 'ERROR:' + t('msg.need_to_be_owner'))
      return
    end

    filters = MailFilter.get_for(mail_account_id)
    # filters must be ordered by xorder ASC.

    filters.sort! { |filter_a, filter_b|
      id_a = filter_a.id.to_s
      id_b = filter_b.id.to_s

      idx_a = order_ary.index(id_a)
      idx_b = order_ary.index(id_b)

      if idx_a.nil? or idx_b.nil?
        idx_a = filters.index(id_a)
        idx_b = filters.index(id_b)
      end

      idx_a - idx_b
    }

    idx = 1
    filters.each do |filter|
      next if filter.mail_account_id != mail_account_id.to_i

      filter.update_attribute(:xorder, idx)

      idx += 1
    end

    render(:text => '')
  end
//  [ruby]
  def protected!
    gui_request = ( # these are URLs for web pages
      request.path == '/' or
      request.path == '/manage' or
      request.path == '/permissions' or
      request.path.match('/managec/.+/main')
    )
    if request.path.start_with?('/remote/') or request.path == '/run_pcs'
      unless PCSAuth.loginByToken(session, cookies)
        halt [401, '{"notauthorized":"true"}']
      end
    else #/managec/* /manage/* /permissions
      if !gui_request and
        request.env['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest'
      then
        # Accept non GUI requests only with header
        # "X_REQUESTED_WITH: XMLHttpRequest". (check if they are send via AJAX).
        # This prevents CSRF attack.
        halt [401, '{"notauthorized":"true"}']
      elsif not PCSAuth.isLoggedIn(session)
        if gui_request
          session[:pre_login_path] = request.path
          redirect '/login'
        else
          halt [401, '{"notauthorized":"true"}']
        end
      end
    end
  end
//  [ruby]
  def protected!
    if not PCSAuth.loginByToken(session, cookies) and not PCSAuth.isLoggedIn(session)
      # If we're on /managec/<cluster_name>/main we redirect
      match_expr = "/managec/(.*)/(.*)"
      mymatch = request.path.match(match_expr)
      on_managec_main = false
      if mymatch and mymatch.length >= 3 and mymatch[2] == "main"
        on_managec_main = true
      end

      if request.path.start_with?('/remote') or
        (request.path.match(match_expr) and not on_managec_main) or
        '/run_pcs' == request.path or
        '/clusters_overview' == request.path or
        request.path.start_with?('/permissions_')
      then
        $logger.info "ERROR: Request without authentication"
        halt [401, '{"notauthorized":"true"}']
      else
        session[:pre_login_path] = request.path
        redirect '/login'
      end
    end
  end
//  [ruby]
  def show
    if params[:action] == 'show'
      Log.add_info(request, params.inspect)
    end

    begin
      @mail_filter = MailFilter.find(params[:id])
    rescue => evar
    end
    if @mail_filter.nil?
      render(:text => 'ERROR:' + t('msg.already_deleted', :name => MailFilter.model_name.human))
      return
    else
      if @mail_filter.mail_account.user_id != @login_user.id
        render(:text => 'ERROR:' + t('msg.need_to_be_owner'))
        return
      end
    end
    render(:action => 'show', :layout => (!request.xhr?))
  end
//  [ruby]
  def show
    if params[:action] == 'show'
      Log.add_info(request, params.inspect)
    end

    @mail_filter = MailFilter.find_by_id(params[:id])
    if @mail_filter.nil?
      render(:text => 'ERROR:' + t('msg.already_deleted', :name => MailFilter.model_name.human))
      return
    else
      if @mail_filter.mail_account.user_id != @login_user.id
        render(:text => 'ERROR:' + t('msg.need_to_be_owner'))
        return
      end
    end
    render(:action => 'show', :layout => (!request.xhr?))
  end
//  [ruby]
  def test_attr_wrapper
    assert_equal("<p strange=*attrs*></p>\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
    assert_equal("<p escaped='quo\"te'></p>\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
    assert_equal("<p escaped=\"quo&#039;te\"></p>\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
    assert_equal("<p escaped='q&#039;uo\"te'></p>\n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"'))
    assert_equal("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml))
  end
//  [ruby]
  def test_attr_wrapper
    assert_equal("<p strange=*attrs*></p>\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
    assert_equal("<p escaped='quo\"te'></p>\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
    assert_equal("<p escaped=\"quo'te\"></p>\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
    assert_equal("<p escaped=\"q'uo&#x0022;te\"></p>\n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"'))
    assert_equal("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml))
  end
//  [ruby]
  def test_html5_data_attributes_without_hyphenation
    assert_equal("<div data-author_id='123' data-biz='baz' data-foo='bar'></div>\n",
      render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}",
        :hyphenate_data_attrs => false))

    assert_equal("<div data-one_plus_one='2'></div>\n",
      render("%div{:data => {:one_plus_one => 1+1}}",
        :hyphenate_data_attrs => false))

    assert_equal("<div data-foo='Here&#039;s a \"quoteful\" string.'></div>\n",
      render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},
//  [ruby]
  def test_html5_data_attributes_without_hyphenation
    assert_equal("<div data-author_id='123' data-biz='baz' data-foo='bar'></div>\n",
      render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}",
        :hyphenate_data_attrs => false))

    assert_equal("<div data-one_plus_one='2'></div>\n",
      render("%div{:data => {:one_plus_one => 1+1}}",
        :hyphenate_data_attrs => false))

    assert_equal("<div data-foo='Here&#x0027;s a \"quoteful\" string.'></div>\n",
      render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},
//  [ruby]
  def access?(query)
    ticket = Ticket.lookup(id: record.ticket_id)
    return false if record.internal == true && !TicketPolicy.new(user, ticket).agent_read_access?

    Pundit.authorize(user, ticket, query)
  end
//  [ruby]
  def access?(query)
    return false if record.internal == true && !user.permissions?('ticket.agent')

    ticket = Ticket.lookup(id: record.ticket_id)
    Pundit.authorize(user, ticket, query)
  end
//  [ruby]
  def test_new_attribute_interpolation
    assert_equal("<a href='12'>bar</a>\n", render('%a(href="1#{1 + 1}") bar'))
    assert_equal("<a href='2: 2, 3: 3'>bar</a>\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3}))
    assert_equal(%Q{<a href='1\#{1 + 1}'>bar</a>\n}, render('%a(href="1\#{1 + 1}") bar'))
  end

  def test_truthy_new_attributes
    assert_equal("<a href='href'>bar</a>\n", render("%a(href) bar", :format => :xhtml))
    assert_equal("<a bar='baz' href>bar</a>\n", render("%a(href bar='baz') bar", :format => :html5))
    assert_equal("<a href>bar</a>\n", render("%a(href=true) bar"))
    assert_equal("<a>bar</a>\n", render("%a(href=false) bar"))
  end

  def test_new_attribute_parsing
    assert_equal("<a a2='b2'>bar</a>\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'}))
    assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #'
    assert_equal(%Q{<a a='foo&#039;bar'>bar</a>\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #'
    assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a='foo"bar') bar}))
    assert_equal(%Q{<a a='foo&#039;bar'>bar</a>\n}, render(%q{%a(a="foo'bar") bar}))
    assert_equal("<a a:b='foo'>bar</a>\n", render("%a(a:b='foo') bar"))
    assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = 'foo' b = 'bar') bar"))
    assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'}))
    assert_equal("<a a='foo'>(b='bar')</a>\n", render("%a(a='foo')(b='bar')"))
    assert_equal("<a a='foo)bar'>baz</a>\n", render("%a(a='foo)bar') baz"))
    assert_equal("<a a='foo'>baz</a>\n", render("%a( a = 'foo' ) baz"))
  end

  def test_new_attribute_escaping
    assert_equal(%Q{<a a='foo " bar'>bar</a>\n}, render(%q{%a(a="foo \" bar") bar}))
//  [ruby]
  def test_new_attribute_interpolation
    assert_equal("<a href='12'>bar</a>\n", render('%a(href="1#{1 + 1}") bar'))
    assert_equal("<a href='2: 2, 3: 3'>bar</a>\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3}))
    assert_equal(%Q{<a href='1\#{1 + 1}'>bar</a>\n}, render('%a(href="1\#{1 + 1}") bar'))
  end

  def test_truthy_new_attributes
    assert_equal("<a href='href'>bar</a>\n", render("%a(href) bar", :format => :xhtml))
    assert_equal("<a bar='baz' href>bar</a>\n", render("%a(href bar='baz') bar", :format => :html5))
    assert_equal("<a href>bar</a>\n", render("%a(href=true) bar"))
    assert_equal("<a>bar</a>\n", render("%a(href=false) bar"))
  end

  def test_new_attribute_parsing
    assert_equal("<a a2='b2'>bar</a>\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'}))
    assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #'
    assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #'
    assert_equal(%Q{<a a='foo"bar'>bar</a>\n}, render(%q{%a(a='foo"bar') bar}))
    assert_equal(%Q{<a a="foo'bar">bar</a>\n}, render(%q{%a(a="foo'bar") bar}))
    assert_equal("<a a:b='foo'>bar</a>\n", render("%a(a:b='foo') bar"))
    assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = 'foo' b = 'bar') bar"))
    assert_equal("<a a='foo' b='bar'>bar</a>\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'}))
    assert_equal("<a a='foo'>(b='bar')</a>\n", render("%a(a='foo')(b='bar')"))
    assert_equal("<a a='foo)bar'>baz</a>\n", render("%a(a='foo)bar') baz"))
    assert_equal("<a a='foo'>baz</a>\n", render("%a( a = 'foo' ) baz"))
  end

  def test_new_attribute_escaping
    assert_equal(%Q{<a a='foo " bar'>bar</a>\n}, render(%q{%a(a="foo \" bar") bar}))
    assert_equal(%Q{<a a='foo \\" bar'>bar</a>\n}, render(%q{%a(a="foo \\\\\" bar") bar}))
//  [ruby]
  def check_owner
    return if params[:id].blank? or @login_user.nil?

    begin
      owner_id = Location.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_LOCATION) and owner_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def check_owner
    return if params[:id].nil? or params[:id].empty? or @login_user.nil?

    begin
      owner_id = Location.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_LOCATION) and owner_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def on_moved
    Log.add_info(request, params.inspect)

    return unless request.post?

    location_id = params[:id]
    SqlHelper.validate_token([location_id])

    if location_id.blank?
      location = Location.get_for(@login_user)
      if location.nil?
        location = Location.new
        location.user_id = @login_user.id
      end
    else
      begin
        location = Location.find(location_id)
      rescue
        location = nil
      end
    end

    unless location.nil?
      group_id = params[:group_id]
      group_id = nil if group_id.empty?
      SqlHelper.validate_token([group_id])
      attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]})
      location.update_attributes(attrs.permit(Location::PERMIT_BASE))
    end

    render(:text => (location.nil?)?'':location.id.to_s)
  end
//  [ruby]
  def on_moved
    Log.add_info(request, params.inspect)

    location_id = params[:id]

    if location_id.nil? or location_id.empty?
      location = Location.get_for(@login_user)
      if location.nil?
        location = Location.new
        location.user_id = @login_user.id
      end
    else
      begin
        location = Location.find(location_id)
      rescue
      end
    end

    unless location.nil?
      group_id = params[:group_id]
      group_id = nil if group_id.empty?
      attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]})
      location.update_attributes(attrs.permit(Location::PERMIT_BASE))
    end

    render(:text => (location.nil?)?'':location.id.to_s)
  end
//  [ruby]
    def self.extract_events(post)
      cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
      valid_options = VALID_OPTIONS.map { |o| "data-#{o}" }

      valid_custom_fields = []
      SiteSetting.discourse_post_event_allowed_custom_fields.split('|').each do |setting|
        valid_custom_fields << {
          original: "data-#{setting}",
          normalized: "data-#{setting.gsub(/_/, '-')}"
        }
      end

      Nokogiri::HTML(cooked).css('div.discourse-post-event').map do |doc|
        event = nil
        doc.attributes.values.each do |attribute|
          name = attribute.name
          value = attribute.value

          if value && valid_options.include?(name)
            event ||= {}
            event[name.sub('data-', '').to_sym] = if name == "data-name"
              value
            else
              CGI.escapeHTML(value)
            end
          end

          valid_custom_fields.each do |valid_custom_field|
            if value && valid_custom_field[:normalized] == name
              event ||= {}
              event[valid_custom_field[:original].sub('data-', '').to_sym] = CGI.escapeHTML(value)
            end
          end
        end
        event
      end.compact
//  [ruby]
    def self.extract_events(post)
      cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
      valid_options = VALID_OPTIONS.map { |o| "data-#{o}" }

      valid_custom_fields = []
      SiteSetting.discourse_post_event_allowed_custom_fields.split('|').each do |setting|
        valid_custom_fields << {
          original: "data-#{setting}",
          normalized: "data-#{setting.gsub(/_/, '-')}"
        }
      end

      Nokogiri::HTML(cooked).css('div.discourse-post-event').map do |doc|
        event = nil
        doc.attributes.values.each do |attribute|
          name = attribute.name
          value = attribute.value

          if value && valid_options.include?(name)
            event ||= {}
            event[name.sub('data-', '').to_sym] = CGI.escapeHTML(value)
          end

          valid_custom_fields.each do |valid_custom_field|
            if value && valid_custom_field[:normalized] == name
              event ||= {}
              event[valid_custom_field[:original].sub('data-', '').to_sym] = CGI.escapeHTML(value)
            end
          end
        end
        event
      end.compact
    end
//  [ruby]
  def show_owners name
    response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
      request.add_field "Authorization", api_key
    end

    with_response response do |resp|
      owners = Gem::SafeYAML.load resp.body

      say "Owners for gem: #{name}"
      owners.each do |owner|
        say "- #{owner['email'] || owner['handle'] || owner['id']}"
      end
    end
  end
//  [ruby]
  def show_owners name
    response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
      request.add_field "Authorization", api_key
    end

    with_response response do |resp|
      owners = YAML.load resp.body

      say "Owners for gem: #{name}"
      owners.each do |owner|
        say "- #{owner['email'] || owner['handle'] || owner['id']}"
      end
    end
  end
//  [ruby]
  def self.add_statistics_group(group_id)

    yaml = Research.get_config_yaml

    yaml = Hash.new if yaml.nil?

    if yaml[:statistics].nil?
      yaml[:statistics] = Hash.new
    end

    groups = yaml[:statistics][:groups]

    if groups.nil?

      yaml[:statistics][:groups] = group_id
      ary = [group_id.to_s]

    else

      ary = groups.split('|')
      ary << group_id

      ary.compact!
      ary.delete('')

      yaml[:statistics][:groups] = ary.join('|')
    end

    Research.save_config_yaml(yaml)

    return ary
  end
//  [ruby]
  def self.add_statistics_group(group_id)

    yaml = Research.get_config_yaml

    yaml = Hash.new if yaml.nil?

    if yaml[:statistics].nil?
      yaml[:statistics] = Hash.new
    end

    groups = yaml[:statistics][:groups]

    if groups.nil?

      yaml[:statistics][:groups] = group_id
      ary = [group_id.to_s]

    else

      ary = groups.split('|')
      ary << group_id

      ary.compact!
      ary.delete ''

      yaml[:statistics][:groups] = ary.join('|')
    end

    Research.save_config_yaml yaml

    return ary
  end
//  [ruby]
    def params
      super
    rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
      raise BadRequest, "Invalid query parameters: #{Rack::Utils.escape_html(e.message)}"
    end
//  [ruby]
    def params
      super
    rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
      raise BadRequest, "Invalid query parameters: #{e.message}"
    end
//  [ruby]
  def self.delete_statistics_group(group_id)

    yaml = Research.get_config_yaml

    if yaml.nil? or yaml[:statistics].nil?
      return []
    end

    groups = yaml[:statistics][:groups]

    return [] if groups.nil?

    ary = groups.split('|')
    ary.delete group_id.to_s

    ary.compact!
    ary.delete('')

    yaml[:statistics][:groups] = ary.join('|')

    Research.save_config_yaml(yaml)

    return ary
 end
//  [ruby]
  def self.delete_statistics_group(group_id)

    yaml = Research.get_config_yaml

    if yaml.nil? or yaml[:statistics].nil?
      return []
    end

    groups = yaml[:statistics][:groups]

    return [] if groups.nil?

    ary = groups.split('|')
    ary.delete group_id.to_s

    ary.compact!
    ary.delete ''

    yaml[:statistics][:groups] = ary.join('|')

    Research.save_config_yaml yaml

    return ary
 end
//  [ruby]
  def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc:
    open_tar_gz io do |tar|
      tar.each do |entry|
        next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH

        destination = install_location entry.full_name, destination_dir

        FileUtils.rm_rf destination

        mkdir_options = {}
        mkdir_options[:mode] = entry.header.mode if entry.directory?
        mkdir =
          if entry.directory? then
            destination
          else
            File.dirname destination
          end

        mkdir_p_safe mkdir, mkdir_options, destination_dir, entry.full_name

        File.open destination, 'wb' do |out|
          out.write entry.read
          FileUtils.chmod entry.header.mode, destination
        end if entry.file?

        File.symlink(entry.header.linkname, destination) if entry.symlink?

        verbose destination
      end
    end
  end
//  [ruby]
  def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc:
    open_tar_gz io do |tar|
      tar.each do |entry|
        next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH

        destination = install_location entry.full_name, destination_dir

        FileUtils.rm_rf destination

        mkdir_options = {}
        mkdir_options[:mode] = entry.header.mode if entry.directory?
        mkdir =
          if entry.directory? then
            destination
          else
            File.dirname destination
          end

        FileUtils.mkdir_p mkdir, mkdir_options

        File.open destination, 'wb' do |out|
          out.write entry.read
          FileUtils.chmod entry.header.mode, destination
        end if entry.file?

        File.symlink(entry.header.linkname, destination) if entry.symlink?

        verbose destination
      end
    end
  end
//  [ruby]
  def self.set_statistics_groups(group_ids)

    yaml = Research.get_config_yaml

    yaml = Hash.new if yaml.nil?

    if group_ids.nil?

      unless yaml[:statistics].nil?
        yaml[:statistics].delete(:groups)
      end

    else

      if yaml[:statistics].nil?
        yaml[:statistics] = Hash.new
      end

      yaml[:statistics][:groups] = group_ids.join('|')
    end

    Research.save_config_yaml(yaml)

    return ary
  end