jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def test_extract_symlink_parent
   skip 'symlink not supported' if Gem.win_platform?

   package = Gem::Package.new @gem

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

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

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

   assert_equal("installing into parent path lib/link/outside.txt of " +
                 "#{destination_subdir} is not allowed", e.message)
  end
//  [ruby]
  def test_extract_symlink_parent
   skip 'symlink not supported' if Gem.win_platform?

   package = Gem::Package.new @gem

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

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

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

   assert_equal("installing into parent path ../outside.txt of " +
                 "#{destination_subdir} is not allowed", e.message)
  end
//  [ruby]
      def _extend_marshalling(options)
        extend Serialization unless @serializer.nil?
      end
//  [ruby]
      def _extend_marshalling(options)
        @marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory
        extend Marshalling if @marshalling
      end
//  [ruby]
  it 'is valid with valid attributes' do
    notification = build(:notification, user: user)

    expect(notification).to be_valid
  end
//  [ruby]
  it 'is valid with valid attributes' do
    notification = build(:notification)

    expect(notification).to be_valid
  end
//  [ruby]
  def new
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]

    if mail_account_id.blank?
      account_xtype = params[:mail_account_xtype]
      SqlHelper.validate_token([account_xtype])
      @mail_account = MailAccount.get_default_for(@login_user.id, account_xtype)
    else
      @mail_account = MailAccount.find(mail_account_id)
      if @mail_account.user_id != @login_user.id
        flash[:notice] = 'ERROR:' + t('msg.need_to_be_owner')
        render(:partial => 'common/flash_notice', :layout => false)
        return
      end
    end

    if $thetis_config[:menu]['disp_user_list'] == '1'
      unless params[:to_user_ids].blank?
        @email = Email.new
        to_addrs = []
        @user_obj_cache ||= {}
        params[:to_user_ids].each do |user_id|
          user = User.find_with_cache(user_id, @user_obj_cache)
          user_emails = user.get_emails_by_type(nil)
          user_emails.each do |user_email|
            disp = EmailsHelper.format_address_exp(user.get_name, user_email, false)
            entry_val = "#{disp}"   # "#{disp}#{Email::ADDR_ORDER_SEPARATOR}#{user.get_xorder(@group_id)}"

            to_addrs << entry_val
          end
        end
        @email.to_addresses = to_addrs.join(Email::ADDRESS_SEPARATOR)
      end
    end

    render(:action => 'edit', :layout => (!request.xhr?))
  end
//  [ruby]
  def new
    Log.add_info(request, params.inspect)

    mail_account_id = params[:mail_account_id]

    if mail_account_id.nil? or mail_account_id.empty?
      account_xtype = params[:mail_account_xtype]
      @mail_account = MailAccount.get_default_for(@login_user.id, account_xtype)
    else
      @mail_account = MailAccount.find(mail_account_id)
      if @mail_account.user_id != @login_user.id
        flash[:notice] = 'ERROR:' + t('msg.need_to_be_owner')
        render(:partial => 'common/flash_notice', :layout => false)
        return
      end
    end

    if $thetis_config[:menu]['disp_user_list'] == '1'
      unless params[:to_user_ids].blank?
        @email = Email.new
        to_addrs = []
        @user_obj_cache ||= {}
        params[:to_user_ids].each do |user_id|
          user = User.find_with_cache(user_id, @user_obj_cache)
          user_emails = user.get_emails_by_type(nil)
          user_emails.each do |user_email|
            disp = EmailsHelper.format_address_exp(user.get_name, user_email, false)
            entry_val = "#{disp}"   # "#{disp}#{Email::ADDR_ORDER_SEPARATOR}#{user.get_xorder(@group_id)}"

            to_addrs << entry_val
          end
        end
        @email.to_addresses = to_addrs.join(Email::ADDRESS_SEPARATOR)
      end
    end

    render(:action => 'edit', :layout => (!request.xhr?))
  end
