jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def attachments_without_content

    return [] if self.id.nil?

    sql = 'select id, title, memo, name, size, content_type, comment_id, xorder, location from attachments'
    sql << ' where comment_id=' + self.id.to_s
    sql << ' order by xorder ASC'
    begin
      attachments = Attachment.find_by_sql(sql)
    rescue => evar
      Log.add_error(nil, evar)
    end
    attachments = [] if attachments.nil?
    return attachments
  end
//  [ruby]
    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_template("recaptcha.html")
//  [ruby]
    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]
//  [ruby]
  def self.get_for(user_id, fiscal_year=nil)

    SqlHelper.validate_token([user_id, fiscal_year])

    begin
      con = []
      con << "(user_id=#{user_id.to_i})"
      if fiscal_year.nil?
        return PaidHoliday.where(con).order('year ASC').to_a
      else
        con << "(year=#{fiscal_year.to_i})"
        return PaidHoliday.where(con.join(' and ')).first
      end
    rescue
    end
    return nil
  end
//  [ruby]
  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
//  [ruby]
  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.to_i}) and (year < #{year.to_i})"
      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
//  [ruby]
  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
//  [ruby]
  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.to_i})"
      con << "(year=#{fiscal_year.to_i})"
      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
//  [ruby]
  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
//  [ruby]
  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.to_i}"
    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
//  [ruby]
  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
//  [ruby]
  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.to_i})"
      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.to_i})"
      where << ' and ('
      where <<      "((Folder.xtype='#{XTYPE_GROUP}') and (Folder.owner_id=#{group_id.to_i}))"
      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
//  [ruby]
  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
//  [ruby]
  def test_parse_bigger
    xml = <<-XML.strip_heredoc
      <request id="1027" creator="Iggy">
        <action type="submit">
          <source project="home:Iggy" package="TestPack" rev="1"/>
          <target project="kde4" package="mypackage"/>
          <options>
            <sourceupdate>cleanup</sourceupdate>
          </options>
          <acceptinfo rev="1" srcmd5="806a6e27ed7915d1bb8d8a989404fd5a" osrcmd5="d41d8cd98f00b204e9800998ecf8427e"/>
        </action>
        <priority>critical</priority>
        <state name="review" who="Iggy" when="2012-11-07T21:13:12">
          <comment>No comment</comment>
        </state>
        <review state="new" when="2017-09-01T09:11:11" by_user="adrian"/>
        <review state="new" when="2017-09-01T09:11:11" by_group="test_group"/>
        <review state="accepted" when="2012-11-07T21:13:12" who="tom" by_user="tom">
          <comment>review1</comment>
        </review>
        <review state="new" when="2012-11-07T21:13:13" who="tom" by_user="tom">
          <comment>please accept</comment>
        </review>
        <description>Left blank</description>
      </request>
    XML
    req = BsRequest.new_from_xml(xml)
    req.save!
    # number got increased by one
    assert_equal 1027, req.number

    newxml = req.render_xml
    expected = <<-XML.strip_heredoc
      <request id="1027" creator="Iggy">
        <action type="submit">
          <source project="home:Iggy" package="TestPack" rev="1"/>
          <target project="kde4" package="mypackage"/>
          <options>
            <sourceupdate>cleanup</sourceupdate>
          </options>
          <acceptinfo rev="1" srcmd5="806a6e27ed7915d1bb8d8a989404fd5a" osrcmd5="d41d8cd98f00b204e9800998ecf8427e"/>
        </action>
        <priority>critical</priority>
        <state name="review" who="Iggy" when="2012-11-07T21:13:12">
          <comment>No comment</comment>
        </state>
        <review state="new" when="2017-09-01T09:11:11" by_user="adrian"/>
        <review state="new" when="2017-09-01T09:11:11" by_group="test_group"/>
        <review state="new" when="2012-11-07T21:13:12" who="tom" by_user="tom">
          <comment>review1</comment>
        </review>
        <review state="new" when="2012-11-07T21:13:13" who="tom" by_user="tom">
          <comment>please accept</comment>
        </review>
        <description>Left blank</description>
      </request>
    XML
    assert_equal expected, newxml

    wi = req.webui_infos(diffs: false)
    # iggy is *not* target maintainer
    assert_equal false, wi['is_target_maintainer']
    assert_equal wi['actions'][0], type: :submit,
                                   sprj: 'home:Iggy',
                                   spkg: 'TestPack',
                                   srev: '1',
                                   tprj: 'kde4',
                                   tpkg: 'mypackage',
                                   name: 'Submit TestPack'
  end
