  def self.parse_csv_row(row, book, idxs, user)

    imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)
    unless imp_id.nil? or imp_id.empty?
      org_address = Address.find_by_id(imp_id)
    end

    if org_address.nil?
      address = Address.new
    else
      address = org_address
    end

    address.id = imp_id
    attr_names = [
      :name,
      :name_ruby,
      :nickname,
      :screenname,
      :email1,
      :email2,
      :email3,
      :postalcode,
      :address,
      :tel1_note,
      :tel1,
      :tel2_note,
      :tel2,
      :tel3_note,
      :tel3,
      :fax,
      :url,
      :organization,
      :title,
      :memo,
      :xorder,
      :groups,
      :teams
    ]
    attr_names.each_with_index do |attr_name, idx|
      row_idx = idxs[idx+1]
      break if row_idx.nil?

      val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)
      address.send(attr_name.to_s + '=', val)
    end
    if (address.groups == Address::EXP_IMP_FOR_ALL) \
        or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)
      address.groups = nil
      address.teams = nil
      address.owner_id = 0
    elsif !address.groups.blank? or !address.teams.blank?
      address.owner_id = 0
    else
      address.owner_id = user.id
    end

    return address
  end


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

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

    unless Folder.check_user_auth(@folder.id, @login_user, 'w', true)
      flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
      render(:partial => 'ajax_folder_name', :layout => false)
      return
    end

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


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

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

    attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})
    @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))

    @orders = @workflow.get_orders

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


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

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

    orders_hash = params.dup
    orders_hash.reject! { |key, value|
      key.index(/order-/) != 0
    }
    orders_hash.sort_by { |key, value|
      key.split('-').last.to_i
    }

    orders = []
    orders_hash.each do |key, value|

      orders << '|' + value.split(',').join('|') + '|'
    end
    @item.workflow.update_attribute(:users, orders.join(','))

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

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

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


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

    unless params[:select_sorting].nil? or params[:select_sorting].empty?
      sort_a = params[:select_sorting].split(' ')
      params[:sort_col] = sort_a.first
      params[:sort_type] = sort_a.last
    end

    list

    if params[:keyword].nil? or params[:keyword].empty?
      if params[:from_action].nil? or params[:from_action] == 'bbs'
        render(:action => 'bbs')
      else
        render(:action => 'list')
      end
    end
  end


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

    location_id = params[:id]

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

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

    render(:text => (location.nil?)?'':location.id.to_s)
  end


  def check_member

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

    if Item.find(params[:id]).user_id != @login_user.id
      Log.add_check(request, '[check_member]'+request.to_s)

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


  def create_title

    titles = User.get_config_titles
    titles = [] if titles.nil?
    titles << t('user.new_title')
    User.save_config_titles titles

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


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

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

    group_id = params[:thetisBoxSelKeeper].split(':').last
    unless group_id == '0'  # '0' for ROOT
      begin
        group = Group.find(group_id)
      rescue => evar
        Log.add_error(request, evar)
      ensure
        if group.nil?
          render(:partial => 'ajax_groups', :layout => false)
          return
        end
      end
    end

    begin
      @user = User.find(params[:user_id])
    rescue => evar
      Log.add_error(request, evar)
    end

    unless @user.nil?

      is_modified = false

      # Change, not simply Add
      unless params[:current_id] == nil or params[:current_id].empty?
        if @user.exclude_from(params[:current_id])
          is_modified = true
        end
      end

      is_modified = true if @user.add_to(group_id)

      if is_modified == true
