jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def self.setup_tmpl_folder

    begin
      tmpl_folder = Folder.where(name: TMPL_ROOT).first
    rescue
    end
    if tmpl_folder.nil?
      # Setup initial template-folders
      folder = Folder.new
      folder.name = TMPL_ROOT
      folder.parent_id = 0
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_folder = folder
    end

    childs = Folder.where("folders.parent_id=#{tmpl_folder.id}").to_a

    # System
    tmpl_system_folder = childs.find{|child| child.name == TMPL_SYSTEM}
    if tmpl_system_folder.nil?
      folder = Folder.new
      folder.name = TMPL_SYSTEM
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_system_folder = folder

      # System - Profile Sheet
      item = Item.new_profile(tmpl_system_folder.id)
      item.title = Item.profile_title_def
      item.user_id = 0
      item.save!
    end

    # Workflow
    tmpl_workflows_folder = childs.find{|child| child.name == TMPL_WORKFLOWS}
    if tmpl_workflows_folder.nil?
      folder = Folder.new
      folder.name = TMPL_WORKFLOWS
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_workflows_folder = folder
    end

    # Local
    tmpl_local_folder = childs.find{|child| child.name == TMPL_LOCAL}
    if tmpl_local_folder.nil?
      folder = Folder.new
      folder.name = TMPL_LOCAL
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_local_folder = folder
    end

    # Research
    tmpl_q_folder = childs.find{|child| child.name == TMPL_RESEARCH}
    if tmpl_q_folder.nil?
      folder = Folder.new
      folder.name = TMPL_RESEARCH
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_q_folder = folder
    end

    return [tmpl_folder, tmpl_system_folder, tmpl_workflows_folder, tmpl_local_folder, tmpl_q_folder]

  rescue => evar
    Log.add_error(nil, evar)
    return nil
  end
//  [ruby]
  def self.setup_tmpl_folder

    begin
      tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first
    rescue
    end
    if tmpl_folder.nil?
      # Setup initial template-folders
      folder = Folder.new
      folder.name = TMPL_ROOT
      folder.parent_id = 0
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_folder = folder
    end

    childs = Folder.where("folders.parent_id=#{tmpl_folder.id}").to_a

    # System
    tmpl_system_folder = childs.find{|child| child.name == TMPL_SYSTEM}
    if tmpl_system_folder.nil?
      folder = Folder.new
      folder.name = TMPL_SYSTEM
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_system_folder = folder

      # System - Profile Sheet
      item = Item.new_profile(tmpl_system_folder.id)
      item.title = Item.profile_title_def
      item.user_id = 0
      item.save!
    end

    # Workflow
    tmpl_workflows_folder = childs.find{|child| child.name == TMPL_WORKFLOWS}
    if tmpl_workflows_folder.nil?
      folder = Folder.new
      folder.name = TMPL_WORKFLOWS
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_workflows_folder = folder
    end

    # Local
    tmpl_local_folder = childs.find{|child| child.name == TMPL_LOCAL}
    if tmpl_local_folder.nil?
      folder = Folder.new
      folder.name = TMPL_LOCAL
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_local_folder = folder
    end

    # Research
    tmpl_q_folder = childs.find{|child| child.name == TMPL_RESEARCH}
    if tmpl_q_folder.nil?
      folder = Folder.new
      folder.name = TMPL_RESEARCH
      folder.parent_id = tmpl_folder.id
      folder.owner_id = 0
      folder.xtype = Folder::XTYPE_SYSTEM
      folder.save!
      tmpl_q_folder = folder
    end

    return [tmpl_folder, tmpl_system_folder, tmpl_workflows_folder, tmpl_local_folder, tmpl_q_folder]

  rescue => evar
    Log.add_error(nil, evar)
    return nil
  end
//  [ruby]
      def match?(name, ip)
        if ip?
          if pattern.include?(IPAddr.new(ip))
            Puppet.deprecation_warning "Authentication based on IP address is deprecated; please use certname-based rules instead"
            true
          else
            false
          end
        else
          matchname?(name)
        end
      end
//  [ruby]
      def match?(name, ip)
        ip? ? pattern.include?(IPAddr.new(ip)) : matchname?(name)
      end
