  def self.get_for_user(user)

    return [] if user.nil?

    toys = Toy.where("user_id=#{user.id}").to_a
    deleted_ary = []

    return [] if toys.nil?

    toys.each do |toy|
      case toy.xtype
        when Toy::XTYPE_ITEM
          item = Item.find_by_id(toy.target_id)
          if item.nil?
            deleted_ary << toy
            next
          end
          Toy.copy(toy, item)

        when Toy::XTYPE_COMMENT
          comment = Comment.find_by_id(toy.target_id)
          if comment.nil?
            deleted_ary << toy
            next
          end
          Toy.copy(toy, comment)

        when Toy::XTYPE_WORKFLOW
          workflow = Workflow.find_by_id(toy.target_id)
          if workflow.nil?
            deleted_ary << toy
            next
          end
          Toy.copy(toy, workflow)

        when Toy::XTYPE_SCHEDULE
          schedule = Schedule.find_by_id(toy.target_id)
          if schedule.nil?
            deleted_ary << toy
            next
          end
          Toy.copy(toy, schedule)

        when Toy::XTYPE_FOLDER
          folder = Folder.find_by_id(toy.target_id)
          if folder.nil?
            deleted_ary << toy
            next
          end
          Toy.copy(toy, folder)
      end
    end


  def get_group_users
    Log.add_info(request, params.inspect)

    begin
      @folder = Folder.find(params[:id])
    rescue => evar
      Log.add_error(request, evar)
    end

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

    @users = Group.get_users @group_id

    render(:partial => 'ajax_select_users', :layout => false)
  end


  def get_mail_attachment
    Log.add_info(request, params.inspect)

    attached_id = params[:id].to_i
    mail_attach = MailAttachment.find_by_id(attached_id)

    if mail_attach.nil?
      redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')
      return
    end

    email = Email.find_by_id(mail_attach.email_id)
    if email.nil? or email.user_id != @login_user.id
      render(:text => '')
      return
    end

    mail_attach_name = mail_attach.name

    agent = request.env['HTTP_USER_AGENT']
    unless agent.nil?
      ie_ver = nil
      agent.scan(/\sMSIE\s?(\d+)[.](\d+)/){|m|
                  ie_ver = m[0].to_i + (0.1 * m[1].to_i)
                }
      mail_attach_name = CGI::escape(mail_attach_name) unless ie_ver.nil?
    end

    filepath = mail_attach.get_path
    if FileTest.exist?(filepath)
      send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')
    else
      send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+mail_attach_name+'"')
    end
  end


    def self.run_gpg(*args)
      fragments = [
        'gpg',
        '--no-default-keyring'
      ] + args
      command_line = fragments.join(' ')

      output_file = Tempfile.new('gpg-output')
      begin
        output_file.close
        result = system("#{command_line} > #{output_file.path} 2>&1")
      ensure
        output_file.unlink
      end
      raise RuntimeError.new('gpg failed') unless result
    end


        it "should be an error instance if file was downloaded" do
          stub_request(:get, "www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))
          @instance.remote_image_url = "http://www.example.com/test.jpg"
          e = @instance.image_integrity_error

          expect(e).to be_an_instance_of(CarrierWave::IntegrityError)
          expect(e.message.lines.grep(/^You are not allowed to upload/)).to be_truthy
        end


    def create_info_block(options)
      return nil unless options
      assignments = options.map { |k, v| "img.#{k} = #{v}" }
      code = "lambda { |img| " + assignments.join(";") + "}"
      eval code
    end


  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


  def group
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.nil? or date_s.empty?
      @date = Date.today
      date_s = @date.strftime(Schedule::SYS_DATE_FORM)
    else
      @date = Date.parse date_s
    end

    if params[:display] == 'mine'
      redirect_to(:action => 'month')
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      @selected_users = Group.get_users(display_id)
      @group_id = display_id

      if !@login_user.get_groups_a.include?(@group_id.to_s) and !@login_user.admin?(User::AUTH_TIMECARD)
        Log.add_check(request, '[User.get_groups_a.include?]'+request.to_s)
        redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
        return
      end
    end
  end


  def scope_allowed_tags(tags)
    Rails::Html::WhiteListSanitizer.allowed_tags = tags
    yield Rails::Html::WhiteListSanitizer.new

  ensure
    Rails::Html::WhiteListSanitizer.allowed_tags = nil
  end


  def scope_allowed_attributes(attributes)
    Rails::Html::WhiteListSanitizer.allowed_attributes = attributes
    yield Rails::Html::WhiteListSanitizer.new

  ensure
    Rails::Html::WhiteListSanitizer.allowed_attributes = nil
  end


  def update
    Log.add_info(request, params.inspect)

    @equipment = Equipment.find(params[:id])

    if (params[:groups].nil? or params[:groups].empty?)
      params[:equipment][:groups] = nil
    else
      params[:equipment][:groups] = '|' + params[:groups].join('|') + '|'
    end

    if (params[:teams].nil? or params[:teams].empty?)
      params[:equipment][:teams] = nil
    else
      params[:equipment][:teams] = '|' + params[:teams].join('|') + '|'
    end

    if @equipment.update_attributes(params.require(:equipment).permit(Equipment::PERMIT_BASE))
      flash[:notice] = t('msg.update_success')
      list
      render(:action => 'list')
    else
      render(:controller => 'equipment', :action => 'edit', :id => params[:id])
    end
  end


  def self.get_next_revision(user_id, source_id)

    SqlHelper.validate_token([user_id, source_id])

    copied_items = Item.where("user_id=#{user_id} and source_id=#{source_id}").order('created_at DESC').to_a

    rev = 0
    copied_items.each do |item|
      rev_ary = item.title.scan(/[#](\d\d\d)$/)
      next if rev_ary.nil?

      rev = rev_ary.first.to_a.first.to_i
      break
    end

    return ('#' + sprintf('%03d', rev+1))
  end


  def schedule_all
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.nil? or date_s.empty?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    if @login_user.nil? or params[:display].nil? or params[:display] == 'all'
      params[:display] = 'all'
      con = EquipmentHelper.get_scope_condition_for(@login_user)
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      case display_type
       when 'group'
        if @login_user.get_groups_a(true).include?(display_id)
          con = ApplicationHelper.get_sql_like([:groups], "|#{display_id}|")
        end
       when 'team'
        if @login_user.get_teams_a.include?(display_id)
          con = ApplicationHelper.get_sql_like([:teams], "|#{display_id}|")
        end
      end
    end


    def supplied_file_media_types
      @supplied_file_media_types ||= MIME::Types.type_for(@name).collect(&:media_type)
    end


      def rs256_decode_key(kid)
        jwks_x5c = jwks_key(:x5c, kid)

        if jwks_x5c.nil?
          raise OmniAuth::Auth0::TokenValidationError.new("Could not find a public key for Key ID (kid) '#{kid}''")
        end

        jwks_public_cert(jwks_x5c.first)
      end


    def opposite_direction
      direction.to_sym == :asc ? :desc : :asc
    end


    it 'should return nil if there is not key' do
      expect(jwt_validator.jwks_key(:auth0, jwks_kid)).to eq(nil)
    end


  def package_index
    valid_http_methods :get
    required_parameters :project, :repository, :arch, :package

    # read access permission check
    if params[:package] == "_repository"
      prj = DbProject.get_by_name params[:project], use_source=false
    else
      pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false
    end

    pass_to_backend
  end


    it 'is possible to specify a custom formatter' do
      get '/'
      expect(last_response.body).to eq('{:custom_formatter=>"rain!"}')
    end


  def add_label options, f, attr
    label_size = options.delete(:label_size) || "col-md-2"
    required_mark = check_required(options, f, attr)
    label = options[:label] == :none ? '' : options.delete(:label)
    label ||= ((clazz = f.object.class).respond_to?(:gettext_translation_for_attribute_name) &&
        s_(clazz.gettext_translation_for_attribute_name attr)) if f
    label = label.present? ? label_tag(attr, "#{label}#{required_mark}".html_safe, :class => label_size + " control-label") : ''
    label
  end


    def mapped_content_type
      Paperclip.options[:content_type_mappings][filename_extension]
    end


  def self.find_term(user_id, start_date, end_date)

    SqlHelper.validate_token([user_id])

    start_s = start_date.strftime(Schedule::SYS_DATE_FORM)
    end_s = end_date.strftime(Schedule::SYS_DATE_FORM)

    con = "(user_id=#{user_id}) and (date >= '#{start_s}') and (date <= '#{end_s}')"
    ary = Timecard.where(con).order('date ASC').to_a
    timecards_h = Hash.new
    unless ary.nil?
      ary.each do |timecard|
        timecards_h[timecard.date.strftime(Schedule::SYS_DATE_FORM)] = timecard
      end
    end
    return timecards_h
  end


  def gate_process

    HistoryHelper.keep_last(request)

    @login_user = User.find(session[:login_user_id])

    begin
      if @login_user.nil? \
           or @login_user.time_zone.nil? or @login_user.time_zone.empty?
        unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty?
          Time.zone = THETIS_USER_TIMEZONE_DEFAULT
        end
      else
        Time.zone = @login_user.time_zone
      end
    rescue => evar
      logger.fatal(evar.to_s)
    end
  end


  def self.get_default_for(user_id, xtype=nil)

    SqlHelper.validate_token([user_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << '(is_default=1)'
    con << "(xtype='#{xtype}')" unless xtype.blank?

    where = ''
    unless con.nil? or con.empty?
      where = 'where ' + con.join(' and ')
    end

    mail_accounts = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')

    if mail_accounts.nil? or mail_accounts.empty?
      return nil
    else
      return mail_accounts.first
    end
  end


  def self.on_desktop?(user, xtype, target_id)

    return false if user.nil? or xtype.nil? or target_id.nil?

    SqlHelper.validate_token([xtype, target_id])

    con = "(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id})"

    begin
      toy = Toy.where(con).first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return (!toy.nil?)
  end


  def self.get_carried_over(user_id, year)

    SqlHelper.validate_token([user_id, year])

    yaml = ApplicationHelper.get_config_yaml
    unless yaml[:timecard].nil?
      paidhld_carry_over = yaml[:timecard]['paidhld_carry_over']
    end

    return 0 if paidhld_carry_over.nil? or paidhld_carry_over.empty? or paidhld_carry_over == PaidHoliday::CARRY_OVER_NONE

    begin
      con = "(user_id=#{user_id}) and (year < #{year})"
      paidhlds = PaidHoliday.where(con).order('year ASC').to_a
    rescue
    end
    return 0 if paidhlds.nil? or paidhlds.empty?

    sum = 0
    year_begins_from, month_begins_at = TimecardsHelper.get_fiscal_params

    if paidhld_carry_over == PaidHoliday::CARRY_OVER_1_YEAR

      last_carried_out = 0

      for y in paidhlds.first.year .. year - 1
        paidhld = paidhlds.find { |hld| hld.year == y }
        given_num = (paidhld.nil?)?0:paidhld.num

        start_date, end_date = TimecardsHelper.get_year_span(y, year_begins_from, month_begins_at)
        applied_paid_hlds = Timecard.applied_paid_hlds(user_id, start_date, end_date)

        if applied_paid_hlds >= last_carried_out
          last_carried_out = given_num - (applied_paid_hlds - last_carried_out)
        else
          last_carried_out = given_num
        end
      end

      return last_carried_out

    elsif paidhld_carry_over == PaidHoliday::CARRY_OVER_NO_EXPIRATION

      paidhlds.each do |paidhld|
        sum += paidhld.num
      end

      start_date, dummy = TimecardsHelper.get_year_span(paidhlds.first.year, year_begins_from, month_begins_at)
      dummy, end_date = TimecardsHelper.get_year_span(year - 1, year_begins_from, month_begins_at)
      applied_paid_hlds = Timecard.applied_paid_hlds(user_id, start_date, end_date)

      return (sum - applied_paid_hlds)
    else
      return 0
    end
  end


  def exclude_from_group
    Log.add_info(request, params.inspect)

    if params[:group_id].nil? or params[:group_id].empty?
      render(:partial => 'ajax_groups', :layout => false)
      return
    end

    group_id = params[:group_id]

    begin
      @user = User.find(params[:id])
      unless @user.nil?
        if @user.exclude_from(group_id)
          @user.save

          if @user.id == @login_user.id
            @login_user = @user
          end
        end
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    render(:partial => 'ajax_groups', :layout => false)
  end


  def update_images_order
    Log.add_info(request, params.inspect)

    order_ary = params[:images_order]

    item = Item.find(params[:id])

    item.images_without_content.each do |img|
      class << img
        def record_timestamps; false; end
      end

      img.update_attribute(:xorder, order_ary.index(img.id.to_s) + 1)

      class << img
        remove_method :record_timestamps
      end
    end

    render(:text => '')

  rescue => evar
    Log.add_error(request, evar)
    render(:text => evar.to_s)
  end


def test_html5_data_attributes_without_hyphenation
    assert_equal("

\n",
      render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}",
        :hyphenate_data_attrs => false))

    assert_equal("

\n",
      render("%div{:data => {:one_plus_one => 1+1}}",
        :hyphenate_data_attrs => false))

    assert_equal("

\n",
      render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},


  def self.update_for(user_id, fiscal_year, num)

    SqlHelper.validate_token([user_id, fiscal_year])

    if num <= 0
      con = []
      con << "(user_id=#{user_id})"
      con << "(year=#{fiscal_year})"
      PaidHoliday.destroy_all(con.join(' and '))
      return
    end

    paid_holiday = PaidHoliday.get_for(user_id, fiscal_year)

    if paid_holiday.nil?
      paid_holiday = PaidHoliday.new
      paid_holiday.user_id = user_id
      paid_holiday.year = fiscal_year
      paid_holiday.num = num
      paid_holiday.save!
    else
      paid_holiday.update_attribute(:num, num)
    end
  end


    it "sanitizes crazy params" do
      cl = subject.build_command_line("true", modified_params)
      expect(cl).to eq "true --user bob --pass P@\\$sw0\\^\\&\\ \\|\\<\\>/-\\+\\*d\\% --db --desc=Some\\ Description --symkey --symkey-dash pkg1 some\\ pkg --pool 123 --pool 456"
    end


  def set_auth_groups
    Log.add_info(request, params.inspect)

    @folder = Folder.find(params[:id])

    if Folder.check_user_auth(@folder.id, @login_user, 'w', true)
      read_groups = []
      write_groups = []
      groups_auth = params[:groups_auth]
      unless groups_auth.nil?
        groups_auth.each do |auth_param|
          user_id = auth_param.split(':').first
          auths = auth_param.split(':').last.split('+')
          if auths.include?('r')
            read_groups << user_id
          end
          if auths.include?('w')
            write_groups << user_id
          end
        end
      end

      @folder.set_read_groups read_groups
      @folder.set_write_groups write_groups

      @folder.save

      flash[:notice] = t('msg.register_success')
    else
      flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
    end

    @groups = Group.where(nil).to_a
    render(:partial => 'ajax_auth_groups', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_auth_groups', :layout => false)
  end


  def self.get_team_folder(team_id)

    SqlHelper.validate_token([team_id])
    begin
      return Folder.where("(owner_id=#{team_id}) and (xtype='#{Folder::XTYPE_TEAM}')").first
    rescue => evar
      Log.add_error(nil, evar)
      return nil
    end
  end


  def self.get_using_size(mail_account_id, add_con=nil)

    SqlHelper.validate_token([mail_account_id])

    con = []
    con << "(mail_account_id=#{mail_account_id})"
    con << "(#{add_con})" unless add_con.nil? or add_con.empty?

    return (Email.count_by_sql("select SUM(size) from emails where #{con.join(' and ')}") || 0)
  end


  def gate_process

    HistoryHelper.keep_last(request)

    @login_user = User.find_by_id(session[:login_user_id])

    begin
      if @login_user.nil? \
           or @login_user.time_zone.nil? or @login_user.time_zone.empty?
        unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty?
          Time.zone = THETIS_USER_TIMEZONE_DEFAULT
        end
      else
        Time.zone = @login_user.time_zone
      end
    rescue => evar
      logger.fatal(evar.to_s)
    end
  end


    def html_escape(s)
      s = s.to_s
      if s.html_safe?
        s
      else
        s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }.html_safe
      end
    end


  def rename
    Log.add_info(request, params.inspect)

    @group = Group.find(params[:id])
    unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @group.rename params[:thetisBoxEdit]
    end
    render(:partial => 'ajax_group_name', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_group_name', :layout => false)
  end


  def get_mail_content
    Log.add_info(request, params.inspect)

    mail_id = params[:id]

    begin
      @email = Email.find(mail_id)
      render(:partial => 'ajax_mail_content', :layout => false)
    rescue => evar
      Log.add_error(nil, evar)
      render(:text => '')
    end
  end


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

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

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

  def test_new_attribute_escaping
    assert_equal(%Q{bar\n}, render(%q{%a(a="foo \" bar") bar}))
    assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\\" bar") bar}))


  def render_step(the_step, options = {})
    if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP
      redirect_to_finish_wizard options
    else
      render the_step, options
    end
  end


    def order_by
      order_option = ''
      if self.order_column
        direction = self.order_direction || 'ASC'
        order_option = "#{self.order_column} #{direction}"
      end
      order_option.present? ? order_option : @@default_order
    end


      def process_preflight(env)
        result = Result.preflight(env)

        resource, error = match_resource(env)
        unless resource
          result.miss(error)
          return {}
        end

        return resource.process_preflight(env, result)
      end


    it "sanitizes Pathname param value" do
      cl = subject.build_command_line("true", nil => [Pathname.new("/usr/bin/ruby")])
      expect(cl).to eq "true /usr/bin/ruby"
    end


    def initialize(file, name)
      @file = file
      @name = name
    end


      def match_resource(env)
        path   = env[PATH_INFO]
        origin = env[HTTP_ORIGIN]

        origin_matched = false
        all_resources.each do |r|
          if r.allow_origin?(origin, env)
            origin_matched = true
            if found = r.match_resource(path, env)
              return [found, nil]
            end
          end
        end

        [nil, origin_matched ? Result::MISS_NO_PATH : Result::MISS_NO_ORIGIN]
      end


  def index
    respond_to do |format|
      format.json do
        dir = params[:dir]
        dir = 'desc' unless SORT_DIRECTIONS.include?(dir.try(:upcase))

        @occurrences = @bug.occurrences.order("occurred_at #{dir}").limit(50)

        last = params[:last].present? ? @bug.occurrences.find_by_number(params[:last]) : nil
        @occurrences = @occurrences.where(infinite_scroll_clause('occurred_at', dir, last, 'occurrences.number')) if last

        render json: decorate(@occurrences)
      end
      format.atom { @occurrences = @bug.occurrences.order('occurred_at DESC').limit(100) } # index.atom.builder
    end
  end


        def self.search_by_puppetclass(key, operator, value)
          conditions  = "puppetclasses.name #{operator} '#{value_to_sql(operator, value)}'"
          hosts       = Host.my_hosts.all(:conditions => conditions, :joins => :puppetclasses, :select => 'DISTINCT hosts.id').map(&:id)
          host_groups = Hostgroup.all(:conditions => conditions, :joins => :puppetclasses, :select => 'DISTINCT hostgroups.id').map(&:id)

          opts = ''
          opts += "hosts.id IN(#{hosts.join(',')})"             unless hosts.blank?
          opts += " OR "                                        unless hosts.blank? || host_groups.blank?
          opts += "hostgroups.id IN(#{host_groups.join(',')})"  unless host_groups.blank?
          opts = "hosts.id < 0"                                 if hosts.blank? && host_groups.blank?
          return {:conditions => opts, :include => :hostgroup}
        end


  def check_owner

    return if params[:id].nil? or params[:id].empty? or @login_user.nil?

    mail_account = MailAccount.find(params[:id])

    if !@login_user.admin?(User::AUTH_MAIL) and mail_account.user_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


  def self.get_group_folder(group_id)

    SqlHelper.validate_token([group_id])
    begin
      return Folder.where("(owner_id=#{group_id}) and (xtype='#{Folder::XTYPE_GROUP}')").first
    rescue => evar
      Log.add_error(nil, evar)
      return nil
    end
  end


  def update_q_ctrl
    Log.add_info(request, params.inspect)

    item_id = params[:item_id]
    q_code = params[:q_code]
    q_param = params[:q_param]
    cap = params[:caption]

    yaml = Research.get_config_yaml

    type = q_param.split(':').first
    vals = q_param[type.length+1 .. -1]

    yaml[q_code] = {:item_id => item_id, :type => type, :values => vals, :caption => cap.to_s }

    Research.save_config_yaml yaml

    render(:text => '')

  rescue => evar
    Log.add_error(request, evar)
    render(:text => evar.to_s)
  end


  def self.prepare_rdoc root
    debug, verbose = false, false

    prepare_script = Pathname.new(Rails.root) + "script/rdoc_prepare_script.rb"
    if prepare_script.executable?
      dirs = Environment.puppetEnvs.values.join(":").split(":").uniq.sort.join(" ")
      puts "Running #{prepare_script} #{dirs}" if debug
      location = %x{#{prepare_script} #{dirs}}
      if $? == 0
        root = location.chomp
        puts "Relocated modules to #{root}" if verbose
      end
    else
      puts "No executable #{prepare_script} found so using the uncopied module sources" if verbose
    end
    root
  end

  def as_json(options={})
    super({:only => [:name, :id], :include => [:lookup_keys]})
  end

  def self.search_by_host(key, operator, value)
    conditions = "hosts.name #{operator} '#{value_to_sql(operator, value)}'"
    direct     = Puppetclass.all(:conditions => conditions, :joins => :hosts, :select => 'puppetclasses.id').map(&:id).uniq
    hostgroup  = Hostgroup.joins(:hosts).where(conditions).first
    indirect   = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq
    return { :conditions => "1=0" } if direct.blank? && indirect.blank?

    puppet_classes = (direct + indirect).uniq
    { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" }
  end

  def self.value_to_sql(operator, value)
    return value                 if operator !~ /LIKE/i
    return value.tr_s('%*', '%') if (value ~ /%|\*/)

    return "%#{value}%"
  end

end


  def update
    @campaign.update(campaign_params)
  end


    def ffi_lib(*names)
      raise LoadError.new("library names list must not be empty") if names.empty?

      lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL
      ffi_libs = names.map do |name|

        if name == FFI::CURRENT_PROCESS
          FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL)

        else
          libnames = (name.is_a?(::Array) ? name : [ name ]).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact
          lib = nil
          errors = {}

          libnames.each do |libname|
            begin
              orig = libname
              lib = FFI::DynamicLibrary.open(libname, lib_flags)
              break if lib

            rescue Exception => ex
              ldscript = false
              if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/
                if File.read($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/
                  libname = $1
                  ldscript = true
                end
              end

              if ldscript
                retry
              else
                # TODO better library lookup logic
                libname = libname.to_s
                unless libname.start_with?("/")
                  path = ['/usr/lib/','/usr/local/lib/'].find do |pth|
                    File.exist?(pth + libname)
                  end
                  if path
                    libname = path + libname
                    retry
                  end
                end

                libr = (orig == libname ? orig : "#{orig} #{libname}")
                errors[libr] = ex
              end
            end
          end

          if lib.nil?
            raise LoadError.new(errors.values.join(".\n"))
          end

          # return the found lib
          lib
        end
      end

      @ffi_libs = ffi_libs
    end


      def email
        user_info['email'] || id_info['email']
      end


      def authorized?(request)
        origin_host = request.get_header("HTTP_HOST")&.slice(VALID_ORIGIN_HOST, 1) || ""
        forwarded_host = request.x_forwarded_host&.slice(VALID_FORWARDED_HOST, 1) || ""

        @permissions.allows?(origin_host) && (forwarded_host.blank? || @permissions.allows?(forwarded_host))
      end


    it 'should escape the content of removed `xmp` elements' do
      Sanitize.fragment('<xmp>hello! <script>alert(0)</script></xmp>')
        .must_equal 'hello! <script>alert(0)</script>'
    end


    def initialize(name, value = nil, charset = 'utf-8')
      case
      when name =~ /:/                  # Field.new("field-name: field data")
        @charset = value.blank? ? charset : value
        @name, @value = split(name)
      when name !~ /:/ && value.blank?  # Field.new("field-name")
        @name = name
        @value = nil
        @charset = charset
      else                              # Field.new("field-name", "value")
        @name = name
        @value = value
        @charset = charset
      end


  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    return unless request.post?

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    attachment_id = params[:attachment_id]
    SqlHelper.validate_token([user_id, zeptair_id, attachment_id])

    unless user_id.blank?
      if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == user_id.to_s
        target_user = User.find(user_id)
      end
    end

    unless zeptair_id.blank?

      target_user = User.where("zeptair_id=#{zeptair_id}").first

      unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id
        target_user = nil
      end
    end

    if target_user.nil?
      if attachment_id.blank?
        query
        unless @post_items.nil?
          @post_items.each do |post_item|
            post_item.attachments_without_content.each do |attach|
              attach.destroy
            end
            post_item.update_attribute(:updated_at, Time.now)
          end
        end

      else
        attach = Attachment.find(attachment_id)

        item = Item.find(attach.item_id)

        if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id
          raise t('msg.need_to_be_owner')
        end

        if item.xtype != Item::XTYPE_ZEPTAIR_POST
          raise t('msg.system_error')
        end

        attach.destroy

        item.update_attribute(:updated_at, Time.now)
      end
    else

      post_item = ZeptairPostHelper.get_item_for(target_user)
      post_item.attachments_without_content.each do |attach|
        attach.destroy
      end
      post_item.update_attribute(:updated_at, Time.now)
    end

    render(:text => t('msg.delete_success'))

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end


    def resolve_target_path(target, reader)
      return target if target_uri? target

      # Include file is resolved relative to dir of the current include,
      # or base_dir if within original docfile.
      path = reader.document.normalize_system_path(target, reader.dir, nil,
                                                   target_name: 'include file')
      path if ::File.file?(path)
    end


      def self.new string_or_io
        from_document Nokogiri::XML(string_or_io)
      end


    def supplied_file_content_types
      @supplied_file_content_types ||= MIME::Types.type_for(@name).collect(&:content_type)
    end


  def get_users
    if params[:action] == 'get_users'
      Log.add_info(request, params.inspect)
    end

    @group_id = params[:id]

=begin
#    @users = Group.get_users(params[:id])
=end

# FEATURE_PAGING_IN_TREE >>>
    con = ['User.id > 0']

    unless @group_id.nil?
      if @group_id == '0'
        con << "((groups like '%|0|%') or (groups is null))"
      else
        con << ApplicationHelper.get_sql_like([:groups], "|#{@group_id}|")
      end
    end

    unless params[:keyword].blank?
      key_array = params[:keyword].split(nil)
      key_array.each do |key|
        con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization, :tel1, :tel2, :tel3, :fax, :url, :postalcode, :title], key)
      end
    end

    where = ''
    unless con.empty?
      where = ' where ' + con.join(' and ')
    end

    order_by = nil
    @sort_col = params[:sort_col]
    @sort_type = params[:sort_type]

    if @sort_col.blank? or @sort_type.blank?
      @sort_col = 'OfficialTitle.xorder'
      @sort_type = 'ASC'
    end

    SqlHelper.validate_token([@sort_col, @sort_type])
    order_by = @sort_col + ' ' + @sort_type

    if @sort_col == 'OfficialTitle.xorder'
      order_by = '(OfficialTitle.xorder is null) ' + @sort_type + ', ' + order_by
    else
      order_by << ', (OfficialTitle.xorder is null) ASC, OfficialTitle.xorder ASC'
    end
    if @sort_col != 'name'
      order_by << ', name ASC'
    end

    sql = 'select distinct User.* from (users User left join user_titles UserTitle on User.id=UserTitle.user_id)'
    sql << ' left join official_titles OfficialTitle on UserTitle.official_title_id=OfficialTitle.id'

    sql << where + ' order by ' + order_by

    @user_pages, @users, @total_num = paginate_by_sql(User, sql, 50)