//  [ruby]
  def test_parse_bigger
    xml = <<-XML.strip_heredoc
      <request id="1027" creator="Iggy">
        <action type="submit">
          <source project="home:Iggy" package="TestPack" rev="1"/>
          <target project="kde4" package="mypackage"/>
          <options>
            <sourceupdate>cleanup</sourceupdate>
          </options>
          <acceptinfo rev="1" srcmd5="806a6e27ed7915d1bb8d8a989404fd5a" osrcmd5="d41d8cd98f00b204e9800998ecf8427e"/>
        </action>
        <priority>critical</priority>
        <state name="review" who="Iggy" when="2012-11-07T21:13:12">
          <comment>No comment</comment>
        </state>
        <review state="new" when="2017-09-01T09:11:11" by_user="adrian"/>
        <review state="new" when="2017-09-01T09:11:11" by_group="test_group"/>
        <review state="accepted" when="2012-11-07T21:13:12" who="tom" by_user="tom">
          <comment>review1</comment>
        </review>
        <review state="new" when="2012-11-07T21:13:13" who="tom" by_user="tom">
          <comment>please accept</comment>
        </review>
        <description>Left blank</description>
      </request>
    XML
    req = BsRequest.new_from_xml(xml)
    req.save!
    # number got increased by one
    assert_equal 1027, req.number

    newxml = req.render_xml
    assert_equal xml, newxml

    wi = req.webui_infos(diffs: false)
    # iggy is *not* target maintainer
    assert_equal false, wi['is_target_maintainer']
    assert_equal wi['actions'][0], type: :submit,
                                   sprj: 'home:Iggy',
                                   spkg: 'TestPack',
                                   srev: '1',
                                   tprj: 'kde4',
                                   tpkg: 'mypackage',
                                   name: 'Submit TestPack'
  end
//  [ruby]
      def find(uuid, options = {})
        if uuid.nil? || uuid.to_s.empty?
          raise NotFound, "can't find a record with nil identifier"
        end

        begin
          from_response API.get(member_path(uuid), {}, options)
        rescue API::NotFound => e
          raise NotFound, e.description
        end
      end
//  [ruby]
      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
//  [ruby]
  def update_by_ajax
    Log.add_info(request, params.inspect)

    return unless request.post?

    cat_h = {:desktop => User::AUTH_DESKTOP, :user => User::AUTH_USER, :log => User::AUTH_LOG}

    yaml = ApplicationHelper.get_config_yaml

    cat_h.keys.each do |cat|

      next if params[cat].blank?

      unless @login_user.admin?(cat_h[cat])
        render(:text => t('msg.need_to_be_admin'))
        return
      end

      yaml[cat] ||= {}

      params[cat].each do |key, val|
        yaml[cat][key] = val
      end
    end

    ApplicationHelper.save_config_yaml(yaml)

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

    cat_h = {:desktop => User::AUTH_DESKTOP, :user => User::AUTH_USER, :log => User::AUTH_LOG}

    yaml = ApplicationHelper.get_config_yaml

    cat_h.keys.each do |cat|

      next if params[cat].nil? or params[cat].empty?

      unless @login_user.admin?(cat_h[cat])
        render(:text => t('msg.need_to_be_admin'))
        return
      end

      yaml[cat] ||= {}

      params[cat].each do |key, val|
        yaml[cat][key] = val
      end
    end

    ApplicationHelper.save_config_yaml(yaml)

    render(:text => '')
  end
//  [ruby]
  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.to_i}"

      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
//  [ruby]
  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