//  [ruby]
  def day
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.blank?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    if params[:user_id].blank?
      user_id = @login_user.id unless @login_user.nil?
      @schedules = Schedule.get_user_day(@login_user, @date)
    else
      user_id = params[:user_id].to_i
      @schedules = Schedule.get_somebody_day(@login_user, user_id, @date)
    end

    schedule_id = nil
    schedule_id = params[:show_id] unless params[:show_id].nil?
    schedule_id = params[:edit_id] unless params[:edit_id].nil?
    unless schedule_id.nil?
      begin
        @schedule = Schedule.find(schedule_id)

        unless @schedule.check_user_auth(@login_user, 'r', true)

          Log.add_check(request, '[Schedule.check_user_auth]'+request.to_s)

          if @login_user.nil?
            check_login
          else
            redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
          end
          return
        end
      rescue
      end
    end

    if !@login_user.nil? and user_id == @login_user.id and !@schedules.nil?
      equip_ary = []
      @schedules.each do |schedule|
        equip_ary = equip_ary | schedule.get_equipment_a
      end
      overlap_h = {}
      equip_ary.each do |equip_id|
        schedule_ary = Schedule.get_equipment_day(equip_id, @date)
        overlaps = Schedule.check_overlap_equipment(equip_id, schedule_ary, @date)
        unless overlaps.empty?
          overlap_h[equip_id] = overlaps
        end
      end
      unless overlap_h.empty?
        flash[:notice] = 'ERROR:' + t('schedule.conflict_equipment')
        flash[:notice] << '<br/>'
        overlap_h.each do |equip_id, schedule_ary|
          flash[:notice] << '&laquo;' + Equipment.get_name(equip_id) + '&raquo;<br/>'
          flash[:notice] << '<ul style=\'padding-left:40px;\'>'
          schedule_ary.each do |schedule_id|
            flash[:notice] << '<li>' + Schedule.get_title(schedule_id) + '</li>'
          end
          flash[:notice] << '</ul>'
        end
      end
    end

    params[:display] = 'day'
  end
//  [ruby]
  def day
    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 params[:user_id].blank?
      user_id = @login_user.id unless @login_user.nil?
      @schedules = Schedule.get_user_day(@login_user, @date)
    else
      user_id = params[:user_id].to_i
      @schedules = Schedule.get_somebody_day(@login_user, user_id, @date)
    end

    schedule_id = nil
    schedule_id = params[:show_id] unless params[:show_id].nil?
    schedule_id = params[:edit_id] unless params[:edit_id].nil?
    unless schedule_id.nil?
      begin
        @schedule = Schedule.find(schedule_id)

        unless @schedule.check_user_auth(@login_user, 'r', true)

          Log.add_check(request, '[Schedule.check_user_auth]'+request.to_s)

          if @login_user.nil?
            check_login
          else
            redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
          end
          return
        end
      rescue
      end
    end

    if !@login_user.nil? and user_id == @login_user.id and !@schedules.nil?
      equip_ary = []
      @schedules.each do |schedule|
        equip_ary = equip_ary | schedule.get_equipment_a
      end
      overlap_h = {}
      equip_ary.each do |equip_id|
        schedule_ary = Schedule.get_equipment_day(equip_id, @date)
        overlaps = Schedule.check_overlap_equipment(equip_id, schedule_ary, @date)
        unless overlaps.empty?
          overlap_h[equip_id] = overlaps
        end
      end
      unless overlap_h.empty?
        flash[:notice] = 'ERROR:' + t('schedule.conflict_equipment')
        flash[:notice] << '<br/>'
        overlap_h.each do |equip_id, schedule_ary|
          flash[:notice] << '&laquo;' + Equipment.get_name(equip_id) + '&raquo;<br/>'
          flash[:notice] << '<ul style=\'padding-left:40px;\'>'
          schedule_ary.each do |schedule_id|
            flash[:notice] << '<li>' + Schedule.get_title(schedule_id) + '</li>'
          end
          flash[:notice] << '</ul>'
        end
      end
    end

    params[:display] = 'day'
  end