//  [ruby]
      def write_key_to_disk(key, identity)

        # Writing is disabled. Don't bother checking any other states.
        return unless lookup_config_option('learn_public_keys') =~ /^1|y/

        publickey_dir = lookup_config_option('publickey_dir')

        unless publickey_dir
          Log.info("Public key sent with request but no publickey_dir defined in configuration. Not writing key to disk.")
          return
        end

        if File.directory?(publickey_dir)
          # Reject identity if it would result in directory traversal.
          old_keyfile = File.join(File.expand_path(publickey_dir), "#{identity}_pub.pem")
          unless File.expand_path(old_keyfile) == old_keyfile
            Log.warn("Identity returned by server would result in directory traversal. Not writing key to disk.")
            return
          end

          if File.exists?(old_keyfile)
            old_key = File.read(old_keyfile).chomp

            unless old_key == key
              unless lookup_config_option('overwrite_stored_keys', 'n') =~ /^1|y/
                Log.warn("Public key sent from '%s' does not match the stored key. Not overwriting." % identity)
              else
                Log.warn("Public key sent from '%s' does not match the stored key. Overwriting." % identity)
                File.open(old_keyfile, 'w') { |f| f.puts key }
              end
            end
          else
            Log.debug("Discovered a new public key for '%s'. Writing to '%s'" % [identity, publickey_dir])
            File.open(old_keyfile, 'w') { |f| f.puts key }
          end
        else
          raise("Cannot write public key to '%s'. Directory does not exist." % publickey_dir)
        end
      end
//  [ruby]
      def write_key_to_disk(key, identity)

        # Writing is disabled. Don't bother checking any other states.
        return unless lookup_config_option('learn_public_keys') =~ /^1|y/

        publickey_dir = lookup_config_option('publickey_dir')

        unless publickey_dir
          Log.info("Public key sent with request but no publickey_dir defined in configuration. Not writing key to disk.")
          return
        end

        if File.directory?(publickey_dir)
          if File.exists?(old_keyfile = File.join(publickey_dir, "#{identity}_pub.pem"))
            old_key = File.read(old_keyfile).chomp

            unless old_key == key
              unless lookup_config_option('overwrite_stored_keys', 'n') =~ /^1|y/
                Log.warn("Public key sent from '%s' does not match the stored key. Not overwriting." % identity)
              else
                Log.warn("Public key sent from '%s' does not match the stored key. Overwriting." % identity)
                File.open(File.join(publickey_dir, "#{identity}_pub.pem"), 'w') { |f| f.puts key }
              end
            end
          else
            Log.debug("Discovered a new public key for '%s'. Writing to '%s'" % [identity, publickey_dir])
            File.open(File.join(publickey_dir, "#{identity}_pub.pem"), 'w') { |f| f.puts key }
          end
        else
          raise("Cannot write public key to '%s'. Directory does not exist." % publickey_dir)
        end
      end
//  [ruby]
    def apply(operations)
      operations.inject(self) do |builder, (name, argument)|
        if argument == true || argument == nil
          builder.public_send(name)
        elsif argument.is_a?(Array)
          builder.public_send(name, *argument)
        elsif argument.is_a?(Hash)
          builder.public_send(name, **argument)
        else
          builder.public_send(name, argument)
        end
      end
    end
//  [ruby]
    def apply(operations)
      operations.inject(self) do |builder, (name, argument)|
        if argument == true || argument == nil
          builder.send(name)
        elsif argument.is_a?(Array)
          builder.send(name, *argument)
        elsif argument.is_a?(Hash)
          builder.send(name, **argument)
        else
          builder.send(name, argument)
        end
      end
    end
//  [ruby]
    def each
      documents = load
      documents.each { |doc| yield doc }

      while more?
        return kill if limited? && @limit <= 0

        documents = get_more
        documents.each { |doc| yield doc }
      end
    end
//  [ruby]
    def each
      documents = query @query_op
      documents.each { |doc| yield doc }

      while more?
        return kill if limited? && @get_more_op.limit <= 0

        documents = query @get_more_op
        documents.each { |doc| yield doc }
      end
    end