#        @user.update_attribute(:groups, @user.groups)
        @user.save!

        if @user.id == @login_user.id
          @login_user = @user
        end
      end
    end

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


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

    begin
      owner_id = Workflow.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_WORKFLOW) 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 copy
    Log.add_info(request, params.inspect)

    return unless request.post?

    tmpl_id = params[:thetisBoxSelKeeper].split(':').last
    tmpl_item = Item.find(tmpl_id)

    item = tmpl_item.copy(@login_user.id, @login_user.get_my_folder.id)
    if item.public != false
      item.update_attribute(:public, false)
    end

    redirect_to(:controller => 'items', :action => 'edit', :id => item.id)

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

    redirect_to(:controller => 'items', :action => 'new')
  end


  def self.get_comment_of(item_id, user_id)

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

    return comment
  end


  def self.get_tree_by_group_for_admin(group_id)

    SqlHelper.validate_token([group_id])

    folder_tree = {}
    tree_id = '0'

    if group_id.to_s == '0'
      sql = 'select distinct * from folders'

      where = " where (parent_id = #{tree_id})"
      where << " and ((xtype is null) or not(xtype = '#{XTYPE_GROUP}' or xtype = '#{XTYPE_USER}'))"

      order_by = ' order by xorder ASC, id ASC'
    else
      sql = 'select distinct Folder.* from folders Folder, users User'

      where = " where (Folder.parent_id = #{tree_id})"
      where << ' and ('
      where <<      "(Folder.xtype = '#{XTYPE_GROUP}' and Folder.owner_id = #{group_id})"
      where <<      ' or '
      where <<      "(Folder.xtype = '#{XTYPE_USER}' and  Folder.owner_id = User.id and #{SqlHelper.get_sql_like(['User.groups'], "|#{group_id}|")})"
      where <<     ' )'

      order_by = ' order by Folder.xorder ASC, Folder.id ASC'
    end

    sql << where + order_by

    folder_tree[tree_id] = Folder.find_by_sql(sql)

    folder_tree[tree_id].each do |folder|
      folder_tree = Folder.get_tree(folder_tree, nil, folder, true)
    end

    return Folder.sort_tree(folder_tree)
  end


  def self.get_tree(folder_tree, conditions, parent, admin)

    if parent.instance_of?(Folder)
      tree_id = parent.id.to_s
    else
      tree_id = parent.to_s
      parent = nil
      if tree_id != '0'
        begin
          parent = Folder.find(tree_id)
        rescue
        end
        return folder_tree if parent.nil?
      end
    end

    group_obj_cache = {}
    folder_tree[tree_id] = []
    if !parent.nil? and (parent.xtype == Folder::XTYPE_GROUP)
      Group.get_childs(parent.owner_id, false, true).each do |group|
        group_obj_cache[group.id] = group
        con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?
        if con.nil?
          con = ''
        else
          con << ' and '
        end
        con << "(xtype='#{Folder::XTYPE_GROUP}') and (owner_id=#{group.id})"
        begin
          group_folder = Folder.where(con).first
        rescue => evar
          Log.add_error(nil, evar)
        end
        unless group_folder.nil?
          folder_tree[tree_id] << group_folder
        end
      end
    end

    con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?
    if con.nil?
      con = ''
    else
      con << ' and '
    end
    con << "parent_id=#{tree_id}"
    folder_tree[tree_id] += Folder.where(con).order('xorder ASC, id ASC').to_a

    delete_ary = []

    folder_tree[tree_id].each do |folder|

      if !admin and (folder.xtype == Folder::XTYPE_SYSTEM)
        delete_ary << folder
        next
      end

      if (tree_id == '0') and (folder.xtype == Folder::XTYPE_GROUP)
        group = Group.find_with_cache(folder.owner_id, group_obj_cache)
        unless group.nil?
          if group.parent_id != 0
            delete_ary << folder
            next
          end
        end
      end

      folder_tree = Folder.get_tree(folder_tree, conditions, folder, admin)
    end

    folder_tree[tree_id] -= delete_ary

    return folder_tree
   end


  def self.get_for_group(group_id)

    SqlHelper.validate_token([group_id])
    if group_id.nil?
      con = 'group_id is null'
    else
      con = "group_id=#{group_id}"
    end

    Location.do_expire(con)

    return Location.where(con).to_a
  end


  def self.get_for(group_id, include_parents=false, enabled=nil)

    SqlHelper.validate_token([group_id])

    con = []
    #con << "(disabled=#{!enabled})" unless enabled.nil?

    if include_parents
      group_con = '(group_id is null)'

      unless group_id.nil? or group_id.to_s == '0'
        group_obj_cache = {}
        group = Group.find_with_cache(group_id, group_obj_cache)
        group_ids = group.get_parents(false, group_obj_cache)
        group_ids << group_id
        group_con << " or (group_id in (#{group_ids.join(',')}))"
      end

      con << '(' + group_con + ')'
    else
      con << "(group_id=#{group_id})"
    end

    order_by = 'order by xorder ASC, id ASC'
    #order_by = 'order by disabled ASC, xorder ASC, id ASC'

    sql = 'select * from official_titles where ' + con.join(' and ') + ' ' + order_by

    return OfficialTitle.find_by_sql(sql)
  end


  def self.get_for(user_id, fiscal_year=nil)

    SqlHelper.validate_token([user_id, fiscal_year])

    begin
      con = []
      con << "(user_id=#{user_id})"
      if fiscal_year.nil?
        return PaidHoliday.where(con).order('year ASC').to_a
      else
        con << "(year=#{fiscal_year})"
        return PaidHoliday.where(con.join(' and ')).first
      end
    rescue
    end
    return nil
  end


  def self.save_value(user_id, category, key, value)

    SqlHelper.validate_token([user_id, category, key])

    con = []
    con << "(user_id=#{user_id})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    if value.nil?
      unless setting.nil?
        setting.destroy
      end
    else
      if setting.nil?
        setting = Setting.new
        setting.user_id = user_id
        setting.category = category
        setting.xkey = key
        setting.xvalue = value
        setting.save!
      else
        setting.update_attribute(:xvalue, value)
      end
    end
  end


  def self.get_value(user_id, category, key)

    SqlHelper.validate_token([user_id, category, key])

    con = []
    con << "(user_id=#{user_id})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end


  def self.get_by_email(mail_addr, user, book=Address::BOOK_BOTH)

    SqlHelper.validate_token([mail_addr])

    email_con = []
    email_con.push("(email1='#{mail_addr}')")
    email_con.push("(email2='#{mail_addr}')")
    email_con.push("(email3='#{mail_addr}')")
    con = []
    con.push('('+email_con.join(' or ')+')')
    con.push(AddressbookHelper.get_scope_condition_for(user, book))

    return Address.where(con.join(' and ')).to_a
  end


  def load_file(filename)
    Gem.load_yaml

    yaml_errors = [ArgumentError]
    yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)

    return {} unless filename and File.exist? filename

    begin
      content = YAML.load(File.read(filename))
      unless content.kind_of? Hash
        warn "Failed to load #{filename} because it doesn't contain valid YAML hash"
        return {}
      end
      return content
    rescue *yaml_errors => e
      warn "Failed to load #{filename}, #{e}"
    rescue Errno::EACCES
      warn "Failed to load #{filename} due to permissions problem."
    end

    {}
  end


  def read_checksums gem
    Gem.load_yaml

    @checksums = gem.seek 'checksums.yaml.gz' do |entry|
      Zlib::GzipReader.wrap entry do |gz_io|
        YAML.load gz_io.read
      end
    end
  end


  def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc:
    open_tar_gz io do |tar|
      tar.each do |entry|
        next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH

        destination = install_location entry.full_name, destination_dir

        FileUtils.rm_rf destination

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

        FileUtils.mkdir_p mkdir, mkdir_options

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

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

        verbose destination
      end
    end
  end


  def install_location filename, destination_dir # :nodoc:
    raise Gem::Package::PathError.new(filename, destination_dir) if
      filename.start_with? '/'

    destination_dir = File.realpath destination_dir if
      File.respond_to? :realpath
    destination_dir = File.expand_path destination_dir

    destination = File.join destination_dir, filename
    destination = File.realpath destination if
      File.respond_to? :realpath
    destination = File.expand_path destination

    raise Gem::Package::PathError.new(destination, destination_dir) unless
      destination.start_with? destination_dir + '/'

    destination.untaint
    destination
  end


      def find(uuid, options = {})
        if uuid.nil? || uuid.to_s.empty?
          raise NotFound, "can't find a record with nil identifier"
        end

        uri = uuid =~ /^http/ ? uuid : member_path(uuid)
        begin
          from_response API.get(uri, {}, options)
        rescue API::NotFound => e
          raise NotFound, e.description
        end
      end


      def _extend_marshalling(options)
        @marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory
        extend Marshalling if @marshalling
      end


        def _marshal(val, options)
          yield marshal?(options) ? Marshal.dump(val) : val
        end


  def self.map_library_name(lib)
    # Mangle the library name to reflect the native library naming conventions
    lib = lib.to_s unless lib.kind_of?(String)
    lib = Library::LIBC if lib == 'c'

    if lib && File.basename(lib) == lib
      lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/
      r = Platform::IS_GNU ? "\\.so($|\\.[1234567890]+)" : "\\.#{Platform::LIBSUFFIX}$"
      lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/
    end

    lib
  end


    it 'removes existing content types' do
      subject.content_type :xls, 'application/vnd.ms-excel'
      subject.get :excel do
        'some binary content'
      end
      get '/excel.json'
      expect(last_response.status).to eq(406)
      expect(last_response.body).to eq("The requested format 'txt' is not supported.")
    end


  def set_member_and_redirect(member)
    set_member member
    Member::ActivityLog.create(
      cur_site: @cur_site,
      cur_member: member,
      activity_type: "login",
      remote_addr: remote_addr,
      user_agent: request.user_agent)

    ref = URI::decode(params[:ref] || flash[:ref] || "")
    ref = redirect_url if ref.blank?
    flash.discard(:ref)

    redirect_to ref
  end


    it 'should verify a standard RS256 token' do
      domain = 'example.org'
      sub = 'abc123'
      payload = {
        sub: sub,
        exp: future_timecode,
        iss: "https://#{domain}/",
        iat: past_timecode,
        aud: client_id,
        kid: jwks_kid
      }
      token = make_rs256_token(payload)
      verified_token = make_jwt_validator(opt_domain: domain).verify(token)
      expect(verified_token['sub']).to eq(sub)
    end


    def initialize(attribute = nil, direction = nil)
      @attribute = attribute
      @direction = direction || :asc
    end


    it "should raise an error if the image fails an integrity check 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::IntegrityError)
    end


  def updated_ajax
    @user = current_site.users.find(params[:user_id])
    render inline: @user.update(params.require(:password).permit!) ? "" : @user.errors.full_messages.join(', ')
  end


  def mime_magic_content_type(new_file)
    content_type = nil

    File.open(new_file.path) do |fd|
      content_type = Marcel::MimeType.for(fd)
    end

    content_type
  end


  def group_link(uniqueid, data)
    notification = t(
      "notifications.group.#{data[:type]}",
      name: data[:user],
      group_name: data[:group]
    )
    link = "/groups/#{data[:group_id]}"
    notification_link(uniqueid, link, notification)
  end


    it "should get a 200 with html for an authorized user" do

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

      get "/message-bus/_diagnostics"
      last_response.status.must_equal 200
    end


    it "should return a 403 if a user attempts to get at the _diagnostics path" do
      get "/message-bus/_diagnostics"
      last_response.status.must_equal 403
    end


    def base_api_url
      computed_api_endpoint = "https://#{get_data_center_from_api_key(self.api_key)}api.mailchimp.com"
      raise Gibbon::GibbonError, "SSRF attempt" unless URI(computed_api_endpoint).host.include?("api.mailchimp.com")

      "#{self.api_endpoint || computed_api_endpoint}/3.0/"
    end