//  [ruby]
  def team
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.blank?
      @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
//  [ruby]
  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
//  [ruby]
  def get_folder_items
    Log.add_info(request, params.inspect)

    unless params[:thetisBoxSelKeeper].blank?
      @folder_id = params[:thetisBoxSelKeeper].split(':').last
    end

    begin
      if Folder.check_user_auth(@folder_id, @login_user, 'r', true)
        @items = Folder.get_items(@login_user, @folder_id)
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    submit_url = url_for(:controller => 'schedules', :action => 'get_folder_items')
    render(:partial => 'common/select_items', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})
  end
//  [ruby]
  def get_folder_items
    Log.add_info(request, params.inspect)

    unless params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      @folder_id = params[:thetisBoxSelKeeper].split(':').last
    end

    begin
      if Folder.check_user_auth(@folder_id, @login_user, 'r', true)
        @items = Folder.get_items(@login_user, @folder_id)
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    submit_url = url_for(:controller => 'schedules', :action => 'get_folder_items')
    render(:partial => 'common/select_items', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})
  end
//  [ruby]
  def group
    Log.add_info(request, params.inspect)

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

    @group_id = params[:id]
    SqlHelper.validate_token([@group_id, params[:id]])
    group_users = Group.get_users(params[:id])

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

    params[:display] = params[:action] + '_' + params[:id]
  end
//  [ruby]
  def group
    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

    @group_id = params[:id]
    group_users = Group.get_users(params[:id])

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

    params[:display] = params[:action] + '_' + params[:id]
  end
//  [ruby]
  def week
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.blank?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end
    params[:display] = 'week'
  end
//  [ruby]
  def week
    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
    params[:display] = 'week'
  end
//  [ruby]
  def self.get_tmpl_subfolder(name)

    SqlHelper.validate_token([name])

    tmpl_folder = Folder.where(name: TMPL_ROOT).first

    unless tmpl_folder.nil?
      name_quot = SqlHelper.quote(name)
      con = "(parent_id=#{tmpl_folder.id}) and (name=#{name_quot})"
      begin
        child = Folder.where(con).first
      rescue => evar
        Log.add_error(nil, evar)
      end
    end

    return [tmpl_folder, child]
  end
//  [ruby]
  def self.get_tmpl_subfolder(name)

    SqlHelper.validate_token([name])

    tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first

    unless tmpl_folder.nil?
      con = "(parent_id=#{tmpl_folder.id}) and (name='#{name}')"
      begin
        child = Folder.where(con).first
      rescue => evar
        Log.add_error(nil, evar)
      end
    end

    return [tmpl_folder, child]
  end
//  [ruby]
  def get_auth_groups
    Log.add_info(request, params.inspect)

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

    begin
      @folder = Folder.find(folder_id)
    rescue
      @folder = nil
    end

    @groups = Group.where(nil).to_a

    session[:folder_id] = folder_id

    render(:partial => 'ajax_auth_groups', :layout => false)
  end
//  [ruby]
  def get_auth_groups
    Log.add_info(request, params.inspect)

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

    @groups = Group.where(nil).to_a

    session[:folder_id] = params[:id]

    render(:partial => 'ajax_auth_groups', :layout => false)
  end
//  [ruby]
  def get_path
    Log.add_info(request, params.inspect)

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

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

    @folder_path = Folder.get_path(@selected_id)

    render(:partial => 'ajax_folder_path', :layout => false)
  end
//  [ruby]
  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
//  [ruby]
  def get_auth_users
    Log.add_info(request, params.inspect)

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

    begin
      @folder = Folder.find(folder_id)
    rescue
      @folder = nil
    end

    @users = []

    session[:folder_id] = folder_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
//  [ruby]
  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
//  [ruby]
  def rename
    Log.add_info(request, params.inspect)

    return unless request.post?

    @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].blank?
      @folder.name = params[:thetisBoxEdit]
      @folder.save
    end
    render(:partial => 'ajax_folder_name', :layout => false)
  end
//  [ruby]
  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