//  [ruby]
  def send_password
    Log.add_info(request, params.inspect)

    mail_addr = params[:thetisBoxEdit]
    begin
      users = User.where(email: mail_addr).to_a
    rescue => evar
    end

    if users.nil? or users.empty?
      Log.add_error(request, evar)
      flash[:notice] = 'ERROR:' + t('email.address_not_found')
    else
      user_passwords_h = {}
      users.each do |user|
        newpass = UsersHelper.generate_password
        user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))

        user_passwords_h[user] = newpass
      end

      NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
      flash[:notice] = t('email.sent')
    end

    render(:controller => 'login', :action => 'index')
  end
//  [ruby]
    def kill
      @node.kill_cursors [@cursor_id]
    end
//  [ruby]
    def kill
      session.execute kill_cursor_op
    end
//  [ruby]
      def initialize(string)
        super("'#{string}' is not a valid object id.")
      end
//  [ruby]
      def decode_compact_serialized(input, private_key_or_secret, algorithms = nil, encryption_methods = nil, _allow_blank_payload = false)
        unless input.count('.') + 1 == NUM_OF_SEGMENTS
          raise InvalidFormat.new("Invalid JWE Format. JWE should include #{NUM_OF_SEGMENTS} segments.")
        end
        jwe = new
        _header_json_, jwe.jwe_encrypted_key, jwe.iv, jwe.cipher_text, jwe.authentication_tag = input.split('.', NUM_OF_SEGMENTS).collect do |segment|
          begin
            Base64.urlsafe_decode64 segment
          rescue ArgumentError
            raise DecryptionFailed
          end
        end
        jwe.auth_data = input.split('.').first
        jwe.header = JSON.parse(_header_json_).with_indifferent_access
        unless private_key_or_secret == :skip_decryption
          jwe.decrypt! private_key_or_secret, algorithms, encryption_methods
        end
        jwe
      end
//  [ruby]
      def decode_compact_serialized(input, private_key_or_secret, algorithms = nil, encryption_methods = nil, _allow_blank_payload = false)
        unless input.count('.') + 1 == NUM_OF_SEGMENTS
          raise InvalidFormat.new("Invalid JWE Format. JWE should include #{NUM_OF_SEGMENTS} segments.")
        end
        jwe = new
        _header_json_, jwe.jwe_encrypted_key, jwe.iv, jwe.cipher_text, jwe.authentication_tag = input.split('.').collect do |segment|
          begin
            Base64.urlsafe_decode64 segment
          rescue ArgumentError
            raise DecryptionFailed
          end
        end
        jwe.auth_data = input.split('.').first
        jwe.header = JSON.parse(_header_json_).with_indifferent_access
        unless private_key_or_secret == :skip_decryption
          jwe.decrypt! private_key_or_secret, algorithms, encryption_methods
        end
        jwe
      end
//  [ruby]
    def more?
      @cursor_id != 0
    end
//  [ruby]
    def more?
      @get_more_op.cursor_id != 0
    end
//  [ruby]
  def column_content(column, item)
    value = column.value_object(item)
    if value.is_a?(Array)
      values = value.collect {|v| column_value(column, item, v)}.compact
      safe_join(values, ', ')
    else
      column_value(column, item, value)
    end
  end
//  [ruby]
  def column_content(column, item)
    value = column.value_object(item)
    if value.is_a?(Array)
      value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe
    else
      column_value(column, item, value)
    end
  end
//  [ruby]
  def render_step(the_step, options = {})
    if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP
      redirect_to_finish_wizard options
    else
      render ERB::Util.url_encode(the_step), options
    end
  end
//  [ruby]
  def render_step(the_step, options = {})
    if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP
      redirect_to_finish_wizard options
    else
      render the_step, options
    end
  end
//  [ruby]
  def spec_summary entry, spec
    summary = truncate_text(spec.summary, "the summary for #{spec.full_name}")
    entry << "\n\n" << format_text(summary, 68, 4)
  end
//  [ruby]
  def spec_summary entry, spec
    entry << "\n\n" << format_text(spec.summary, 68, 4)
  end