func TestReadRequest_BadConnectHost(t *testing.T) {
	data := []byte("CONNECT []%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a HTTP/1.0\n\n")
	r, err := ReadRequest(bufio.NewReader(bytes.NewReader(data)))
	if err == nil {
		t.Fatal("Got unexpected request = %#v", r)
	}
}


func SearchUserByName(opt SearchOption) (us []*User, err error) {
	opt.Keyword = FilterSQLInject(opt.Keyword)
	if len(opt.Keyword) == 0 {
		return us, nil
	}
	opt.Keyword = strings.ToLower(opt.Keyword)

	us = make([]*User, 0, opt.Limit)
	err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
	return us, err
}


func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {
	buffer := make([]byte, len(aad)+len(nonce)+len(ciphertext)+8)
	n := 0
	n += copy(buffer, aad)
	n += copy(buffer[n:], nonce)
	n += copy(buffer[n:], ciphertext)
	binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad)*8))

	// According to documentation, Write() on hash.Hash never fails.
	hmac := hmac.New(ctx.hash, ctx.integrityKey)
	_, _ = hmac.Write(buffer)

	return hmac.Sum(nil)[:ctx.authtagBytes]
}


func main() {
	if len(os.Args) < 3 {
		fatal(usage)
	}

	cmd, filename := os.Args[1], os.Args[2]

	ff := archiver.MatchingFormat(filename)
	if ff == nil {
		fatalf("%s: Unsupported file extension", filename)
	}

	var err error
	switch cmd {
	case "make":
		if len(os.Args) < 4 {
			fatal(usage)
		}
		err = ff.Make(filename, os.Args[3:])
	case "open":
		dest := ""
		if len(os.Args) == 4 {
			dest = os.Args[3]
		} else if len(os.Args) > 4 {
			fatal(usage)
		}
		err = ff.Open(filename, dest)
	default:
		fatal(usage)
	}
	if err != nil {
		fatal(err)
	}
}


func validateAndCreateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) {
	c.Data["Webhook"] = w

	if c.HasError() {
		c.Success(orCtx.TmplNew)
		return
	}

	field, msg, ok := validateWebhook(c.User, c.Locale, w)
	if !ok {
		c.FormErr(field)
		c.RenderWithErr(msg, orCtx.TmplNew, nil)
		return
	}

	if err := w.UpdateEvent(); err != nil {
		c.Error(err, "update event")
		return
	} else if err := db.CreateWebhook(w); err != nil {
		c.Error(err, "create webhook")
		return
	}

	c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
	c.Redirect(orCtx.Link + "/settings/hooks")
}


func TestSkipUnknownTypeBinaryProtocol(t *testing.T) {
	var m MyTestStruct
	d := NewDeserializer()
	f := NewBinaryProtocolFactoryDefault()
	d.Protocol = f.GetProtocol(d.Transport)
	// skip over a map with invalid key/value type and 1.7B entries
	data := []byte("\n\x10\rO\t6\x03\n\n\n\x10\r\n\tslice\x00")
	start := time.Now()
	err := d.Read(&m, data)
	if err == nil {
		t.Fatalf("Parsed invalid message correctly")
	} else if !strings.Contains(err.Error(), "unknown type") {
		t.Fatalf("Failed for reason besides unknown type")
	}

	if time.Now().Sub(start).Seconds() > 5 {
		t.Fatalf("It should not take seconds to parse a small message")
	}
}


	appendMessage = func(targetOffset uint32) bool {
		for _, f := range frags {
			if f.handshakeHeader.FragmentOffset == targetOffset {
				fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)
				if fragmentEnd != f.handshakeHeader.Length {
					if !appendMessage(fragmentEnd) {
						return false
					}
				}

				rawMessage = append(f.data, rawMessage...)
				return true
			}
		}
		return false
	}