//  [ruby]
  def create
    Log.add_info(request, params.inspect)

    return unless request.post?

    parent_id = params[:selectedFolderId]

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

    if params[:thetisBoxEdit].blank?
      @folder = nil
    else
      @folder = Folder.new
      @folder.name = params[:thetisBoxEdit]
      @folder.xorder = Folder.get_order_max(parent_id) + 1
      @folder.parent_id = parent_id
      @folder.inherit_parent_auth
      @folder.save!
    end
    render(:partial => 'ajax_folder_entry', :layout => false)
  end
//  [ruby]
  def create
    Log.add_info(request, params.inspect)

    parent_id = params[:selectedFolderId]

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

    if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @folder = nil
    else
      @folder = Folder.new
      @folder.name = params[:thetisBoxEdit]
      @folder.xorder = Folder.get_order_max(parent_id) + 1
      @folder.parent_id = parent_id
      @folder.inherit_parent_auth
      @folder.save!
    end
    render(:partial => 'ajax_folder_entry', :layout => false)
  end
//  [ruby]
  def get_auth_teams
    Log.add_info(request, params.inspect)

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

    begin
      @folder = Folder.find(folder_id)
    rescue
      @folder = nil
    end

    target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
    @teams = Team.get_for(target_user_id, true)

    session[:folder_id] = folder_id

    render(:partial => 'ajax_auth_teams', :layout => false)
  end
//  [ruby]
  def get_auth_teams
    Log.add_info(request, params.inspect)

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

    target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
    @teams = Team.get_for(target_user_id, true)

    session[:folder_id] = params[:id]

    render(:partial => 'ajax_auth_teams', :layout => false)
  end
//  [ruby]
  def set_auth_groups
    Log.add_info(request, params.inspect)

    return unless request.post?

    @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
//  [ruby]
  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
//  [ruby]
  def get_disp_ctrl
    Log.add_info(request, params.inspect)

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

    if folder_id != '0'
      begin
        @folder = Folder.find(folder_id)
      rescue => evar
        @folder = nil
      end
    end

    session[:folder_id] = folder_id

    render(:partial => 'ajax_disp_ctrl', :layout => false)
  end
//  [ruby]
  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
//  [ruby]
  def set_auth_users
    Log.add_info(request, params.inspect)

    return unless request.post?

    @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]
    SqlHelper.validate_token([@group_id])

    if @group_id.blank?
      @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
//  [ruby]
  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
//  [ruby]
  def tags_for_index(model)
    model.tags.inject("".html_safe) do |out, tag|
      query = controller.send(:current_query) || ""
      hashtag = "##{tag}"
      if query.empty?
        query = hashtag
      elsif !query.include?(hashtag)
        query += " #{hashtag}"
      end
      out << link_to_function(tag, "crm.search_tagged('#{escape_javascript(query)}', '#{model.class.to_s.tableize}')", title: tag)
    end
  end
//  [ruby]
  def tags_for_index(model)
    model.tags.inject("".html_safe) do |out, tag|
      query = controller.send(:current_query) || ""
      hashtag = "##{tag}"
      if query.empty?
        query = hashtag
      elsif !query.include?(hashtag)
        query += " #{hashtag}"
      end
      out << link_to_function(tag, "crm.search_tagged('#{query}', '#{model.class.to_s.tableize}')", title: tag)
    end
  end