//  [ruby]
    def initialize(session, query_operation)
      @session = session

      @database    = query_operation.database
      @collection  = query_operation.collection
      @selector    = query_operation.selector

      @cursor_id = 0
      @limit = query_operation.limit
      @limited = @limit > 0

      @options = {
        request_id: query_operation.request_id,
        flags: query_operation.flags,
        limit: query_operation.limit,
        skip: query_operation.skip,
        fields: query_operation.fields
      }
    end
//  [ruby]
    def initialize(session, query_operation)
      @session = session
      @query_op = query_operation.dup

      @get_more_op = Protocol::GetMore.new(
        @query_op.database,
        @query_op.collection,
        0,
        @query_op.limit
      )

      @kill_cursor_op = Protocol::KillCursors.new([0])
    end
//  [ruby]
    def limited?
      @limited
    end
//  [ruby]
    def limited?
      @query_op.limit > 0
    end
//  [ruby]
  def remove_application(users)

    return if users.nil? or users.empty?

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

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

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

    Comment.destroy_all(array.join(' and '))
 end
//  [ruby]
  def show_article
    auto_discovery_feed
    respond_to do |format|
      format.html do
        @comment = Comment.new
        @page_title = this_blog.article_title_template.to_title(@article, this_blog, params)
        if @article.password.blank?
          @description = this_blog.article_desc_template.
            to_title(@article, this_blog, params)
        end

        @keywords = @article.tags.map(&:name).join(", ")
        render "articles/#{@article.post_type}"
      end
      format.atom { render_feedback_feed("atom") }
      format.rss { render_feedback_feed("rss") }
      format.xml { render_feedback_feed("atom") }
    end
  rescue ActiveRecord::RecordNotFound
    error!
  end
//  [ruby]
  def show_article
    auto_discovery_feed
    respond_to do |format|
      format.html do
        @comment = Comment.new
        @page_title = this_blog.article_title_template.to_title(@article, this_blog, params)
        @description = this_blog.article_desc_template.to_title(@article, this_blog, params)

        @keywords = @article.tags.map(&:name).join(", ")
        render "articles/#{@article.post_type}"
      end
      format.atom { render_feedback_feed("atom") }
      format.rss { render_feedback_feed("rss") }
      format.xml { render_feedback_feed("atom") }
    end
  rescue ActiveRecord::RecordNotFound
    error!
  end
//  [ruby]
    def insert(documents)
      documents = [documents] unless documents.is_a? Array

      database.session.with(consistency: :strong) do |session|
        session.context.insert(database.name, name, documents)
      end
    end
//  [ruby]
    def insert(documents)
      documents = [documents] unless documents.is_a? Array
      insert = Protocol::Insert.new(database.name, name, documents)

      database.session.with(consistency: :strong) do |session|
        session.execute insert
      end

    end
//  [ruby]
  def initialize(*args)
    initialize_without_private_address_check(*args)
    if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_address.ip_address)
      raise PrivateAddressCheck::PrivateConnectionAttemptedError
    end
  end
//  [ruby]
  def initialize(remote_host, remote_port, local_host = nil, local_port = nil)
    if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_host)
      raise PrivateAddressCheck::PrivateConnectionAttemptedError
    end

    initialize_without_private_address_check(remote_host, remote_port, local_host, local_port)
  end
//  [ruby]
    def calculated_media_type
      @calculated_media_type ||= calculated_content_type.split("/").first
    end
//  [ruby]
  def update_config
    Log.add_info(request, params.inspect)

    return unless request.post?

    @yaml = ApplicationHelper.get_config_yaml

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

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

    flash[:notice] = t('msg.update_success')
    render(:partial => 'ajax_user_before_login', :layout => false)
  end
//  [ruby]
  def update_config
    Log.add_info(request, params.inspect)

    @yaml = ApplicationHelper.get_config_yaml

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

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

    flash[:notice] = t('msg.update_success')
    render(:partial => 'ajax_user_before_login', :layout => false)
  end
//  [ruby]
    def filename_extension
      File.extname(@name.to_s.downcase).sub(/^\./, '').to_sym
    end
//  [ruby]
    def calculated_content_type
      @calculated_content_type ||= type_from_file_command.chomp
    end