func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.")
	h.L.Warnln("A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.")

	w.Write([]byte(`

	<title>Misconfigured consent/login URL</title>

	It looks like you forgot to set the consent/login provider url, which can be set using the OAUTH2_CONSENT_URL and OAUTH2_LOGIN_URL
	environment variable.

	If you are an administrator, please read
	the guide to understand what you need to do. If you are a user, please contact the administrator.

`))
}


func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.")

	fmt.Fprintf(w, `

	<title>An OAuth 2.0 Error Occurred</title>

	The OAuth2 request resulted in an error.

Error: %s

Description: %s

Hint: %s

Debug: %s

	You are seeing this default error page because the administrator has not set a dedicated error URL (environment variable OAUTH2_ERROR_URL is not set).
	If you are an administrator, please read the guide to understand what you
	need to do. If you are a user, please contact the administrator.

`, r.URL.Query().Get("error"), r.URL.Query().Get("error_description"), r.URL.Query().Get("error_hint"), r.URL.Query().Get("error_debug"))
}


		patches.forEach(patch => {
			const {path, op} = patch

			let base: any = draft
			for (let i = 0; i < path.length - 1; i++) {
				const parentType = getArchtype(base)
				const p = path[i]
				// See #738, avoid prototype pollution
				if (
					(parentType === Archtype.Object || parentType === Archtype.Array) &&
					(p === "__proto__" || p === "constructor")
				)
					die(24)
				if (typeof base === "function" && p === "prototype") die(24)
				base = get(base, p)
				if (typeof base !== "object") die(15, path.join("/"))
			}


func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {
	pluginID := web.Params(c.Req)[":pluginId"]
	plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)
	if !exists {
		c.JsonApiErr(404, "Plugin not found", nil)
		return
	}

	requestedFile := filepath.Clean(web.Params(c.Req)["*"])
	pluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)

	if !plugin.IncludedInSignature(requestedFile) {
		hs.log.Warn("Access to requested plugin file will be forbidden in upcoming Grafana versions as the file "+
			"is not included in the plugin signature", "file", requestedFile)
	}

	// It's safe to ignore gosec warning G304 since we already clean the requested file path and subsequently
	// use this with a prefix of the plugin's directory, which is set during plugin loading
	// nolint:gosec
	f, err := os.Open(pluginFilePath)
	if err != nil {
		if os.IsNotExist(err) {
			c.JsonApiErr(404, "Plugin file not found", err)
			return
		}
		c.JsonApiErr(500, "Could not open plugin file", err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			hs.log.Error("Failed to close file", "err", err)
		}
	}()

	fi, err := f.Stat()
	if err != nil {
		c.JsonApiErr(500, "Plugin file exists but could not open", err)
		return
	}

	if hs.Cfg.Env == setting.Dev {
		c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
	} else {
		c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
	}

	http.ServeContent(c.Resp, c.Req, pluginFilePath, fi.ModTime(), f)
}