//  [ruby]
  def set_auth_teams
    Log.add_info(request, params.inspect)

    return unless request.post?

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

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

      @folder.set_read_teams(read_teams)
      @folder.set_write_teams(write_teams)

      @folder.save

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

    target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
    @teams = Team.get_for(target_user_id, true)
    render(:partial => 'ajax_auth_teams', :layout => false)

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

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

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

      @folder.set_read_teams read_teams
      @folder.set_write_teams write_teams

      @folder.save

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

    target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
    @teams = Team.get_for(target_user_id, true)
    render(:partial => 'ajax_auth_teams', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_auth_teams', :layout => false)
  end
//  [ruby]
  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
//  [ruby]
  def check_owner

    return if params[:id].blank? 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
//  [ruby]
  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
//  [ruby]
    it "with dofollowify disabled, links should be nofollowed" do
      @blog.dofollowify = false
      @blog.save

      result = nofollowify_links(original_html)

      aggregate_failures do
        expect(result).to eq('<a href="http://myblog.net" rel="nofollow">my blog</a>')
        expect(result).to be_html_safe
      end
    end
//  [ruby]
    it "with dofollowify disabled, links should be nofollowed" do
      @blog.dofollowify = false
      @blog.save

      expect(nofollowify_links('<a href="http://myblog.net">my blog</a>')).
        to eq('<a href="http://myblog.net" rel="nofollow">my blog</a>')
    end
//  [ruby]
    it 'should not choke on valueless attributes' do
      @s.fragment('foo <a href>foo</a> bar')
        .must_equal 'foo <a href rel="nofollow">foo</a> bar'
    end
//  [ruby]
    it 'should not choke on valueless attributes' do
      @s.fragment('foo <a href>foo</a> bar')
        .must_equal 'foo <a href="" rel="nofollow">foo</a> bar'
    end
//  [ruby]
  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 << SqlHelper.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
//  [ruby]
  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
//  [ruby]
    def build_query(path, details)
      query = @pattern.dup

      prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
      query.gsub!(/\:prefix(\/)?/, prefix)

      partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
      query.gsub!(/\:action/, partial)

      details.each do |ext, variants|
        query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
      end

      File.expand_path(query, @path)
    end
//  [ruby]
    def build_query(path, details)
      query = @pattern.dup
      query.gsub!(/\:prefix(\/)?/, path.prefix.empty? ? "" : "#{path.prefix}\\1") # prefix can be empty...
      query.gsub!(/\:action/, path.partial? ? "_#{path.name}" : path.name)

      details.each do |ext, variants|
        query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
      end

      File.expand_path(query, @path)
    end
//  [ruby]
  def check_owner

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

    email = Email.find(params[:id])

    if !@login_user.admin?(User::AUTH_MAIL) and email.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
//  [ruby]
  def check_owner

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

    email = Email.find(params[:id])

    if !@login_user.admin?(User::AUTH_MAIL) and email.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
//  [ruby]
  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].blank?
      @group_id = params[:group_id]
    end
    SqlHelper.validate_token([@group_id])

    submit_url = url_for(:controller => 'send_mails', :action => 'get_group_users')
    render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :email, :submit_url => submit_url})
  end
//  [ruby]
  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 => 'send_mails', :action => 'get_group_users')
    render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :email, :submit_url => submit_url})
  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? \
          and token.to_s.match(/^[ ]*\d+-\d+-\d+[ ]*$/).nil?
        raise("[ERROR] SqlHelper.validate_token failed: #{token}")
      end
    end
  end
//  [ruby]
    def read_lines(path, selector)
      # IO.open is deliberately not used directly to avoid potential security risks.
      # TODO: Get rid of 'open-uri' (URI.open).
      io = target_http?(path) ? URI : File

      io.open(path) do |f|
        if selector
          f.each.select.with_index(1, &selector)
        else
          f.read
        end
      end
    end
//  [ruby]
  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.to_i}) 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
//  [ruby]
    def _call(env)
      unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
        return fail(405, "Method Not Allowed")
      end

      path_info = Utils.unescape(env["PATH_INFO"])
      parts = path_info.split SEPS

      clean = []

      parts.each do |part|
        next if part.empty? || part == '.'
        part == '..' ? clean.pop : clean << part
      end

      @path = F.join(@root, *clean)

      available = begin
        F.file?(@path) && F.readable?(@path)
      rescue SystemCallError
        false
      end

      if available
        serving(env)
      else
        fail(404, "File not found: #{path_info}")
      end
    end
//  [ruby]
    def _call(env)
      unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
        return fail(405, "Method Not Allowed")
      end

      path_info = Utils.unescape(env["PATH_INFO"])
      parts = path_info.split SEPS

      parts.inject(0) do |depth, part|
        case part
        when '', '.'
          depth
        when '..'
          return fail(404, "Not Found") if depth - 1 < 0
          depth - 1
        else
          depth + 1
        end
      end
//  [ruby]
  def self.get_for(user_id, date_s)

    SqlHelper.validate_token([user_id, date_s])
    begin
      con = "(user_id=#{user_id.to_i}) and (date='#{date_s}')"
      return Timecard.where(con).first
    rescue
    end
    return nil
  end