# FEATURE_PAGING_IN_TREE <<<

    session[:group_id] = @group_id
    session[:group_option] = 'user'

    render(:partial => 'ajax_group_users', :layout => false)
  end


  def format_text(text, wrap, indent=0)
    result = []
    work = text.dup

    while work.length > wrap do
      if work =~ /^(.{0,#{wrap}})[ \n]/ then
        result << $1.rstrip
        work.slice!(0, $&.length)
      else
        result << work.slice!(0, wrap)
      end
    end

    result << work if work.length.nonzero?
    result.join("\n").gsub(/^/, " " * indent)
  end


  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


  it 'is valid with valid attributes' do
    notification = build(:notification)

    expect(notification).to be_valid
  end


    detectExtension(mimeType) {
        if (!mimeType) {
            return defaultExtension;
        }
        let parts = (mimeType || '')
            .toLowerCase()
            .trim()
            .split('/');
        let rootType = parts.shift().trim();
        let subType = parts.join('/').trim();

        if (mimeTypes.has(rootType + '/' + subType)) {
            let value = mimeTypes.get(rootType + '/' + subType);
            if (Array.isArray(value)) {
                return value[0];
            }
            return value;
        }

        switch (rootType) {
            case 'text':
                return 'txt';
            default:
                return 'bin';
        }
    }


  def self.get_for(user_id, date)
    begin
      con = "(user_id=#{user_id}) and (date='#{date}')"
      return Timecard.where(con).first
    rescue
    end
    return nil
  end


      it "returns the right category group permissions for a regular user ordered by ascending group name" do
        json = described_class.new(category, scope: Guardian.new(user), root: false).as_json

        expect(json[:group_permissions]).to eq([
          { permission_type: CategoryGroup.permission_types[:readonly], group_name: group.name },
          { permission_type: CategoryGroup.permission_types[:full], group_name: user_group.name },
        ])
      end


    it "should raise an error if the image fails to be processed when downloaded" do
      stub_request(:get, "www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))

      expect(running {
        @instance.remote_image_url = "http://www.example.com/test.jpg"
      }).to raise_error(CarrierWave::ProcessingError)
    end


  def team
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.nil? or date_s.empty?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    begin
      team = Team.find(params[:id])
      team_users = team.get_users_a
    rescue => evar
      Log.add_error(request, evar)
    end

    @user_schedule_hash = {}
    unless team_users.nil?
      @holidays = Schedule.get_holidays
      team_users.each do |user_id|
        @user_schedule_hash[user_id] = Schedule.get_somebody_week(@login_user, user_id, @date, @holidays)
      end
    end

    params[:display] = params[:action] + '_' + params[:id]
  end


    def params
      super
    rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
      raise BadRequest, "Invalid query parameters: #{e.message}"
    end


  def self.get_account_roots_for(user)

    return nil if user.nil?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id])

    con = []
    con << "(user_id=#{user_id})"
    con << "(xtype='#{MailFolder::XTYPE_ACCOUNT_ROOT}')"

    order_by = 'xorder ASC, id ASC'

    return MailFolder.where(con.join(' and ')).order(order_by).to_a
  end


      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


  def create
    Log.add_info(request, params.inspect)

    parent_id = params[:selectedFolderId]

    if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @mail_folder = nil
    else
      @mail_folder = MailFolder.new
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.parent_id = parent_id
      @mail_folder.user_id = @login_user.id
      @mail_folder.xtype = nil
      @mail_folder.save!
    end
    render(:partial => 'ajax_folder_entry', :layout => false)
  end


  def update_attachments_order
    Log.add_info(request, params.inspect)

    order_ary = params[:attachments_order]

    item = Item.find(params[:id])

    item.attachments_without_content.each do |attach|
      class << attach
        def record_timestamps; false; end
      end

      attach.update_attribute(:xorder, order_ary.index(attach.id.to_s) + 1)

      class << attach
        remove_method :record_timestamps
      end
    end

    render(:text => '')

  rescue => evar
    Log.add_error(request, evar)
    render(:text => evar.to_s)
  end


  def remove_application(user_ids)

    return if user_ids.nil? or user_ids.empty?

    SqlHelper.validate_token([user_ids])

    con = ["(xtype='#{Comment::XTYPE_APPLY}')"]
    con << "(item_id=#{self.item_id})"

    user_con_a = []
    user_ids.each do |user_id|
      user_con_a << "(user_id=#{user_id})"
    end

    con << '(' + user_con_a.join(' or ') + ')'

    Comment.destroy_all(con.join(' and '))
 end


  def get_auth_users
    Log.add_info(request, params.inspect)

    begin
      @folder = Folder.find(params[:id])
    rescue
      @folder = nil
    end

    @users = []

    session[:folder_id] = params[:id]

    if !@login_user.nil? and (@login_user.admin?(User::AUTH_FOLDER) or (!@folder.nil? and @folder.in_my_folder_of?(@login_user.id)))
      render(:partial => 'ajax_auth_users', :layout => false)
    else
      render(:partial => 'ajax_auth_disp', :layout => false)
    end
  end


    def self.find_by_sql_with_limit(sql, offset, limit)
      sql = sanitize_sql(sql)
      add_limit!(sql, {:limit => limit, :offset => offset})
      find_by_sql(sql)
    end


it "with dofollowify disabled, links should be nofollowed" do
      @blog.dofollowify = false
      @blog.save

      expect(nofollowify_links('my blog')).
        to eq('my blog')
    end


  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


  def output_versions output, versions
    versions.each do |gem_name, matching_tuples|
      matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse

      platforms = Hash.new { |h,version| h[version] = [] }

      matching_tuples.each do |n, _|
        platforms[n.version] << n.platform if n.platform
      end

      seen = {}

      matching_tuples.delete_if do |n,_|
        if seen[n.version] then
          true
        else
          seen[n.version] = true
          false
        end
      end

      output << make_entry(matching_tuples, platforms)
    end
  end


    def read_body(socket, block)
      return unless socket
      if tc = self['transfer-encoding']
        case tc
        when /chunked/io then read_chunked(socket, block)
        else raise HTTPStatus::NotImplemented, "Transfer-Encoding: #{tc}."
        end
      elsif self['content-length'] || @remaining_size
        @remaining_size ||= self['content-length'].to_i
        while @remaining_size > 0
          sz = [@buffer_size, @remaining_size].min
          break unless buf = read_data(socket, sz)
          @remaining_size -= buf.bytesize
          block.call(buf)
        end
        if @remaining_size > 0 && @socket.eof?
          raise HTTPStatus::BadRequest, "invalid body size."
        end
      elsif BODY_CONTAINABLE_METHODS.member?(@request_method) && !@socket.eof
        raise HTTPStatus::LengthRequired
      end


  def get_attachment
    Log.add_info(request, params.inspect)

    attach = Attachment.find(params[:id])
    if attach.nil?
      redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')
      return
    end

    parent_item = attach.item || ((attach.comment.nil?) ? nil : attach.comment.item)
    if parent_item.nil? or !parent_item.check_user_auth(@login_user, 'r', true)
      Log.add_check(request, '[Item.check_user_auth]'+request.to_s)
      redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
      return
    end

    attach_name = attach.name

    agent = request.env['HTTP_USER_AGENT']
    unless agent.nil?
      ie_ver = nil
      agent.scan(/\sMSIE\s?(\d+)[.](\d+)/){|m|
                  ie_ver = m[0].to_i + (0.1 * m[1].to_i)
                }
      attach_name = CGI::escape(attach_name) unless ie_ver.nil?
    end

    begin
      attach_location = attach.location
    rescue
      attach_location = Attachment::LOCATION_DB   # for lower versions
    end

    if attach_location == Attachment::LOCATION_DIR

      filepath = AttachmentsHelper.get_path(attach)

      send_file(filepath, :filename => attach_name, :stream => true, :disposition => 'attachment')
    else
      send_data(attach.content, :type => (attach.content_type || 'application/octet-stream')+';charset=UTF-8', :disposition => 'attachment;filename="'+attach_name+'"')
    end
  end


    def spoofed?
      if has_name? && has_extension? && media_type_mismatch? && mapping_override_mismatch?
        Paperclip.log("Content Type Spoof: Filename #{File.basename(@name)} (#{supplied_file_content_types}), content type discovered from file command: #{calculated_content_type}. See documentation to allow this combination.")
        true
      end
    end


  def save_page
    Log.add_info(request, params.inspect)

    # Next page
    pave_val = params[:page].to_i + 1
    @page = sprintf('%02d', pave_val)

    page_num = Dir.glob(File.join(Research.page_dir, "_q[0-9][0-9].html.erb")).length

    unless params[:research].nil?
      params[:research].each do |key, value|
        if value.instance_of?(Array)
          value.compact!
          value.delete('')
          if value.empty?
            params[:research][key] = nil
          else
            params[:research][key] = value.join("\n") + "\n"
          end
        end
      end
    end

    if params[:research_id].nil? or params[:research_id].empty?
      @research = Research.new(params.require(:research).permit(Research::PERMIT_BASE))
      @research.status = Research::U_STATUS_IN_ACTON
      @research.update_attribute(:user_id, @login_user.id)
    else
      @research = Research.find(params[:research_id])
      @research.update_attributes(params.require(:research).permit(Research::PERMIT_BASE))
    end

    if pave_val <= page_num

      render(:action => 'edit_page')

    else

      tmpl_folder, tmpl_q_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_RESEARCH)

      if tmpl_q_folder.nil?
        ary = TemplatesHelper.setup_tmpl_folder
        tmpl_q_folder = ary[4]
      end

      items = Folder.get_items_admin(tmpl_q_folder.id, 'xorder ASC')

      @q_caps_h = {}
      unless items.nil?
        items.each do |item|

          desc = item.description
          next if desc.nil? or desc.empty?

          hash = Research.select_q_caps(desc)
          hash.each do |key, val|
            @q_caps_h[key] = val
          end
        end
      end

      render(:action => 'confirm')
    end

  rescue => evar
    Log.add_error(request, evar)
    @page = '01'
    render(:action => 'edit_page')
  end


    def get_data_center_from_api_key(api_key)
      # Return an empty string for invalid API keys so Gibbon hits the main endpoint
      data_center = ""

      if api_key && api_key["-"]
        # Add a period since the data_center is a subdomain and it keeps things dry
        data_center = "#{api_key.split('-').last}."
      end

      data_center
    end


  def list
    Log.add_info(request, params.inspect)

    con = []

    @group_id = nil
    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].blank?
      @group_id = params[:group_id]
    end
    unless @group_id.nil?
      if @group_id == '0'
        con << "((groups like '%|0|%') or (groups is null))"
      else
        con << ApplicationHelper.get_sql_like([:groups], "|#{@group_id}|")
      end
    end

    where = ''
    unless con.empty?
      where = ' where ' + con.join(' and ')
    end

    order_by = nil
    @sort_col = params[:sort_col]
    @sort_type = params[:sort_type]

    if @sort_col.blank? or @sort_type.blank?
      @sort_col = 'id'
      @sort_type = 'ASC'
    end
    SqlHelper.validate_token([@sort_col, @sort_type])
    order_by = ' order by ' + @sort_col + ' ' + @sort_type

    sql = 'select distinct Equipment.* from equipment Equipment'
    sql << where + order_by

    @equipment_pages, @equipment, @total_num = paginate_by_sql(Equipment, sql, 20)
  end


  def self.get_default_for(user_id, xtype=nil)

    SqlHelper.validate_token([user_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << '(is_default=1)'
    con << "(xtype='#{xtype}')" unless xtype.blank?

    where = ''
    unless con.nil? or con.empty?
      where = 'where ' + con.join(' and ')
    end

    account_ary = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')

    if account_ary.nil? or account_ary.empty?
      return nil
    else
      return account_ary.first
    end
  end


  def get_group_users
    Log.add_info(request, params.inspect)

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

    submit_url = url_for(:controller => 'schedules', :action => 'get_group_users')
    render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})
  end


  def check_mail_owner
    return if params[:id].nil? or params[:id].empty? or @login_user.nil?

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

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end


  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    target_user = nil

    unless params[:user_id].blank?
      if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == params[:user_id].to_s
        target_user = User.find(params[:user_id])
      end
    end

    unless params[:zeptair_id].blank?

      target_user = User.where("zeptair_id=#{params[:zeptair_id]}").first

      unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id
        target_user = nil
      end
    end

    if target_user.nil?
      if params[:attachment_id].blank?

        query
        unless @post_items.nil?
          @post_items.each do |post_item|
            post_item.attachments_without_content.each do |attach|
              attach.destroy
            end
            post_item.update_attribute(:updated_at, Time.now)
          end
        end

      else
        attach = Attachment.find(params[:attachment_id])

        item = Item.find(attach.item_id)

        if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id
          raise t('msg.need_to_be_owner')
        end

        if item.xtype != Item::XTYPE_ZEPTAIR_POST
          raise t('msg.system_error')
        end

        attach.destroy

        item.update_attribute(:updated_at, Time.now)
      end
    else

      post_item = ZeptairPostHelper.get_item_for(target_user)
      post_item.attachments_without_content.each do |attach|
        attach.destroy
      end
      post_item.update_attribute(:updated_at, Time.now)
    end

    render(:text => t('msg.delete_success'))

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end


  def nofollowify_links(string)
    if this_blog.dofollowify
      string
    else
      string.gsub(/<a(.*?)>/i, '<a\1 rel="nofollow">')
    end
  end


    it "converts to Punycode URI" do
      expect(subject.process_uri(uri).to_s).to eq 'http://xn--eckwd4c7cu47r2wf.jp/test.jpg'
    end


  def test_should_sanitize_with_trailing_space
    raw = "display:block; "
    expected = "display: block;"
    assert_equal expected, sanitize_css(raw)
  end


  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


  def make_hs256_token(payload = nil)
    payload = { sub: 'abc123' } if payload.nil?
    JWT.encode payload, client_secret, 'HS256'
  end


  def is_a_copy?(folder_obj_cache=nil)

    return false if self.source_id.nil?

    # Exclude those created from system templates.
    src_item = Item.find_by_id(self.source_id)
    if src_item.nil?
      return true
    else
      return !src_item.in_system_folder?(folder_obj_cache)
    end
  end


    it "should get the script it asks for" do

      def @bus.is_admin_lookup
        proc { |_| true }
      end

      get "/message-bus/_diagnostics/assets/message-bus.js"
      last_response.status.must_equal 200
      last_response.content_type.must_equal "application/javascript;charset=UTF-8"
    end


  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


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

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

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

  def test_new_attribute_escaping
    assert_equal(%Q{bar\n}, render(%q{%a(a="foo \" bar") bar}))
    assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\\" bar") bar}))


  def get_disp_ctrl
    Log.add_info(request, params.inspect)

    if params[:id] != '0'
      begin
        @folder = Folder.find(params[:id])
      rescue => evar
        @folder = nil
      end
    end

    session[:folder_id] = params[:id]

    render(:partial => 'ajax_disp_ctrl', :layout => false)
  end


  def create_event(comment)
    Event.create! bug_id: comment.bug_id, kind: 'comment', data: {'comment_id' => comment.id}, user_id: comment.user_id
  end


  def test_verify_security_policy_checksum_missing
    skip 'openssl is missing' unless defined?(OpenSSL::SSL)

    @spec.cert_chain = [PUBLIC_CERT.to_pem]
    @spec.signing_key = PRIVATE_KEY

    build = Gem::Package.new @gem
    build.spec = @spec
    build.setup_signer

    FileUtils.mkdir 'lib'
    FileUtils.touch 'lib/code.rb'

    File.open @gem, 'wb' do |gem_io|
      Gem::Package::TarWriter.new gem_io do |gem|
        build.add_metadata gem
        build.add_contents gem

        # write bogus data.tar.gz to foil signature
        bogus_data = Gem.gzip 'hello'
        gem.add_file_simple 'data.tar.gz', 0444, bogus_data.length do |io|
          io.write bogus_data
        end

        # pre rubygems 2.0 gems do not add checksums
      end
    end

    Gem::Security.trust_dir.trust_cert PUBLIC_CERT

    package = Gem::Package.new @gem
    package.security_policy = Gem::Security::HighSecurity

    e = assert_raises Gem::Security::Exception do
      package.verify
    end

    assert_equal 'invalid signature', e.message

    refute package.instance_variable_get(:@spec), '@spec must not be loaded'
    assert_empty package.instance_variable_get(:@files), '@files must empty'
  end


      def mget(*keys)
        options = (keys.pop if keys.last.is_a? Hash) || {}
        if keys.any?
          # Marshalling gets extended before Namespace does, so we need to pass options further
          if singleton_class.ancestors.include? Marshalling
            super(*keys.map {|key| interpolate(key) }, options)
          else
            super(*keys.map {|key| interpolate(key) })
          end
        end
      end


      def skip_node?(node)
        node.text? || node.cdata?
      end


  def self.find_q_codes(html)

    q_hash = {}   # |q_code, q_param|

    return q_hash if html.nil?

    all = Research.get_q_codes

    q_codes = html.scan(/[$](q\d{2}_\d{2})/)

    unless q_codes.nil?

      yaml = Research.get_config_yaml

      q_codes.each do |q_code_a|

        q_code = q_code_a.first

        if all.include?(q_code)

          if yaml[q_code].nil?
            q_hash[q_code] = nil
          else
            q_hash[q_code] = Marshal.load(Marshal.dump(yaml[q_code]))
          end

        end
      end
    end

    return q_hash
  end


    it 'should return a key' do
      expect(jwt_validator.jwks_key(:alg, jwks_kid)).to eq('RS256')
    end


      def call(exception, locale, key, options)
        if exception.is_a?(MissingTranslation)
          options[:rescue_format] == :html ? exception.html_message : exception.message
        elsif exception.is_a?(Exception)
          raise exception
        else
          throw :exception, exception
        end
      end


  def sanitize_key(key)
    case key
    when Symbol then "--#{key.to_s.tr("_", "-")}"
    else             key
    end


  def get_path
    Log.add_info(request, params.inspect)

    if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      @folder_path = '/' + t('paren.unknown')
      render(:partial => 'ajax_folder_path', :layout => false)
      return
    end

    @selected_id = params[:thetisBoxSelKeeper].split(':').last

    @folder_path = Folder.get_path(@selected_id)

    render(:partial => 'ajax_folder_path', :layout => false)
  end


  def self.get_childs(folder_id, conditions, recursive, admin, ret_obj)

    SqlHelper.validate_token([folder_id])
    arr = []

    if recursive

      folder_tree = Folder.get_tree(Hash.new, conditions, folder_id, admin)
      return [] if folder_tree.nil?

      folder_tree.each do |parent_id, childs|
        if ret_obj
          arr |= childs
        else
          childs.each do |folder|
            folder_id = folder.id.to_s
            arr << folder_id unless arr.include?(folder_id)
          end
        end
      end

    else

      con = Marshal.load(Marshal.dump(conditions))
      if con.nil?
        con = ''
      else
        con << ' and '
      end
      con << "parent_id=#{folder_id}"

      unless admin
        con << " and (xtype is null or not (xtype='#{Folder::XTYPE_SYSTEM}'))"
      end

      folders = Folder.where(con).order('xorder ASC').to_a
      if ret_obj
        arr = folders
      else
        folders.each do |folder|
          arr << folder.id.to_s
        end
      end
    end

    return arr
  end


  def check_owner
    return if params[:id].nil? or params[:id].empty? or @login_user.nil?

    begin
      owner_id = Item.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_ITEM) 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


  def edit_timecard
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.nil? or date_s.empty?
      @date = Date.today
      date_s = @date.strftime(Schedule::SYS_DATE_FORM)
    else
      @date = Date.parse(date_s)
    end

    @timecard = Timecard.get_for(@login_user.id, date_s)

    render(:partial => 'timecard', :layout => false)
  end


  def process
    # We don't want any tracking back in the fs.  Unlikely, but there
    # you go.
    client = self.host.gsub("..",".")

    dir = File.join(Puppet[:reportdir], client)

    if ! FileTest.exists?(dir)
      FileUtils.mkdir_p(dir)
      FileUtils.chmod_R(0750, dir)
    end

    # Now store the report.
    now = Time.now.gmtime
    name = %w{year month day hour min}.collect do |method|
      # Make sure we're at least two digits everywhere
      "%02d" % now.send(method).to_s
    end.join("") + ".yaml"

    file = File.join(dir, name)

    f = Tempfile.new(name, dir)
    begin
      begin
        f.chmod(0640)
        f.print to_yaml
      ensure
        f.close
      end
      FileUtils.mv(f.path, file)
    rescue => detail
      puts detail.backtrace if Puppet[:trace]
      Puppet.warning "Could not write report for #{client} at #{file}: #{detail}"
    end

    # Only testing cares about the return value
    file
  end


    def self.dump(object)
      MultiJson.dump object,
        mode: :compat, escape_mode: :xss_safe, time_format: :ruby
    end


    it "sanitizes Pathname param key" do
      cl = subject.build_command_line("true", Pathname.new("/usr/bin/ruby") => nil)
      expect(cl).to eq "true /usr/bin/ruby"
    end


    def verify_signature(string, signature)
      if signature.nil?
        fail InvalidSignature, "missing \"signature\" param"
      elsif signature != generate_signature(string)
        fail InvalidSignature, "provided signature does not match the calculated signature"
      end
    end


    def calculated_content_type
      @calculated_content_type ||= type_from_file_command.chomp
    end


  def self.get_for(user, mail_account_id, xtype)

    return nil if user.nil? or mail_account_id.blank?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id, mail_account_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << "(mail_account_id=#{mail_account_id})"
    con << "(xtype='#{xtype}')"

    return MailFolder.where(con.join(' and ')).first
  end


    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


  def show
    filename = Rails.root.join("attachments", @attachment.filename)
    unless File.exist?(filename)
      COURSE_LOGGER.log("Cannot find the file '#{@attachment.filename}' for"\
                        " attachment #{@attachment.name}")

      flash[:error] = "Error loading #{@attachment.name} from #{@attachment.filename}"
      redirect_to([@course, :attachments]) && return
    end
    send_file(filename, disposition: "inline",
                        type: @attachment.mime_type, filename: @attachment.filename) && return
  end


  def self.get_next_revision(user_id, source_id)
    copied_items = Item.where("user_id=#{user_id} and source_id=#{source_id}").order('created_at DESC').to_a

    rev = 0
    copied_items.each do |item|
      rev_ary = item.title.scan(/[#](\d\d\d)$/)
      next if rev_ary.nil?

      rev = rev_ary.first.to_a.first.to_i
      break
    end

    return '#' + sprintf('%03d', rev+1)
  end


  def update_folders_order
    Log.add_info(request, params.inspect)

    order_ary = params[:folders_order]

    folders = MailFolder.get_childs(params[:id], false, false)
    # folders must be ordered by xorder ASC.

    folders.sort! { |id_a, id_b|

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

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

      idx_a - idx_b
    }

    idx = 1
    folders.each do |folder_id|
      begin
        folder = MailFolder.find(folder_id)
        next if folder.user_id != @login_user.id

        folder.update_attribute(:xorder, idx)

        if folder.xtype == MailFolder::XTYPE_ACCOUNT_ROOT
          mail_account = MailAccount.find_by_id(folder.mail_account_id)
          unless mail_account.nil?
            mail_account.update_attribute(:xorder, idx)
          end
        end

        idx += 1
      rescue => evar
        Log.add_error(request, evar)
      end
    end

    render(:text => '')
  end


  def self.trim_by_capacity(user_id, mail_account_id, capacity_mb)

# FEATURE_MAIL_STRICT_CAPACITY >>>
=begin
#    max_size = capacity_mb * 1024 * 1024
#    cur_size = MailAccount.get_using_size(mail_account_id)
#
#    if cur_size > max_size
#      over_size = cur_size - max_size
#      emails = []
#
#      # First, empty Trashbox
#      user = User.find(user_id)
#      trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
#      trash_nodes = [trashbox.id.to_s]
#      trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
#      con = "mail_folder_id in (#{trash_nodes.join(',')})"
#      emails = Email.where(con).order('updated_at ASC').to_a
#      emails.each do |email|
#        next if email.size.nil?
#
#        email.destroy
#        over_size -= email.size
#        break if over_size <= 0
#      end
#
#      # Now, remove others
#      if over_size > 0
#        emails = Email.where("mail_account_id=#{mail_account_id}").order('updated_at ASC').to_a
#        emails.each do |email|
#          next if email.size.nil?
#
#          email.destroy
#          over_size -= email.size
#          break if over_size <= 0
#        end
#      end
#    end
=end
# FEATURE_MAIL_STRICT_CAPACITY <<<
  end


  def column_content(column, item)
    value = column.value_object(item)
    if value.is_a?(Array)
      value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe
    else
      column_value(column, item, value)
    end
  end


  def set_auth_users
    Log.add_info(request, params.inspect)

    @folder = Folder.find(params[:id])

    if Folder.check_user_auth(@folder.id, @login_user, 'w', true)

      read_users = []
      write_users = []
      users_auth = params[:users_auth]
      unless users_auth.nil?
        users_auth.each do |auth_param|
          user_id = auth_param.split(':').first
          auths = auth_param.split(':').last.split('+')
          if auths.include?('r')
            read_users << user_id
          end
          if auths.include?('w')
            write_users << user_id
          end
        end
      end

      user_id = @folder.get_my_folder_owner
      if !user_id.nil? and (!read_users.include?(user_id.to_s) or !write_users.include?(user_id.to_s))
        flash[:notice] = 'ERROR:' + t('folder.my_folder_without_auth_owner')
      else
        @folder.set_read_users read_users
        @folder.set_write_users write_users

        @folder.save

        flash[:notice] = t('msg.register_success')
      end
    else
      flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
    end

    @group_id = params[:group_id]
    if @group_id.nil? or @group_id.empty?
      @users = []
    else
      @users = Group.get_users(@group_id)
    end
    render(:partial => 'ajax_auth_users', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_auth_users', :layout => false)
  end


  def login_success
    if params[:ref].blank?
      redirect_to default_logged_in_path
    elsif params[:ref] =~ /^\//
      redirect_to params[:ref]
    else
      render "sns/login/redirect"
    end
  end


  def self.validate_token(tokens, extra_chars=nil)

    extra_chars = Regexp.escape((extra_chars || []).join())
    regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.#{extra_chars}]+[ ]*$")

    [tokens].flatten.each do |token|
      next if token.blank?

      if token.to_s.match(regexp).nil?
        raise("[ERROR] SqlHelper.validate_token failed: #{token}")
      end
    end
  end


    it "passes the initial directory" do
      expect(File.cleanpath('C/../../D')).to eq "../D"
    end


  def self.get_for(user_id, category=nil)

    SqlHelper.validate_token([user_id, category])

    con = []
    con << "(user_id=#{user_id})"
    con << "(category='#{category}')" unless category.nil?

    settings = Setting.where(con.join(' and ')).to_a

    return nil if settings.nil? or settings.empty?

    hash = Hash.new

    settings.each do |setting|
      hash[setting.xkey] = setting.xvalue
    end

    return hash
  end


        def self.search_by_params(key, operator, value)
          key_name = key.sub(/^.*\./,'')
          opts     = {:conditions => "name = '#{key_name}' and value #{operator} '#{value_to_sql(operator, value)}'", :order => :priority}
          p        = Parameter.all(opts)
          return {:conditions => '1 = 0'} if p.blank?

          max         = p.first.priority
          negate_opts = {:conditions => "name = '#{key_name}' and NOT(value #{operator} '#{value_to_sql(operator, value)}') and priority > #{max}", :order => :priority}
          n           = Parameter.all(negate_opts)

          conditions = param_conditions(p)
          negate = param_conditions(n)

          conditions += " AND " unless conditions.blank? || negate.blank?
          conditions += " NOT(#{negate})" unless negate.blank?
          return {:conditions => conditions}
        end


      def original_filename
        filename = filename_from_header || filename_from_uri
        mime_type = MiniMime.lookup_by_content_type(file.content_type)
        unless File.extname(filename).present? || mime_type.blank?
          filename = "#{filename}.#{mime_type.extension}"
        end
        filename
      end


  def timeline
    unless params[:type].empty?
      model = params[:type].camelize.constantize
      item = model.find(params[:id])
      item.update_attribute(:state, params[:state])
    else
      comments, emails = params[:id].split("+")
      Comment.update_all("state = '#{params[:state]}'", "id IN (#{comments})") unless comments.blank?
      Email.update_all("state = '#{params[:state]}'", "id IN (#{emails})") unless emails.blank?
    end

    render :nothing => true
  end


  def self.destroy(host)
    client = host.gsub("..",".")
    dir = File.join(Puppet[:reportdir], client)

    if File.exists?(dir)
      Dir.entries(dir).each do |file|
        next if ['.','..'].include?(file)
        file = File.join(dir, file)
        File.unlink(file) if File.file?(file)
      end
      Dir.rmdir(dir)
    end
  end


  def set_attachment
    Log.add_info(request, params.inspect)

    created = false

    if params[:id].nil? or params[:id].empty?
      @item = Item.new_info(0)
      @item.attributes = params[:item]
      @item.user_id = @login_user.id
      @item.title = t('paren.no_title')

      [:attachment0, :attachment1].each do |attach|

        next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0

        @item.save!
        created = true
        break
      end
    else
      @item = Item.find(params[:id])
    end

    modified = false

    item_attachments = @item.attachments_without_content
    [:attachment0, :attachment1].each do |attach|
      next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0

      attachment = Attachment.create(params[attach], @item, item_attachments.length)

      modified = true
      item_attachments << attachment
    end

    if modified and !created
      @item.update_attribute(:updated_at, Time.now)
    end

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

  rescue => evar
    Log.add_error(request, evar)

    @attachment = Attachment.new
    @attachment.errors.add_to_base(evar.to_s[0, 256])

    render(:partial => 'ajax_item_attachment', :layout => false)
  end


  def self.get_sql_like(attr_names, keyword)

    key = ActiveRecord::Base.connection.quote("%#{SqlHelper.escape_for_like(keyword)}%")

    con = []
    attr_names.each do |attr_name|
      con << "(#{attr_name} like #{key})"
    end
    sql = con.join(' or ')
    sql = '(' + sql + ')' if con.length > 1
    return sql
  end


  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


  def delete_statistics_group
    Log.add_info(request, params.inspect)

    group_id = params[:group_id]

    if group_id.nil? or group_id.empty?
      @group_ids = Research.get_statistics_groups
      render(:partial => 'ajax_statistics_groups', :layout => false)
      return
    end

    @group_ids = Research.delete_statistics_group group_id

    render(:partial => 'ajax_statistics_groups', :layout => false)
  end


      def initialize(file)
        @file = file.is_a?(String) ? StringIO.new(file) : file
      end


  def ajax_move_mails
    Log.add_info(request, params.inspect)

    folder_id = params[:thetisBoxSelKeeper].split(':').last
    mail_folder = MailFolder.find_by_id(folder_id)

    if folder_id == '0' \
        or mail_folder.nil? \
        or mail_folder.user_id != @login_user.id
      flash[:notice] = 'ERROR:' + t('msg.cannot_save_in_folder')
      get_mails
      return
    end

    unless params[:check_mail].blank?
      count = 0
      params[:check_mail].each do |email_id, value|
        if value == '1'

          begin
            email = Email.find(email_id)
            next if email.user_id != @login_user.id

            email.update_attribute(:mail_folder_id, folder_id)

          rescue => evar
            Log.add_error(request, evar)
          end

          count += 1
        end
      end
      flash[:notice] = t('mail.moved', :count => count)
    end

    get_mails
  end


        def spree_current_user
          @spree_current_user ||= Spree.user_class.find_by(id: doorkeeper_token.resource_owner_id) if doorkeeper_token
        end


  def self.up
    add_column :items, :source_id, :integer

    add_column :addresses, :groups, :text
    add_column :addresses, :teams, :text

    add_column :workflows, :groups, :text

    add_column :users,  :figure, :string
    add_column :groups, :xtype, :string

    add_column :teams, :req_to_del_at, :datetime
    change_table :teams do |t|
      t.timestamps
    end

    teams = Team.all
    unless teams.nil?
      teams.each do |team|
        begin
          item = Item.find(team.item_id)
        rescue
        end
        next if item.nil?

        attrs = ActionController::Parameters.new({created_at: item.created_at, updated_at: item.updated_at})
        attrs.permit!
        team.update_attributes(attrs)
      end
    end
  end


  def rename
    Log.add_info(request, params.inspect)

    @mail_folder = MailFolder.find(params[:id])

    unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.save
    end
    render(:partial => 'ajax_folder_name', :layout => false)
  end


    it "does not remove multiple '../' at the beginning" do
      expect(File.cleanpath('../../A/B')).to eq '../../A/B'
    end


  def edit
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.nil? or date_s.empty?
      @date = Date.today
      date_s = @date.strftime(Schedule::SYS_DATE_FORM)
    else
      @date = Date.parse(date_s)
    end

    if params[:user_id].nil?
      @selected_user = @login_user
    else
      @selected_user = User.find(params[:user_id])
    end

    @timecard = Timecard.get_for(@selected_user.id, date_s)

    if @selected_user == @login_user
      @schedules = Schedule.get_user_day(@login_user, @date)
    end

    if !params[:display].nil? and params[:display].split('_').first == 'group'
      @group_id = params[:display].split('_').last
    end
  end


  def edit
    Log.add_info(request, params.inspect)

    @group_id = params[:group_id]
    official_title_id = params[:id]

    unless official_title_id.nil? or official_title_id.empty?
      @official_title = OfficialTitle.find(official_title_id)
    end

    render(:partial => 'ajax_official_title_form', :layout => (!request.xhr?))
  end


  def reset_users
    Log.add_info(request, params.inspect)

    count = 0

    unless params[:check_user].nil?

      params[:check_user].each do |user_id, value|
        if value == '1'
          begin
            Research.destroy_all('user_id=' + user_id.to_s)
            count += 1
          rescue => evar
            Log.add_error(request, evar)
          end
        end
      end
    end

    if count > 0
      flash[:notice] = t('msg.status_of')+ count.to_s + t('user.status_reset')
    end

    redirect_to(:controller => 'researches', :action => 'users')

  rescue => evar
    Log.add_error(request, evar)
    render(:text => evar.to_s)
  end


  def get_folders_order
    Log.add_info(request, params.inspect)

    @folder_id = params[:id]

    if @folder_id == '0'
      @folders = MailFolder.get_account_roots_for(@login_user)
    else
      mail_folder = MailFolder.find(@folder_id)
      if mail_folder.user_id == @login_user.id
        @folders = MailFolder.get_childs(@folder_id, false, true)
      end
    end

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

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_folders_order', :layout => false)
  end


  def self.validate_token(tokens, extra_chars=nil)

    if extra_chars.nil?
      extra_chars = ''
    else
      extra_chars = Regexp.escape(extra_chars.join())
    end
    regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.@\\-#{extra_chars}]+[ ]*$")

    [tokens].flatten.each do |token|
      next if token.blank?

      if token.to_s.match(regexp).nil?
        raise("[ERROR] SqlHelper.validate_token failed: #{token}")
      end
    end
  end


  def new

    @item = Item.new
    if params[:folder_id].nil? or params[:folder_id].empty?
      my_folder = @login_user.get_my_folder
      if my_folder.nil?
        @item.folder_id = 0
      else
        @item.folder_id = my_folder.id
      end
    else
      @item.folder_id = params[:folder_id].to_i
    end
    @item.xtype= Item::XTYPE_INFO
    @item.layout = 'C'

    render(:action => 'edit')
  end


  def bbs
    Log.add_info(request, params.inspect)

    if !params[:select_sorting].nil?
      sort_a = params[:select_sorting].split(' ')
      params[:sort_col] = sort_a.first
      params[:sort_type] = sort_a.last
    end

    list
    render(:action => 'bbs')
  end


  def update_config
    Log.add_info(request, params.inspect)

    @yaml = ApplicationHelper.get_config_yaml

    unless params[:desktop].nil? or params[:desktop].empty?
      @yaml[:desktop] = Hash.new if @yaml[:desktop].nil?

      params[:desktop].each do |key, val|
        @yaml[:desktop][key] = val
      end
      ApplicationHelper.save_config_yaml(@yaml)
    end

    flash[:notice] = t('msg.update_success')
    render(:partial => 'ajax_user_before_login', :layout => false)
  end


  def test_should_not_fall_for_xss_image_hack_with_uppercase_tags
    assert_sanitized %(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">), "<img>\">"
  end


      def Schema string_or_io
        Schema.new(string_or_io)
      end


  def self.get_from_name(user_name)

    SqlHelper.validate_token([user_name])

    begin
      user = User.where("name='#{user_name}'").first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return user
  end


  def self.from_yaml(input)
    Gem.load_yaml

    input = normalize_yaml_input input
    spec = YAML.load input

    if spec && spec.class == FalseClass then
      raise Gem::EndOfYAMLException
    end

    unless Gem::Specification === spec then
      raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
    end

    spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
    spec.reset_nil_attributes_to_default

    spec
  end


  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


      def download(url, remote_headers = {})
        headers = remote_headers.
          reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}")
        begin
          file = OpenURI.open_uri(process_uri(url.to_s), headers)
        rescue StandardError => e
          raise CarrierWave::DownloadError, "could not download file: #{e.message}"
        end
        CarrierWave::Downloader::RemoteFile.new(file)
      end


        def _unmarshal(val, options)
          unmarshal?(val, options) ? Marshal.load(val) : val
        end


        def test_parse_memory_nil
          assert_raises(ArgumentError) do
            @parser.parse_memory(nil)
          end
        end


    it "with Pathname command and params" do
      cl = subject.build_command_line(Pathname.new("/usr/bin/ruby"), "-v" => nil)
      expect(cl).to eq "/usr/bin/ruby -v"
    end


  def ajax_delete_items
    Log.add_info(request, params.inspect)

    folder_id = params[:id]

    unless params[:check_item].blank?
      is_admin = @login_user.admin?(User::AUTH_ITEM)

      count = 0
      params[:check_item].each do |item_id, value|
        if value == '1'

          begin
            item = Item.find(item_id)
            next if !is_admin and item.user_id != @login_user.id

            item.destroy

          rescue => evar
            Log.add_error(request, evar)
          end

          count += 1
        end
      end
      flash[:notice] = t('item.deleted', :count => count)
    end

    get_items
  end


  def self.load_yaml
    return if @yaml_loaded
    return unless defined?(gem)

    test_syck = ENV['TEST_SYCK']

    # Only Ruby 1.8 and 1.9 have syck
    test_syck = false unless /^1\./ =~ RUBY_VERSION

    unless test_syck
      begin
        gem 'psych', '>= 1.2.1'
      rescue Gem::LoadError
        # It's OK if the user does not have the psych gem installed.  We will
        # attempt to require the stdlib version
      end

      begin
        # Try requiring the gem version *or* stdlib version of psych.
        require 'psych'
      rescue ::LoadError
        # If we can't load psych, thats fine, go on.
      else
        # If 'yaml' has already been required, then we have to
        # be sure to switch it over to the newly loaded psych.
        if defined?(YAML::ENGINE) && YAML::ENGINE.yamler != "psych"
          YAML::ENGINE.yamler = "psych"
        end

        require 'rubygems/psych_additions'
        require 'rubygems/psych_tree'
      end
    end

    require 'yaml'

    # If we're supposed to be using syck, then we may have to force
    # activate it via the YAML::ENGINE API.
    if test_syck and defined?(YAML::ENGINE)
      YAML::ENGINE.yamler = "syck" unless YAML::ENGINE.syck?
    end

    # Now that we're sure some kind of yaml library is loaded, pull
    # in our hack to deal with Syck's DefaultKey ugliness.
    require 'rubygems/syck_hack'

    @yaml_loaded = true
  end


  def sanitize_value(value)
    case value
    when Array    then value.collect { |i| i.to_s.shellescape }
    when NilClass then value
    else               value.to_s.shellescape
    end


  def schedule_all
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.nil? or date_s.empty?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    if @login_user.nil? or params[:display].nil? or params[:display] == 'all'
      params[:display] = 'all'
      con = EquipmentHelper.get_scope_condition_for(@login_user)
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      case display_type
       when 'group'
        if @login_user.get_groups_a(true).include?(display_id)
          con = SqlHelper.get_sql_like([:groups], "|#{display_id}|")
        end
       when 'team'
        if @login_user.get_teams_a.include?(display_id)
          con = SqlHelper.get_sql_like([:teams], "|#{display_id}|")
        end
      end
    end


  def query
    Log.add_info(request, '')   # Not to show passwords.

    unless @login_user.admin?(User::AUTH_ZEPTAIR)
      render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
      return
    end

    target_user = nil

    SqlHelper.validate_token([params[:user_id], params[:zeptair_id], params[:group_id]])

    unless params[:user_id].blank?
      target_user = User.find(params[:user_id])
    end

    unless params[:zeptair_id].blank?
      zeptair_id = params[:zeptair_id]
      target_user = User.where("zeptair_id=#{zeptair_id}").first
    end

    if target_user.nil?

      if params[:group_id].blank?
        sql = 'select distinct Item.* from items Item, attachments Attachment'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << ' order by Item.user_id ASC'
      else
        group_ids = [params[:group_id]]

        if params[:recursive] == 'true'
          group_ids += Group.get_childs(params[:group_id], true, false)
        end

        groups_con = []
        group_ids.each do |group_id|
          groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{@group_id}|")
        end
        sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
        sql << ' order by Item.user_id ASC'
      end

      @post_items = Item.find_by_sql(sql)
    else
      @post_item = ZeptairPostHelper.get_item_for(target_user)
    end

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end


    def name
      FIELD_NAME_MAP[@name.to_s.downcase] || @name
    end


    detectMimeType(filename) {
        if (!filename) {
            return defaultMimeType;
        }

        let parsed = path.parse(filename);
        let extension = (parsed.ext.substr(1) || parsed.name || '')
            .split('?')
            .shift()
            .trim()
            .toLowerCase();
        let value = defaultMimeType;

        if (extensions.has(extension)) {
            value = extensions.get(extension);
        }

        if (Array.isArray(value)) {
            return value[0];
        }
        return value;
    },


    it "handles Symbol keys with tailing '='" do
      cl = subject.build_command_line("true", :abc= => "def")
      expect(cl).to eq "true --abc=def"
    end


  def update_config
    Log.add_info(request, params.inspect)

    yaml = ApplicationHelper.get_config_yaml

    unless params[:timecard].nil? or params[:timecard].empty?
      yaml[:timecard] = Hash.new if yaml[:timecard].nil?

      params[:timecard].each do |key, val|
        yaml[:timecard][key] = val
      end
      ApplicationHelper.save_config_yaml(yaml)
    end

    @yaml_timecard = yaml[:timecard]
    @yaml_timecard = Hash.new if @yaml_timecard.nil?

    flash[:notice] = t('msg.update_success')
    render(:action => 'configure')
  end


def test_html5_data_attributes_without_hyphenation
    assert_equal("

\n",
      render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}",
        :hyphenate_data_attrs => false))

    assert_equal("

\n",
      render("%div{:data => {:one_plus_one => 1+1}}",
        :hyphenate_data_attrs => false))

    assert_equal("

\n",
      render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},


    it "should find a user by first name or last name" do
      @cur_user.stub(:pref).and_return(:activity_user => 'Billy')
      controller.instance_variable_set(:@current_user, @cur_user)
      User.should_receive(:where).with("upper(first_name) LIKE upper('%Billy%') OR upper(last_name) LIKE upper('%Billy%')").and_return([@user])
      controller.send(:activity_user).should == 1
    end


        it :test_render_parse_nil_param do
          assert_raises(ArgumentError) { parser.parse_memory(nil) }
        end


      def process_cors(env)
        resource, error = match_resource(env)
        if resource
          Result.hit(env)
          cors = resource.to_headers(env)
          cors

        else
          Result.miss(env, error)
          nil
        end
      end


def test_attr_wrapper
    assert_equal("

\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
    assert_equal("

\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
    assert_equal("

\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
    assert_equal("

\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


  def url_valid?(url)
    url = begin
      URI.parse(url)
    rescue StandardError
      false
    end
    url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
  end


  def show_tree
    if params[:action] == 'show_tree'
      Log.add_info(request, params.inspect)
    end

    con = []
    con << "(user_id=#{@login_user.id})"

    account_xtype = params[:mail_account_xtype]

    unless account_xtype.blank?
      SqlHelper.validate_token([account_xtype])
      con << "(xtype='#{account_xtype}')"
    end
    @mail_accounts = MailAccount.find_all(con.join(' and '))

    mail_account_ids = []
    @mail_accounts.each do |mail_account|

      mail_account_ids << mail_account.id

      if MailFolder.where("mail_account_id=#{mail_account.id}").count <= 0
        @login_user.create_default_mail_folders(mail_account.id)
      end

      Email.destroy_by_user(@login_user.id, "status='#{Email::STATUS_TEMPORARY}'")
    end

    @folder_tree = MailFolder.get_tree_for(@login_user, mail_account_ids)
  end


  def test_full_sanitize_allows_turning_off_encoding_special_chars
    assert_equal '&', full_sanitize('&')
    assert_equal '&', full_sanitize('&', encode_special_chars: false)
  end


    def read_config(self, config, **kwargs):
        self.recaptcha_private_key = config.get("recaptcha_private_key")
        self.recaptcha_public_key = config.get("recaptcha_public_key")
        self.enable_registration_captcha = config.get(
            "enable_registration_captcha", False
        )
        self.recaptcha_siteverify_api = config.get(
            "recaptcha_siteverify_api",
            "https://www.recaptcha.net/recaptcha/api/siteverify",
        )
        self.recaptcha_template = self.read_templates(
            ["recaptcha.html"], autoescape=True
        )[0]


    def generate(type, str)
      case type
      when :md5
         attribute_value = '{MD5}' + Base64.encode64(Digest::MD5.digest(str)).chomp!
      when :sha
         attribute_value = '{SHA}' + Base64.encode64(Digest::SHA1.digest(str)).chomp!
      when :ssha
         srand; salt = (rand * 1000).to_i.to_s
         attribute_value = '{SSHA}' + Base64.encode64(Digest::SHA1.digest(str + salt) + salt).chomp!
      else
         raise Net::LDAP::HashTypeUnsupportedError, "Unsupported password-hash type (#{type})"
      end


it 'returns correct link' do
      data = {
        cutoff: false,
        user: 'Julia Nguyen',
        comment: 'Hello',
        typename: 'typename',
        type: 'type_comment_moment',
        typeid: 1,
        commentable_id: 1
      }
      expect(comment_link(uniqueid, data)).to eq('Julia Nguyen commented "Hello" on typename')
    end


  def sanitize(params)
    return [] if params.nil? || params.empty?
    params.collect do |k, v|
      [sanitize_key(k), sanitize_value(v)]
    end
  end


  def self.applied_paid_hlds(user_id, start_date, end_date)

    SqlHelper.validate_token([user_id, start_date, end_date])

    sql = "SELECT COUNT(*) FROM timecards WHERE user_id = #{user_id} AND date >= '#{start_date}' AND date <= '#{end_date}'"

    sum = 0.0
    self.workcodes.each do |key, params|
      paidhld_rate = params[WKCODE_PARAM_PAIDHLD]
      if paidhld_rate > 0.0
        num = Timecard.count_by_sql(sql + " AND workcode='#{key}'")
        sum += num * paidhld_rate
      end
    end

    return sum
  end


  def test_extract_symlink_parent
   skip 'symlink not supported' if Gem.win_platform?

   package = Gem::Package.new @gem

   tgz_io = util_tar_gz do |tar|
     tar.mkdir       'lib',               0755
     tar.add_symlink 'lib/link', '../..', 0644
     tar.add_file    'lib/link/outside.txt', 0644 do |io| io.write 'hi' end
   end

   # Extract into a subdirectory of @destination; if this test fails it writes
   # a file outside destination_subdir, but we want the file to remain inside
   # @destination so it will be cleaned up.
   destination_subdir = File.join @destination, 'subdir'
   FileUtils.mkdir_p destination_subdir

   e = assert_raises Gem::Package::PathError do
     package.extract_tar_gz tgz_io, destination_subdir
   end

   assert_equal("installing into parent path ../outside.txt of " +
                 "#{destination_subdir} is not allowed", e.message)
  end


  def check_image_content_type!(new_file)
    if image?(new_file)
      magic_type = mime_magic_content_type(new_file)
      if magic_type != new_file.content_type
        raise CarrierWave::IntegrityError, "has MIME type mismatch"
      end
    end
  end


it "with dofollowify enabled, links should be nofollowed" do
      @blog.dofollowify = true
      @blog.save

      expect(nofollowify_links('my blog')).
        to eq('my blog')
    end


  def self.get_my_folder(user_id)

    return Folder.where("(owner_id=#{user_id}) and (xtype='#{Folder::XTYPE_USER}')").first
  end


  def destroy
    current_user.invalidate_all_sessions!
    super
  end


    def self.generate_key_pair(key_base_name, recipient, real_name)
      public_key_file_name = "#{key_base_name}.pub"
      private_key_file_name = "#{key_base_name}.sec"
      script = generate_key_script(public_key_file_name, private_key_file_name, recipient, real_name)
      script_file = Tempfile.new('gpg-script')
      begin
        script_file.write(script)
        script_file.close
        result = system("gpg --batch --gen-key #{script_file.path}")
        raise RuntimeError.new('gpg failed') unless result
      ensure
        script_file.close
        script_file.unlink
      end
    end


      it "returns the right category group permissions for an anon user" do
        json = described_class.new(category, scope: Guardian.new, root: false).as_json

        expect(json[:group_permissions]).to eq([
          { permission_type: CategoryGroup.permission_types[:full], group_name: Group[:everyone]&.name }
        ])
      end


      it "returns the right category group permission for a staff user ordered by ascending group name" do
        json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json

        expect(json[:group_permissions]).to eq([
          { permission_type: CategoryGroup.permission_types[:readonly], group_name: group.name },
          { permission_type: CategoryGroup.permission_types[:full], group_name: private_group.name },
          { permission_type: CategoryGroup.permission_types[:full], group_name: user_group.name },
          { permission_type: CategoryGroup.permission_types[:readonly], group_name: 'everyone' },
        ])
      end


  def stub_bad_jwks
    stub_request(:get, 'https://samples.auth0.com/.well-known/jwks-bad.json')
      .to_return(
        status: 404
      )
  end


func validateWebhook(actor *db.User, l macaron.Locale, w *db.Webhook) (field, msg string, ok bool) {
	if !actor.IsAdmin {
		// 🚨 SECURITY: Local addresses must not be allowed by non-admins to prevent SSRF,
		// see https://github.com/gogs/gogs/issues/5366 for details.
		payloadURL, err := url.Parse(w.URL)
		if err != nil {
			return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), false
		}

		if netutil.IsLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) {
			return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_use_local_addresses"), false
		}
	}

	return "", "", true
}


func (v *validator) ValidateSignature(auth kolide.Auth) (kolide.Auth, error) {
	info := auth.(*resp)
	status, err := info.status()
	if err != nil {
		return nil, errors.New("missing or malformed response")
	}
	if status != Success {
		return nil, errors.Errorf("response status %s", info.statusDescription())
	}
	decoded, err := base64.StdEncoding.DecodeString(info.rawResponse())
	if err != nil {
		return nil, errors.Wrap(err, "based64 decoding response")
	}
	doc := etree.NewDocument()
	err = doc.ReadFromBytes(decoded)
	if err != nil || doc.Root() == nil {
		return nil, errors.Wrap(err, "parsing xml response")
	}
	elt := doc.Root()
	signed, err := v.validateSignature(elt)
	if err != nil {
		return nil, errors.Wrap(err, "signing verification failed")
	}
	// We've verified that the response hasn't been tampered with at this point
	signedDoc := etree.NewDocument()
	signedDoc.SetRoot(signed)
	buffer, err := signedDoc.WriteToBytes()
	if err != nil {
		return nil, errors.Wrap(err, "creating signed doc buffer")
	}
	var response Response
	err = xml.Unmarshal(buffer, &response)
	if err != nil {
		return nil, errors.Wrap(err, "unmarshalling signed doc")
	}
	info.setResponse(&response)
	return info, nil
}


func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {

	// Logic based on response type or status
	if noBodyExpected(requestMethod) {
		return 0, nil
	}
	if status/100 == 1 {
		return 0, nil
	}
	switch status {
	case 204, 304:
		return 0, nil
	}

	// Logic based on Transfer-Encoding
	if chunked(te) {
		return -1, nil
	}

	// Logic based on Content-Length
	cl := strings.TrimSpace(header.get("Content-Length"))
	if cl != "" {
		n, err := parseContentLength(cl)
		if err != nil {
			return -1, err
		}
		return n, nil
	} else {
		header.Del("Content-Length")
	}

	if !isResponse && requestMethod == "GET" {
		// RFC 2616 doesn't explicitly permit nor forbid an
		// entity-body on a GET request so we permit one if
		// declared, but we default to 0 here (not -1 below)
		// if there's no mention of a body.
		return 0, nil
	}

	// Body-EOF logic based on other methods (like closing, or chunked coding)
	return -1, nil
}


func (*UpdateAccountRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{36}
}