func (x *GetWalletLedgerRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[45]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*MatchState) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{31}
}


func (x *ListGroupsRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[27]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (x *ListSubscriptionsRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[29]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (*MatchStateRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{32}
}


func (x *LeaderboardRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[25]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}


func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.AuthenticateRequest) (*console.ConsoleSession, error) {
	role := console.UserRole_USER_ROLE_UNKNOWN
	var uname string
	var email string
	var id uuid.UUID
	switch in.Username {
	case s.config.GetConsole().Username:
		if in.Password == s.config.GetConsole().Password {
			role = console.UserRole_USER_ROLE_ADMIN
			uname = in.Username
			id = uuid.Nil
		}
	default:
		var err error
		id, uname, email, role, err = s.lookupConsoleUser(ctx, in.Username, in.Password)
		if err != nil {
			return nil, err
		}
	}

	if role == console.UserRole_USER_ROLE_UNKNOWN {
		return nil, status.Error(codes.Unauthenticated, "Invalid credentials.")
	}

	exp := time.Now().UTC().Add(time.Duration(s.config.GetConsole().TokenExpirySec) * time.Second).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ConsoleTokenClaims{
		ExpiresAt: exp,
		ID:        id.String(),
		Username:  uname,
		Email:     email,
		Role:      role,
		Cookie:    s.cookie,
	})
	key := []byte(s.config.GetConsole().SigningKey)
	signedToken, _ := token.SignedString(key)

	s.consoleSessionCache.Add(id, exp, signedToken, 0, "")
	return &console.ConsoleSession{Token: signedToken}, nil
}


func AppList(c *gin.Context) {

	//service.MyService.Docker().DockerContainerCommit("test2")

	index := c.DefaultQuery("index", "1")
	size := c.DefaultQuery("size", "10000")
	t := c.DefaultQuery("type", "rank")
	categoryId := c.DefaultQuery("category_id", "0")
	key := c.DefaultQuery("key", "")
	recommend, list, community := service.MyService.OAPI().GetServerList(index, size, t, categoryId, key)
	// for i := 0; i < len(recommend); i++ {
	// 	ct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion)
	// 	if ct != nil {
	// 		recommend[i].State = ct.State
	// 	}
	// }
	// for i := 0; i < len(list); i++ {
	// 	ct, _ := service.MyService.Docker().DockerListByImage(list[i].Image, list[i].ImageVersion)
	// 	if ct != nil {
	// 		list[i].State = ct.State
	// 	}
	// }
	// for i := 0; i < len(community); i++ {
	// 	ct, _ := service.MyService.Docker().DockerListByImage(community[i].Image, community[i].ImageVersion)
	// 	if ct != nil {
	// 		community[i].State = ct.State
	// 	}
	// }
	data := make(map[string]interface{}, 3)
	data["recommend"] = recommend
	data["list"] = list
	data["community"] = community

	c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
}


                content: Buffer.concat(buffers),
                mimeType: resp.headers["content-type"] || null,
              });
            });


  _resolvePath(path = '.') {
    const clientPath = (() => {
      path = nodePath.normalize(path);
      if (nodePath.isAbsolute(path)) {
        return nodePath.join(path);
      } else {
        return nodePath.join(this.cwd, path);
      }
    })();

    const fsPath = (() => {
      const resolvedPath = nodePath.join(this.root, clientPath);
      return nodePath.resolve(nodePath.normalize(nodePath.join(resolvedPath)));
    })();

    return {
      clientPath,
      fsPath
    };
  }