//  [ruby]
    def self.using(file, name, content_type)
      new(file, name, content_type)
    end
//  [ruby]
    def self.using(file, name)
      new(file, name)
    end
//  [ruby]
    def mapped_content_type
      Paperclip.options[:content_type_mappings][filename_extension]
    end
//  [ruby]
    def media_type_mismatch?
      supplied_type_mismatch? || calculated_type_mismatch?
    end
//  [ruby]
    def media_type_mismatch?
      ! supplied_file_media_types.include?(calculated_media_type)
    end
//  [ruby]
  def query
    Log.add_info(request, '')   # Not to show passwords.

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

    target_user = nil

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

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

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

    if target_user.nil?

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

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

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

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

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    target_user = nil

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

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

    unless zeptair_id.blank?

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

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

    if target_user.nil?
      if attachment_id.blank?

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

      else
        attach = Attachment.find(attachment_id)

        item = Item.find(attach.item_id)

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

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

        attach.destroy

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

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

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

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    target_user = nil

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

    unless params[:zeptair_id].blank?

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

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

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

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

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

        item = Item.find(attach.item_id)

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

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

        attach.destroy

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

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

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

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
    def spoofed?
      if has_name? && has_extension? && media_type_mismatch? && mapping_override_mismatch?
        Paperclip.log("Content Type Spoof: Filename #{File.basename(@name)} (#{supplied_content_type} from Headers, #{content_types_from_name} from Extension), content type discovered from file command: #{calculated_content_type}. See documentation to allow this combination.")
        true
      else
        false
      end
    end
//  [ruby]
    def spoofed?
      if has_name? && has_extension? && media_type_mismatch? && mapping_override_mismatch?
        Paperclip.log("Content Type Spoof: Filename #{File.basename(@name)} (#{supplied_file_content_types}), content type discovered from file command: #{calculated_content_type}. See documentation to allow this combination.")
        true
      end
    end
//  [ruby]
    def self.dump(object)
      dumped_json = MultiJson.dump object,
        mode: :compat, escape_mode: :xss_safe, time_format: :ruby
      escape(dumped_json)
    end
//  [ruby]
    def self.dump(object)
      MultiJson.dump object,
        mode: :compat, escape_mode: :xss_safe, time_format: :ruby
    end
//  [ruby]
    def initialize(file, name, content_type)
      @file = file
      @name = name
      @content_type = content_type || ""
    end
//  [ruby]
    def initialize(file, name)
      @file = file
      @name = name
    end
//  [ruby]
      it "respects custom options" do
        expect(app.as_json(except: :id)).not_to include("id")
        expect(app.as_json(only: %i[name created_at secret]))
          .to match(
            "name" => app.name,
            "created_at" => an_instance_of(String),
          )
      end
//  [ruby]
    it "respects custom options" do
      expect(app.as_json(except: :secret)).not_to include("secret")
      expect(app.as_json(only: :id)).to match("id" => app.id)
    end
//  [ruby]
  def clean_text(text)
    text.gsub(/[\000-\b\v-\f\016-\037\177]/, ".".freeze)
  end
//  [ruby]
  def clean_text(text)
    text.gsub(/[\u0000-\u0008\u000b-\u000c\u000e-\u001F\u007f]/, ".".freeze)
  end
//  [ruby]
      it "returns the same hash" do
        Moped::BSON::ObjectId.from_data(bytes).hash.should eq Moped::BSON::ObjectId.from_data(bytes).hash
      end
//  [ruby]
      it "returns the same hash" do
        Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash
      end
//  [ruby]
    it "returns a hex string representation of the id" do
      Moped::BSON::ObjectId.from_data(bytes).to_s.should eq "4e4d66343b39b68407000001"
    end
//  [ruby]
    it "returns a hex string representation of the id" do
      Moped::BSON::ObjectId.new(bytes).to_s.should eq "4e4d66343b39b68407000001"
    end
//  [ruby]
      it "returns true" do
        Moped::BSON::ObjectId.from_data(bytes).should == Moped::BSON::ObjectId.from_data(bytes)
      end