//  [ruby]
  def check_owner

    return if (params[:id].blank? or @login_user.nil?)

    address = Address.find(params[:id])

    if !@login_user.admin?(User::AUTH_ADDRESSBOOK) and address.owner_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

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

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

    address = Address.find(params[:id])

    if !@login_user.admin?(User::AUTH_ADDRESSBOOK) and address.owner_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def self.get_copies_folder(user_id)

    my_folder = User.get_my_folder(user_id)

    unless my_folder.nil?
      folder_name_quot = SqlHelper.quote(Item.copies_folder)
      con = "(parent_id=#{my_folder.id}) and (name=#{folder_name_quot})"

      begin
        copies_folder = Folder.where(con).first
      rescue
      end
      if copies_folder.nil?
        folder = Folder.new
        folder.name = Item.copies_folder
        folder.parent_id = my_folder.id
        folder.owner_id = user_id.to_i
        folder.xtype = nil
        folder.read_users = '|' + user_id.to_s + '|'
        folder.write_users = '|' + user_id.to_s + '|'
        folder.save!

        copies_folder = folder
      end
    end

    return copies_folder
  end
//  [ruby]
  def self.get_copies_folder(user_id)

    my_folder = User.get_my_folder(user_id)

    unless my_folder.nil?
      con = "(parent_id=#{my_folder.id}) and (name='#{Item.copies_folder}')"

      begin
        copies_folder = Folder.where(con).first
      rescue
      end
      if copies_folder.nil?
        folder = Folder.new
        folder.name = Item.copies_folder
        folder.parent_id = my_folder.id
        folder.owner_id = user_id.to_i
        folder.xtype = nil
        folder.read_users = '|' + user_id.to_s + '|'
        folder.write_users = '|' + user_id.to_s + '|'
        folder.save!

        copies_folder = folder
      end
    end

    return copies_folder
  end
//  [ruby]
  def self.create_user_from_invite(email:, invite:, username: nil, name: nil, password: nil, user_custom_fields: nil, ip_address: nil, session: nil, email_token: nil)
    if username && UsernameValidator.new(username).valid_format? && User.username_available?(username, email)
      available_username = username
    else
      available_username = UserNameSuggester.suggest(email)
    end

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

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

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

    if (!SiteSetting.must_approve_users && SiteSetting.invite_only) ||
       (SiteSetting.must_approve_users? && EmailValidator.can_auto_approve_user?(user.email))

      ReviewableUser.set_approved_fields!(user, Discourse.system_user)
    end

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

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

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

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

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

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

    authenticator.start

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

    user.save!
    authenticator.finish

    if invite.emailed_status != Invite.emailed_status_types[:not_required] && email == invite.email && invite.email_token.present? && email_token == invite.email_token
      user.activate
    end

    User.find(user.id)
  end
//  [ruby]
  def self.create_user_from_invite(email:, invite:, username: nil, name: nil, password: nil, user_custom_fields: nil, ip_address: nil, session: nil, email_token: nil)
    if username && UsernameValidator.new(username).valid_format? && User.username_available?(username, email)
      available_username = username
    else
      available_username = UserNameSuggester.suggest(email)
    end

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

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

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

    if SiteSetting.must_approve_users? && EmailValidator.can_auto_approve_user?(user.email)
      ReviewableUser.set_approved_fields!(user, Discourse.system_user)
    end

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

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

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

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

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

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

    authenticator.start

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

    user.save!
    authenticator.finish

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

    User.find(user.id)
  end
//  [ruby]
  def self.exists_copies_folder?(user_id)

    my_folder = User.get_my_folder(user_id)

    unless my_folder.nil?
      folder_name_quot = SqlHelper.quote(Item.copies_folder)
      con = "(parent_id=#{my_folder.id}) and (name=#{folder_name_quot})"

      begin
        copies_folder = Folder.where(con).first
      rescue
      end
    end

    return !copies_folder.nil?
  end
//  [ruby]
  def self.exists_copies_folder?(user_id)

    my_folder = User.get_my_folder(user_id)

    unless my_folder.nil?
      con = "(parent_id=#{my_folder.id}) and (name='#{Item.copies_folder}')"

      begin
        copies_folder = Folder.where(con).first
      rescue
      end
    end

    return !copies_folder.nil?
  end
//  [ruby]
  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
//  [ruby]
  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
//  [ruby]
  def self.execute_action_move(mail_filter, email, val)

    mail_folder_id = val
    SqlHelper.validate_token([mail_folder_id])

    begin
      mail_folder = MailFolder.find(mail_folder_id)
    rescue => evar
    end
    if !mail_folder.nil? and (mail_folder.user_id == email.user_id)
      email.update_attribute(:mail_folder_id, mail_folder_id)
    end

    return true
  end