//  [ruby]
  def self.password_reset_via_token(token, password)

    # check token
    user = by_reset_token(token)
    return if !user

    # reset password
    user.update!(password: password, verified: true)

    # delete token
    Token.find_by(action: 'PasswordReset', name: token).destroy
    user
  end
//  [ruby]
  def self.password_reset_via_token(token, password)

    # check token
    user = by_reset_token(token)
    return if !user

    # reset password
    user.update!(password: password)

    # delete token
    Token.find_by(action: 'PasswordReset', name: token).destroy
    user
  end
//  [ruby]
        it 'should not overwrite an existing file if overwrite_stored_key is not set' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('n')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          full_path = File.join(File.expand_path('ssh/pkd'), 'rspec_pub.pem')
          File.stubs(:exists?).with(full_path).returns(true)
          File.stubs(:read).with(full_path).returns('ssh-rsa dcba')
          Log.expects(:warn)
          File.expects(:open).never
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
        it 'should not overwrite an existing file if overwrite_stored_key is not set' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('n')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)
          File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')
          Log.expects(:warn)
          File.expects(:open).never
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
        it 'should write the public key to disk if its the first time its been seen' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          full_path = File.join(File.expand_path('ssh/pkd'), 'rspec_pub.pem')
          File.stubs(:exists?).with(full_path).returns(false)
          file = mock
          File.expects(:open).with(full_path, 'w').yields(file)
          file.expects(:puts).with('ssh-rsa abcd')
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
        it 'should write the public key to disk if its the first time its been seen' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(false)
          file = mock
          File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)
          file.expects(:puts).with('ssh-rsa abcd')
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
        it 'should overwrite the existing public key if overwrite_stored_key is set' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('1')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          full_path = File.join(File.expand_path('ssh/pkd'), 'rspec_pub.pem')
          File.stubs(:exists?).with(full_path).returns(true)
          File.stubs(:read).with(full_path).returns('ssh-rsa dcba')
          file = mock
          File.expects(:open).with(full_path, 'w').yields(file)
          file.expects(:puts).with('ssh-rsa abcd')
          Log.expects(:warn)
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
        it 'should overwrite the existing public key if overwrite_stored_key is set' do
          @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
          @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
          @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('1')
          File.stubs(:directory?).with('ssh/pkd').returns(true)
          File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)
          File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')
          file = mock
          File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)
          file.expects(:puts).with('ssh-rsa abcd')
          Log.expects(:warn)
          @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
        end
//  [ruby]
  def ajax_delete_items
    Log.add_info(request, params.inspect)

    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
            item = nil
            Log.add_error(request, evar)
          end

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

    get_items
  end
//  [ruby]
  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
//  [ruby]
      def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false)
        unless input.count('.') + 1 == NUM_OF_SEGMENTS
          raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.")
        end
        header, claims, signature = input.split('.', NUM_OF_SEGMENTS).collect do |segment|
          Base64.urlsafe_decode64 segment.to_s
        end
        header = JSON.parse(header).with_indifferent_access
        if allow_blank_payload && claims == ''
          claims = nil
        else
          claims = JSON.parse(claims).with_indifferent_access
        end
        jws = new claims
        jws.header = header
        jws.signature = signature
        jws.signature_base_string = input.split('.')[0, NUM_OF_SEGMENTS - 1].join('.')
        jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification
        jws
      end
//  [ruby]
      def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false)
        unless input.count('.') + 1 == NUM_OF_SEGMENTS
          raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.")
        end
        header, claims, signature = input.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment|
          Base64.urlsafe_decode64 segment.to_s
        end
        header = JSON.parse(header).with_indifferent_access
        if allow_blank_payload && claims == ''
          claims = nil
        else
          claims = JSON.parse(claims).with_indifferent_access
        end
        jws = new claims
        jws.header = header
        jws.signature = signature
        jws.signature_base_string = input.split('.')[0, JWS::NUM_OF_SEGMENTS - 1].join('.')
        jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification
        jws
      end