//  [ruby]
      it "returns true" do
        Moped::BSON::ObjectId.new(bytes).should == Moped::BSON::ObjectId.new(bytes)
      end
//  [ruby]
  def self.get_next_revision(user_id, source_id)
    copied_items = Item.where("user_id=#{user_id} and source_id=#{source_id}").order('created_at DESC').to_a

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

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

    return '#' + sprintf('%03d', rev+1)
  end
//  [ruby]
      def fast_forward_to_first_boundary
        loop do
          content = @io.read(BUFSIZE)
          raise EOFError, "bad content body" unless content
          @buf << content

          while @buf.gsub!(/\A([^\n]*\n)/, '')
            read_buffer = $1
            return if read_buffer == full_boundary
          end

          raise EOFError, "bad content body" if Utils.bytesize(@buf) >= BUFSIZE
        end
      end
//  [ruby]
      def fast_forward_to_first_boundary
        loop do
          read_buffer = @io.gets
          break if read_buffer == full_boundary
          raise EOFError, "bad content body" if read_buffer.nil?
        end
      end
//  [ruby]
      def filename_from_uri
        CGI.unescape(File.basename(uri.path))
      end
//  [ruby]
      def filename_from_uri
        CGI.unescape(File.basename(file.base_uri.path))
      end
//  [ruby]
      def filename_from_header
        return nil unless headers['content-disposition']

        match = headers['content-disposition'].match(/filename=(?:"([^"]+)"|([^";]+))/)
        return nil unless match

        match[1].presence || match[2].presence
      end
//  [ruby]
      def filename_from_header
        return nil unless file.meta.include? 'content-disposition'

        match = file.meta['content-disposition'].match(/filename=(?:"([^"]+)"|([^";]+))/)
        return nil unless match

        match[1].presence || match[2].presence
      end