//  [ruby]
  def self.execute_action_move(mail_filter, email, val)

    mail_folder_id = val

    mail_folder = MailFolder.find_by_id(mail_folder_id)
    if !mail_folder.nil? and (mail_folder.user_id == email.user_id)
      email.update_attribute(:mail_folder_id, mail_folder_id)
    end

    return true
  end
//  [ruby]
  def self.get_next_revision(user_id, source_id)

    SqlHelper.validate_token([user_id, source_id])

    copied_items = Item.where("user_id=#{user_id.to_i} and source_id=#{source_id.to_i}").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
//  [ruby]
  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
//  [ruby]
  def html_postprocess(_field, html)
    helper = ContentTextHelpers.new
    helper.sanitize(helper.auto_link(html), tags: self.class.allowed_tags)
  end
//  [ruby]
  def html_postprocess(_field, html)
    helper = ContentTextHelpers.new
    helper.sanitize(helper.auto_link(html))
  end
//  [ruby]
    def self.open(path_or_url, ext = nil, options = {})
      options, ext = ext, nil if ext.is_a?(Hash)

      uri = URI(path_or_url.to_s)

      ext ||= File.extname(uri.path)
      ext.sub!(/:.*/, '') # hack for filenames or URLs that include a colon

      if uri.is_a?(URI::HTTP) || uri.is_a?(URI::FTP)
        uri.open(options) { |file| read(file, ext) }
      else
        File.open(uri.to_s, "rb", options) { |file| read(file, ext) }
      end
    end
//  [ruby]
    def self.open(path_or_url, ext = nil, options = {})
      options, ext = ext, nil if ext.is_a?(Hash)

      ext ||=
        if File.exist?(path_or_url)
          File.extname(path_or_url)
        else
          File.extname(URI(path_or_url).path)
        end

      ext.sub!(/:.*/, '') # hack for filenames or URLs that include a colon

      Kernel.open(path_or_url, "rb", options) do |file|
        read(file, ext)
      end
    end
//  [ruby]
  def html_postprocess(_field, html)
    helper = ContentTextHelpers.new
    helper.sanitize html
  end
//  [ruby]
  def html_postprocess(_field, html)
    html
  end
//  [ruby]
    def self.run_gpg(*args)
      fragments = [
        'gpg',
        '--no-default-keyring'
      ] + args
      command_line = fragments.collect { |fragment| Shellwords.escape(fragment) }.join(' ')

      output_file = Tempfile.new('gpg-output')
      begin
        output_file.close
        result = system("#{command_line} > #{Shellwords.escape(output_file.path)} 2>&1")
      ensure
        output_file.unlink
      end
      raise RuntimeError.new('gpg failed') unless result
    end
//  [ruby]
    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
//  [ruby]
    it "should find a user by first name and last name" do
      @cur_user.stub(:pref).and_return(:activity_user => 'Billy Elliot')
      controller.instance_variable_set(:@current_user, @cur_user)
      User.should_receive(:where).with(:first_name => 'Billy', :last_name => "Elliot").and_return([@user])
      User.should_receive(:where).with(:first_name => 'Elliot', :last_name => "Billy").and_return([@user])
      controller.send(:activity_user).should == 1
    end
//  [ruby]
    it "should find a user by first name and last name" do
      @cur_user.stub(:pref).and_return(:activity_user => 'Billy Elliot')
      controller.instance_variable_set(:@current_user, @cur_user)
      User.should_receive(:where).with("(upper(first_name) LIKE upper('%Billy%') AND upper(last_name) LIKE upper('%Elliot%')) OR (upper(first_name) LIKE upper('%Elliot%') AND upper(last_name) LIKE upper('%Billy%'))").and_return([@user])
      controller.send(:activity_user).should == 1
    end
//  [ruby]
  def set_inboxes
    @inbox_ids = if params[:inbox_id]
                   @current_user.assigned_inboxes.where(id: params[:inbox_id])
                 else
                   @current_user.assigned_inboxes.pluck(:id)
                 end
//  [ruby]
  def set_inboxes
    @inbox_ids = if params[:inbox_id]
                   current_account.inboxes.where(id: params[:inbox_id])
                 else
                   @current_user.assigned_inboxes.pluck(:id)
                 end