function networkStats(ifaces, callback) {

  let ifacesArray = [];
  // fallback - if only callback is given
  if (util.isFunction(ifaces) && !callback) {
    callback = ifaces;
    ifacesArray = [getDefaultNetworkInterface()];
  } else {
    ifaces = ifaces || getDefaultNetworkInterface();
    ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
    ifacesArray = ifaces.split('|');
  }

  return new Promise((resolve) => {
    process.nextTick(() => {

      const result = [];

      const workload = [];
      if (ifacesArray.length && ifacesArray[0].trim() === '*') {
        ifacesArray = [];
        networkInterfaces(false).then(allIFaces => {
          for (let iface of allIFaces) {
            ifacesArray.push(iface.iface);
          }
          networkStats(ifacesArray.join(',')).then(result => {
            if (callback) { callback(result); }
            resolve(result);
          });
        });
      } else {
        for (let iface of ifacesArray) {
          workload.push(networkStatsSingle(iface.trim()));
        }
        if (workload.length) {
          Promise.all(
            workload
          ).then(data => {
            if (callback) { callback(data); }
            resolve(data);
          });
        } else {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
    });
  });
}


function has(target, path) {
    "use strict";
    try {
        var test = reduce(target, path);
        if ( typeof test !== "undefined") {
            return true;
        }
        return false;
    } catch(ex) {
        console.error(ex);
        return;
    }
}


		([ key, value ]) => ({ [key]: exec.bind(null, value) }),
	),


		([ key, value ]) => ({ [key]: list.bind(null, value) }),
	),


    Object.keys(data).forEach((key) => {
      obj.add(deserializer(data[key], baseType) as T);
    });


    schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propertyMetadata.type)};
  }

  schemaTypeOptions = cleanProps({...schemaTypeOptions, ...rawMongooseSchema});

  if (propertyMetadata.isCollection) {
    if (propertyMetadata.isArray) {
      schemaTypeOptions = [schemaTypeOptions];
    } else {
      // Can be a Map or a Set;
      // Mongoose implements only Map;
      if (propertyMetadata.collectionType !== Map) {
        throw new Error(`Invalid collection type. ${propertyMetadata.collectionName} is not supported.`);
      }

      schemaTypeOptions = {type: Map, of: schemaTypeOptions};
    }
  }

  return schemaTypeOptions;
}


  constructor({asset, message, onClick}: Params, element: HTMLElement) {
    super(message);
    this.asset = asset;
    this.message = message;
    this.isVisible = ko.observable(false);
    this.onClick = (_data, event) => onClick(message, event);

    this.dummyImageUrl = `data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 1 1' width='${asset.width}' height='${asset.height}'></svg>`;

    this.imageUrl = ko.observable();

    this.isIdle = () => this.uploadProgress() === -1 && !this.asset.resource() && !this.message.isObfuscated();

    ko.computed(
      () => {
        if (this.isVisible() && asset.resource()) {
          this.assetRepository
            .load(asset.resource())
            .then(blob => {
              this.imageUrl(window.URL.createObjectURL(blob));
            })
            .catch(error => console.error(error));
        }
      },
      {disposeWhenNodeIsRemoved: element},
    );

    this.container = element;
    viewportObserver.onElementInViewport(this.container, () => this.isVisible(true));
  }


export async function loadFromGit(input: Input): Promise<string | never> {
  try {
    return await new Promise((resolve, reject) => {
      exec(createCommand(input), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });
  } catch (error) {
    throw createLoadError(error);
  }
}


      switchToInvites: async () => {
        await this.waitAndClick('.e_InvTabB');
        await this.invitedUsersList.waitUntilLoaded();
      },


export function html(m, keyPath, ...args) {
  const html = str(m, keyPath, ...args);

  return html ? React.createElement('span', { dangerouslySetInnerHTML: { __html: html } }) : null;
}


      `${c.amount(d.value, d.name)}<em>${day(d.date)}</em>`,
  });
}


export function initSidebar(): void {
  const errorCountEl = document.getElementById("error-count");
  if (errorCountEl instanceof HTMLLIElement) {
    errorCount.subscribe((errorCount_val) => {
      errorCountEl.classList.toggle("hidden", errorCount_val === 0);
      const span = errorCountEl.querySelector("span");
      if (span) {
        span.innerHTML = `${errorCount_val}`;
      }
    });
  }

  const asideButton = document.getElementById("aside-button");
  if (asideButton instanceof HTMLButtonElement) {
    asideButton.addEventListener("click", () => {
      document.querySelector("aside")?.classList.toggle("active");
      asideButton.classList.toggle("active");
    });
  }
}


function text({ url, host }: Record<"url" | "host", string>) {
  return `Sign in to ${host}\n${url}\n\n`
}