//  [ruby]
    def create_info_block(options)
      return nil unless options
      proc do |img|
        options.each do |k, v|
          if v.is_a?(String) && (matches = v.match(/^["'](.+)["']/))
            ActiveSupport::Deprecation.warn "Passing quoted strings like #{v} to #manipulate! is deprecated, pass them without quoting."
            v = matches[1]
          end
          img.public_send(:"#{k}=", v)
        end
      end
    end
//  [ruby]
    def create_info_block(options)
      return nil unless options
      assignments = options.map { |k, v| "img.#{k} = #{v}" }
      code = "lambda { |img| " + assignments.join(";") + "}"
      eval code
    end
//  [ruby]
  def perform_accept_invitation
    params.require(:id)
    params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {})

    invite = Invite.find_by(invite_key: params[:id])

    if invite.present?
      begin
        attrs = {
          username: params[:username],
          name: params[:name],
          password: params[:password],
          user_custom_fields: params[:user_custom_fields],
          ip_address: request.remote_ip,
          session: session
        }

        if invite.is_invite_link?
          params.require(:email)
          attrs[:email] = params[:email]
        else
          attrs[:email] = invite.email
          attrs[:email_token] = params[:email_token] if params[:email_token].present?
        end

        user = invite.redeem(**attrs)
      rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e
        return render json: failed_json.merge(message: e.message), status: 412
      end

      if user.blank?
        return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
      end

      log_on_user(user) if user.active? && user.guardian.can_access_forum?
      user.update_timezone_if_missing(params[:timezone])
      post_process_invite(user)
      create_topic_invite_notifications(invite, user)

      topic = invite.topics.first
      response = {}

      if user.present?
        if user.active? && user.guardian.can_access_forum?
          if user.guardian.can_see?(topic)
            response[:redirect_to] = path(topic.relative_url)
          else
            response[:redirect_to] = path("/")
          end
        else
          response[:message] = if user.active?
            I18n.t('activation.approval_required')
          else
            I18n.t('invite.confirm_email')
          end

          if user.guardian.can_see?(topic)
            cookies[:destination_url] = path(topic.relative_url)
          end
        end
      end

      render json: success_json.merge(response)
    else
      render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
    end
//  [ruby]
  def perform_accept_invitation
    params.require(:id)
    params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {})

    invite = Invite.find_by(invite_key: params[:id])

    if invite.present?
      begin
        attrs = {
          username: params[:username],
          name: params[:name],
          password: params[:password],
          user_custom_fields: params[:user_custom_fields],
          ip_address: request.remote_ip,
          session: session
        }

        if invite.is_invite_link?
          params.require(:email)
          attrs[:email] = params[:email]
        else
          attrs[:email] = invite.email
          attrs[:email_token] = params[:email_token] if params[:email_token].present?
        end

        user = invite.redeem(**attrs)
      rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e
        return render json: failed_json.merge(message: e.message), status: 412
      end

      if user.blank?
        return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
      end

      log_on_user(user) if user.active?
      user.update_timezone_if_missing(params[:timezone])
      post_process_invite(user)
      create_topic_invite_notifications(invite, user)

      topic = invite.topics.first
      response = {}

      if user.present?
        if user.active?
          if user.guardian.can_see?(topic)
            response[:redirect_to] = path(topic.relative_url)
          else
            response[:redirect_to] = path("/")
          end
        else
          response[:message] = I18n.t('invite.confirm_email')
          if user.guardian.can_see?(topic)
            cookies[:destination_url] = path(topic.relative_url)
          end
        end
      end

      render json: success_json.merge(response)
    else
      render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
    end
  end
//  [ruby]
      def initialize(file)
        case file
        when String
          @file = StringIO.new(file)
        when Net::HTTPResponse
          @file = StringIO.new(file.body)
          @content_type = file.content_type
          @headers = file
          @uri = file.uri
        else
          @file = file
          @content_type = file.content_type
          @headers = file.meta
          @uri = file.base_uri
        end
//  [ruby]
      def initialize(file)
        @file = file.is_a?(String) ? StringIO.new(file) : file
      end
//  [ruby]
  def self.update_for(user_id, fiscal_year, num)

    if num <= 0
      PaidHoliday.destroy_all(['user_id=? and year=?', user_id, fiscal_year])
      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 format_text(text, wrap, indent=0)
    result = []
    work = clean_text(text)

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

    result << work if work.length.nonzero?
    result.join("\n").gsub(/^/, " " * indent)
  end
//  [ruby]
  def format_text(text, wrap, indent=0)
    result = []
    work = text.dup

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

    result << work if work.length.nonzero?
    result.join("\n").gsub(/^/, " " * indent)
  end
//  [ruby]
      def original_filename
        filename = filename_from_header || filename_from_uri
        mime_type = MiniMime.lookup_by_content_type(content_type)
        unless File.extname(filename).present? || mime_type.blank?
          filename = "#{filename}.#{mime_type.extension}"
        end
        filename
      end
//  [ruby]
      def original_filename
        filename = filename_from_header || filename_from_uri
        mime_type = MiniMime.lookup_by_content_type(file.content_type)
        unless File.extname(filename).present? || mime_type.blank?
          filename = "#{filename}.#{mime_type.extension}"
        end
        filename
      end
//  [ruby]
  def self.from_yaml(input)
    Gem.load_yaml

    input = normalize_yaml_input input
    spec = Gem::SafeYAML.safe_load input

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

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

    spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
    spec.reset_nil_attributes_to_default

    spec
  end
//  [ruby]
  def self.from_yaml(input)
    Gem.load_yaml

    input = normalize_yaml_input input
    spec = YAML.load input

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

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

    spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
    spec.reset_nil_attributes_to_default

    spec
  end
//  [ruby]
  def setup
    @namespace = "theplaylist"
    @store  = Redis::Store.new :namespace => @namespace, :serializer => nil
    @client = @store.instance_variable_get(:@client)
    @rabbit = "bunny"
    @default_store = Redis::Store.new
    @other_namespace = 'other'
    @other_store = Redis::Store.new :namespace => @other_namespace
  end
//  [ruby]
  def setup
    @namespace = "theplaylist"
    @store  = Redis::Store.new :namespace => @namespace, :marshalling => false # TODO remove mashalling option
    @client = @store.instance_variable_get(:@client)
    @rabbit = "bunny"
    @default_store = Redis::Store.new
    @other_namespace = 'other'
    @other_store = Redis::Store.new :namespace => @other_namespace
  end
//  [ruby]
  def check_owner
    return if params[:id].blank? or @login_user.nil?

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

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

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

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
    it "sets the generation time" do
      time = Time.at((Time.now.utc - 64800).to_i).utc
      Moped::BSON::ObjectId.from_time(time).generation_time.should == time
    end
//  [ruby]
      it "sets the generation time" do
        time = Time.at((Time.now.utc - 64800).to_i).utc
        Moped::BSON::ObjectId.new(nil, time).generation_time.should == time
      end
//  [ruby]
  def ajax_move_mails
    Log.add_info(request, params.inspect)

    folder_id = params[:thetisBoxSelKeeper].split(':').last
    SqlHelper.validate_token([folder_id])
    begin
      mail_folder = MailFolder.find(folder_id)
    rescue => evar
    end

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

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

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

            email.update_attribute(:mail_folder_id, folder_id)

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

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

    get_mails
  end
//  [ruby]
  def ajax_move_mails
    Log.add_info(request, params.inspect)

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

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

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

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

            email.update_attribute(:mail_folder_id, folder_id)

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

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

    get_mails
  end
//  [ruby]
  def get_mail_attachment
    Log.add_info(request, params.inspect)

    attached_id = params[:id].to_i
    begin
      mail_attach = MailAttachment.find(attached_id)
    rescue => evar
    end

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

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

    mail_attach_name = mail_attach.name

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

    filepath = mail_attach.get_path
    if FileTest.exist?(filepath)
      send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')
    else
      send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+mail_attach_name+'"')
    end
  end