//  [ruby]
        def __bson_load__(io)
          from_data(io.read(12))
        end
//  [ruby]
        def __bson_load__(io)
          new io.read(12).unpack('C*')
        end
//  [ruby]
    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(:first_name => 'Billy').and_return([@user])
      User.should_receive(:where).with(:last_name => 'Billy').and_return([@user])
      controller.send(:activity_user).should == 1
    end
//  [ruby]
    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
//  [ruby]
      def __bson_dump__(io, key)
        io << Types::OBJECT_ID
        io << key
        io << NULL_BYTE
        io << data
      end
//  [ruby]
      def __bson_dump__(io, key)
        io << Types::OBJECT_ID
        io << key
        io << NULL_BYTE
        io << data.pack('C12')
      end
//  [ruby]
        def generate(time, counter = 0)
          [time, @machine_id, Process.pid, counter << 8].pack("N NX lXX NX")
        end
//  [ruby]
        def generate(time, inc = 0)
          pid = Process.pid % 0xFFFF

          [
            time >> 24 & 0xFF, # 4 bytes time (network order)
            time >> 16 & 0xFF,
            time >> 8  & 0xFF,
            time       & 0xFF,
            @machine_id[0],   # 3 bytes machine
            @machine_id[1],
            @machine_id[2],
            pid  >> 8  & 0xFF, # 2 bytes process id
            pid        & 0xFF,
            inc  >> 16 & 0xFF, # 3 bytes increment
            inc  >> 8  & 0xFF,
            inc        & 0xFF,
          ]
        end
//  [ruby]
    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 #{Shellwords.escape(script_file.path)}")
        raise RuntimeError.new('gpg failed') unless result
      ensure
        script_file.close
        script_file.unlink
      end
    end
//  [ruby]
    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
//  [ruby]
        def initialize
          # Generate and cache 3 bytes of identifying information from the current
          # machine.
          @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("N")[0]

          @mutex = Mutex.new
          @counter = 0
        end
//  [ruby]
        def initialize
          # Generate and cache 3 bytes of identifying information from the current
          # machine.
          @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("C3")

          @mutex = Mutex.new
          @last_timestamp = nil
          @counter = 0
        end
//  [ruby]
        def from_string(string)
          raise Errors::InvalidObjectId.new(string) unless legal?(string)
          data = ""
          12.times { |i| data << string[i*2, 2].to_i(16) }
          from_data data
        end
//  [ruby]
        def from_string(string)
          raise Errors::InvalidObjectId.new(string) unless legal?(string)
          data = []
          12.times { |i| data << string[i*2, 2].to_i(16) }
          new data
        end
//  [ruby]
        def next
          @mutex.lock
          begin
            counter = @counter = (@counter + 1) % 0xFFFFFF
          ensure
            @mutex.unlock rescue nil
          end

          generate(Time.new.to_i, counter)
        end
//  [ruby]
        def next
          now = Time.new.to_i

          counter = @mutex.synchronize do
            last_timestamp, @last_timestamp = @last_timestamp, now

            if last_timestamp == now
              @counter += 1
            else
              @counter = 0
            end
          end

          generate(now, counter)
        end
//  [ruby]
        def legal?(str)
          !!str.match(/\A\h{24}\Z/i)
        end
//  [ruby]
        def legal?(str)
          !!str.match(/^[0-9a-f]{24}$/i)
        end
//  [ruby]
      def to_s
        @@string_format % data.unpack("C12")
      end
//  [ruby]
      def to_s
        @@string_format % data
      end
//  [ruby]
  def is_a_copy?(folder_obj_cache=nil)

    return false if self.source_id.nil?

    # Exclude those created from system templates.
    begin
      src_item = Item.find(self.source_id)
    rescue => evar
      src_item = nil
    end
    if src_item.nil?
      return true
    else
      return !src_item.in_system_folder?(folder_obj_cache)
    end
  end
//  [ruby]
  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