//  [ruby]
  def get_mail_attachment
    Log.add_info(request, params.inspect)

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

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

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

    mail_attach_name = mail_attach.name

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

    filepath = mail_attach.get_path
    if FileTest.exist?(filepath)
      send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')
    else
      send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+mail_attach_name+'"')
    end
  end
//  [ruby]
  def ajax_delete_mails
    Log.add_info(request, params.inspect)

    folder_id = params[:id]
    mail_account_id = params[:mail_account_id]

    unless params[:check_mail].blank?
      mail_folder = MailFolder.find(folder_id)
      trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)

      count = 0
      params[:check_mail].each do |email_id, value|
        next if value != '1'

        begin
          email = Email.find(email_id)
        rescue => evar
        end
        next if email.nil? or (email.user_id != @login_user.id)

        if trash_folder.nil? \
            or folder_id == trash_folder.id.to_s \
            or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
          email.destroy
          flash[:notice] ||= t('msg.delete_success')
        else
          begin
            email.update_attribute(:mail_folder_id, trash_folder.id)
            flash[:notice] ||= t('msg.moved_to_trash')
          rescue => evar
            Log.add_error(request, evar)
            email.destroy
            flash[:notice] ||= t('msg.delete_success')
          end
        end

        count += 1
      end
    end

    get_mails
  end
//  [ruby]
  def ajax_delete_mails
    Log.add_info(request, params.inspect)

    folder_id = params[:id]
    mail_account_id = params[:mail_account_id]

    unless params[:check_mail].blank?
      mail_folder = MailFolder.find(folder_id)
      trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)

      count = 0
      params[:check_mail].each do |email_id, value|
        next if value != '1'

        email = Email.find_by_id(email_id)
        next if email.nil? or (email.user_id != @login_user.id)

        if trash_folder.nil? \
            or folder_id == trash_folder.id.to_s \
            or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
          email.destroy
          flash[:notice] ||= t('msg.delete_success')
        else
          begin
            email.update_attribute(:mail_folder_id, trash_folder.id)
            flash[:notice] ||= t('msg.moved_to_trash')
          rescue => evar
            Log.add_error(request, evar)
            email.destroy
            flash[:notice] ||= t('msg.delete_success')
          end
        end

        count += 1
      end
    end

    get_mails
  end
//  [ruby]
  def self.get_for_user(user)

    return [] if user.nil?

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

    return [] if toys.nil?

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

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

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

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

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