//  [ruby]
      def html_message
        key  = CGI.escape_html titleize(keys.last)
        path = CGI.escape_html keys.join('.')
        %(<span class="translation_missing" title="translation missing: #{path}">#{key}</span>)
      end

      def keys
        @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
          keys << 'no key' if keys.size < 2
        end
      end

      def message
        "translation missing: #{keys.join('.')}"
      end
      alias :to_s :message

      def to_exception
        MissingTranslationData.new(locale, key, options)
      end

      protected

      # TODO : remove when #html_message is removed
      def titleize(key)
        key.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
      end
    end
//  [ruby]
      def html_message
        key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
        %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
//  [ruby]
  def login
    Log.add_info(request, '')   # Not to show passwords.

    user = User.authenticate(params[:user])

    if user.nil?

      flash[:notice] = '<span class=\'font_msg_bold\'>'+t('user.u_name')+'</span>'+t('msg.or')+'<span class=\'font_msg_bold\'>'+t('password.name')+'</span>'+t('msg.is_invalid')

      if params[:fwd_controller].blank?

        redirect_to(:controller => 'login', :action => 'index')
      else

        url_h = {:controller => 'login', :action => 'index', :fwd_controller => params[:fwd_controller], :fwd_action => params[:fwd_action]}

        unless params[:fwd_params].nil?
          params[:fwd_params].each do |key, val|
            url_h["fwd_params[#{key}]"] = val
          end
        end

        redirect_to(url_h)
      end

    else

      @login_user = LoginHelper.on_login(user, session)

      if params[:fwd_controller].blank?
        prms = ApplicationHelper.get_fwd_params(params)
        prms.delete('user')
        prms[:controller] = 'desktop'
        prms[:action] = 'show'
        redirect_to(prms)
      else
        url_h = {:controller => params[:fwd_controller], :action => params[:fwd_action]}
        url_h = url_h.update(params[:fwd_params]) unless params[:fwd_params].nil?
        redirect_to(url_h)
      end
    end
  end
//  [ruby]
  def login
    Log.add_info(request, '')   # Not to show passwords.

    user = User.authenticate(params[:user])

    if user.nil?

      flash[:notice] = '<span class=\'font_msg_bold\'>'+t('user.u_name')+'</span>'+t('msg.or')+'<span class=\'font_msg_bold\'>'+t('password.name')+'</span>'+t('msg.is_invalid')

      if params[:fwd_controller].nil? or params[:fwd_controller].empty?

        redirect_to(:controller => 'login', :action => 'index')
      else

        url_h = {:controller => 'login', :action => 'index', :fwd_controller => params[:fwd_controller], :fwd_action => params[:fwd_action]}

        unless params[:fwd_params].nil?
          params[:fwd_params].each do |key, val|
            url_h["fwd_params[#{key}]"] = val
          end
        end

        redirect_to(url_h)
      end

    else

      @login_user = LoginHelper.on_login(user, session)

      if params[:fwd_controller].nil? or params[:fwd_controller].empty?
        prms = ApplicationHelper.get_fwd_params(params)
        prms.delete('user')
        prms[:controller] = 'desktop'
        prms[:action] = 'show'
        redirect_to(prms)
      else
        url_h = {:controller => params[:fwd_controller], :action => params[:fwd_action]}
        url_h = url_h.update(params[:fwd_params]) unless params[:fwd_params].nil?
        redirect_to(url_h)
      end
    end
  end
//  [ruby]
      def initialize(locale, key, options = nil)
        @key, @locale, @options = key, locale, options.dup || {}
        options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
      end

      def html_message
        key  = CGI.escape_html titleize(keys.last)
        path = CGI.escape_html keys.join('.')
        %(<span class="translation_missing" title="translation missing: #{path}">#{key}</span>)
      end

      def keys
        @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
          keys << 'no key' if keys.size < 2
        end
      end

      def message
        "translation missing: #{keys.join('.')}"
      end
      alias :to_s :message

      def to_exception
        MissingTranslationData.new(locale, key, options)
      end

      protected

      # TODO : remove when #html_message is removed
      def titleize(key)
        key.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
      end
    end

    include Base
  end
//  [ruby]
      def initialize(locale, key, options = nil)
        @key, @locale, @options = key, locale, options.dup || {}
        options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
      end

      def html_message
        key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
        %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
      end

      def keys
        @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
          keys << 'no key' if keys.size < 2
        end
      end

      def message
        "translation missing: #{keys.join('.')}"
      end