Chris@1494: # Redmine - project management software Chris@1494: # Copyright (C) 2006-2014 Jean-Philippe Lang Chris@1494: # Chris@1494: # This program is free software; you can redistribute it and/or Chris@1494: # modify it under the terms of the GNU General Public License Chris@1494: # as published by the Free Software Foundation; either version 2 Chris@1494: # of the License, or (at your option) any later version. Chris@1494: # Chris@1494: # This program is distributed in the hope that it will be useful, Chris@1494: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@1494: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@1494: # GNU General Public License for more details. Chris@1494: # Chris@1494: # You should have received a copy of the GNU General Public License Chris@1494: # along with this program; if not, write to the Free Software Chris@1494: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@1494: Chris@1494: require "digest/md5" Chris@1494: require "fileutils" Chris@1494: Chris@1494: class Attachment < ActiveRecord::Base Chris@1494: belongs_to :container, :polymorphic => true Chris@1494: belongs_to :author, :class_name => "User", :foreign_key => "author_id" Chris@1494: Chris@1494: validates_presence_of :filename, :author Chris@1494: validates_length_of :filename, :maximum => 255 Chris@1494: validates_length_of :disk_filename, :maximum => 255 Chris@1494: validates_length_of :description, :maximum => 255 Chris@1494: validate :validate_max_file_size Chris@1494: Chris@1494: acts_as_event :title => :filename, Chris@1494: :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}} Chris@1494: Chris@1494: acts_as_activity_provider :type => 'files', Chris@1494: :permission => :view_files, Chris@1494: :author_key => :author_id, Chris@1494: :find_options => {:select => "#{Attachment.table_name}.*", Chris@1494: :joins => "LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " + Chris@1494: "LEFT JOIN #{Project.table_name} ON #{Version.table_name}.project_id = #{Project.table_name}.id OR ( #{Attachment.table_name}.container_type='Project' AND #{Attachment.table_name}.container_id = #{Project.table_name}.id )"} Chris@1494: Chris@1494: acts_as_activity_provider :type => 'documents', Chris@1494: :permission => :view_documents, Chris@1494: :author_key => :author_id, Chris@1494: :find_options => {:select => "#{Attachment.table_name}.*", Chris@1494: :joins => "LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " + Chris@1494: "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"} Chris@1494: Chris@1494: cattr_accessor :storage_path Chris@1494: @@storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files") Chris@1494: Chris@1494: cattr_accessor :thumbnails_storage_path Chris@1494: @@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails") Chris@1494: Chris@1494: before_save :files_to_final_location Chris@1494: after_destroy :delete_from_disk Chris@1494: Chris@1494: # Returns an unsaved copy of the attachment Chris@1494: def copy(attributes=nil) Chris@1494: copy = self.class.new Chris@1494: copy.attributes = self.attributes.dup.except("id", "downloads") Chris@1494: copy.attributes = attributes if attributes Chris@1494: copy Chris@1494: end Chris@1494: Chris@1494: def validate_max_file_size Chris@1494: if @temp_file && self.filesize > Setting.attachment_max_size.to_i.kilobytes Chris@1494: errors.add(:base, l(:error_attachment_too_big, :max_size => Setting.attachment_max_size.to_i.kilobytes)) Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def file=(incoming_file) Chris@1494: unless incoming_file.nil? Chris@1494: @temp_file = incoming_file Chris@1494: if @temp_file.size > 0 Chris@1494: if @temp_file.respond_to?(:original_filename) Chris@1494: self.filename = @temp_file.original_filename Chris@1494: self.filename.force_encoding("UTF-8") if filename.respond_to?(:force_encoding) Chris@1494: end Chris@1494: if @temp_file.respond_to?(:content_type) Chris@1494: self.content_type = @temp_file.content_type.to_s.chomp Chris@1494: end Chris@1494: if content_type.blank? && filename.present? Chris@1494: self.content_type = Redmine::MimeType.of(filename) Chris@1494: end Chris@1494: self.filesize = @temp_file.size Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def file Chris@1494: nil Chris@1494: end Chris@1494: Chris@1494: def filename=(arg) Chris@1494: write_attribute :filename, sanitize_filename(arg.to_s) Chris@1494: filename Chris@1494: end Chris@1494: Chris@1494: # Copies the temporary file to its final location Chris@1494: # and computes its MD5 hash Chris@1494: def files_to_final_location Chris@1494: if @temp_file && (@temp_file.size > 0) Chris@1494: self.disk_directory = target_directory Chris@1494: self.disk_filename = Attachment.disk_filename(filename, disk_directory) Chris@1494: logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)") if logger Chris@1494: path = File.dirname(diskfile) Chris@1494: unless File.directory?(path) Chris@1494: FileUtils.mkdir_p(path) Chris@1494: end Chris@1494: md5 = Digest::MD5.new Chris@1494: File.open(diskfile, "wb") do |f| Chris@1494: if @temp_file.respond_to?(:read) Chris@1494: buffer = "" Chris@1494: while (buffer = @temp_file.read(8192)) Chris@1494: f.write(buffer) Chris@1494: md5.update(buffer) Chris@1494: end Chris@1494: else Chris@1494: f.write(@temp_file) Chris@1494: md5.update(@temp_file) Chris@1494: end Chris@1494: end Chris@1494: self.digest = md5.hexdigest Chris@1494: end Chris@1494: @temp_file = nil Chris@1494: # Don't save the content type if it's longer than the authorized length Chris@1494: if self.content_type && self.content_type.length > 255 Chris@1494: self.content_type = nil Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Deletes the file from the file system if it's not referenced by other attachments Chris@1494: def delete_from_disk Chris@1494: if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty? Chris@1494: delete_from_disk! Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Returns file's location on disk Chris@1494: def diskfile Chris@1494: File.join(self.class.storage_path, disk_directory.to_s, disk_filename.to_s) Chris@1494: end Chris@1494: Chris@1494: def title Chris@1494: title = filename.to_s Chris@1494: if description.present? Chris@1494: title << " (#{description})" Chris@1494: end Chris@1494: title Chris@1494: end Chris@1494: Chris@1494: def increment_download Chris@1494: increment!(:downloads) Chris@1494: end Chris@1494: Chris@1494: def project Chris@1494: container.try(:project) Chris@1494: end Chris@1494: Chris@1494: def visible?(user=User.current) Chris@1494: if container_id Chris@1494: container && container.attachments_visible?(user) Chris@1494: else Chris@1494: author == user Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def deletable?(user=User.current) Chris@1494: if container_id Chris@1494: container && container.attachments_deletable?(user) Chris@1494: else Chris@1494: author == user Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def image? Chris@1494: !!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i) Chris@1494: end Chris@1494: Chris@1494: def thumbnailable? Chris@1494: image? Chris@1494: end Chris@1494: Chris@1494: # Returns the full path the attachment thumbnail, or nil Chris@1494: # if the thumbnail cannot be generated. Chris@1494: def thumbnail(options={}) Chris@1494: if thumbnailable? && readable? Chris@1494: size = options[:size].to_i Chris@1494: if size > 0 Chris@1494: # Limit the number of thumbnails per image Chris@1494: size = (size / 50) * 50 Chris@1494: # Maximum thumbnail size Chris@1494: size = 800 if size > 800 Chris@1494: else Chris@1494: size = Setting.thumbnails_size.to_i Chris@1494: end Chris@1494: size = 100 unless size > 0 Chris@1494: target = File.join(self.class.thumbnails_storage_path, "#{id}_#{digest}_#{size}.thumb") Chris@1494: Chris@1494: begin Chris@1494: Redmine::Thumbnail.generate(self.diskfile, target, size) Chris@1494: rescue => e Chris@1494: logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger Chris@1494: return nil Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Deletes all thumbnails Chris@1494: def self.clear_thumbnails Chris@1494: Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file| Chris@1494: File.delete file Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def is_text? Chris@1494: Redmine::MimeType.is_type?('text', filename) Chris@1494: end Chris@1494: Chris@1494: def is_diff? Chris@1494: self.filename =~ /\.(patch|diff)$/i Chris@1494: end Chris@1494: Chris@1494: # Returns true if the file is readable Chris@1494: def readable? Chris@1494: File.readable?(diskfile) Chris@1494: end Chris@1494: Chris@1494: # Returns the attachment token Chris@1494: def token Chris@1494: "#{id}.#{digest}" Chris@1494: end Chris@1494: Chris@1494: # Finds an attachment that matches the given token and that has no container Chris@1494: def self.find_by_token(token) Chris@1494: if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/ Chris@1494: attachment_id, attachment_digest = $1, $2 Chris@1494: attachment = Attachment.where(:id => attachment_id, :digest => attachment_digest).first Chris@1494: if attachment && attachment.container.nil? Chris@1494: attachment Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Bulk attaches a set of files to an object Chris@1494: # Chris@1494: # Returns a Hash of the results: Chris@1494: # :files => array of the attached files Chris@1494: # :unsaved => array of the files that could not be attached Chris@1494: def self.attach_files(obj, attachments) Chris@1494: result = obj.save_attachments(attachments, User.current) Chris@1494: obj.attach_saved_attachments Chris@1494: result Chris@1494: end Chris@1494: Chris@1494: def self.latest_attach(attachments, filename) Chris@1494: attachments.sort_by(&:created_on).reverse.detect { Chris@1494: |att| att.filename.downcase == filename.downcase Chris@1494: } Chris@1494: end Chris@1494: Chris@1494: def self.prune(age=1.day) Chris@1494: Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all Chris@1494: end Chris@1494: Chris@1494: # Moves an existing attachment to its target directory Chris@1494: def move_to_target_directory! Chris@1494: return unless !new_record? & readable? Chris@1494: Chris@1494: src = diskfile Chris@1494: self.disk_directory = target_directory Chris@1494: dest = diskfile Chris@1494: Chris@1494: return if src == dest Chris@1494: Chris@1494: if !FileUtils.mkdir_p(File.dirname(dest)) Chris@1494: logger.error "Could not create directory #{File.dirname(dest)}" if logger Chris@1494: return Chris@1494: end Chris@1494: Chris@1494: if !FileUtils.mv(src, dest) Chris@1494: logger.error "Could not move attachment from #{src} to #{dest}" if logger Chris@1494: return Chris@1494: end Chris@1494: Chris@1494: update_column :disk_directory, disk_directory Chris@1494: end Chris@1494: Chris@1494: # Moves existing attachments that are stored at the root of the files Chris@1494: # directory (ie. created before Redmine 2.3) to their target subdirectories Chris@1494: def self.move_from_root_to_target_directory Chris@1494: Attachment.where("disk_directory IS NULL OR disk_directory = ''").find_each do |attachment| Chris@1494: attachment.move_to_target_directory! Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: private Chris@1494: Chris@1494: # Physically deletes the file from the file system Chris@1494: def delete_from_disk! Chris@1494: if disk_filename.present? && File.exist?(diskfile) Chris@1494: File.delete(diskfile) Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def sanitize_filename(value) Chris@1494: # get only the filename, not the whole path Chris@1494: just_filename = value.gsub(/\A.*(\\|\/)/m, '') Chris@1494: Chris@1494: # Finally, replace invalid characters with underscore Chris@1494: @filename = just_filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_') Chris@1494: end Chris@1494: Chris@1494: # Returns the subdirectory in which the attachment will be saved Chris@1494: def target_directory Chris@1494: time = created_on || DateTime.now Chris@1494: time.strftime("%Y/%m") Chris@1494: end Chris@1494: Chris@1494: # Returns an ASCII or hashed filename that do not Chris@1494: # exists yet in the given subdirectory Chris@1494: def self.disk_filename(filename, directory=nil) Chris@1494: timestamp = DateTime.now.strftime("%y%m%d%H%M%S") Chris@1494: ascii = '' Chris@1494: if filename =~ %r{^[a-zA-Z0-9_\.\-]*$} Chris@1494: ascii = filename Chris@1494: else Chris@1494: ascii = Digest::MD5.hexdigest(filename) Chris@1494: # keep the extension if any Chris@1494: ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$} Chris@1494: end Chris@1494: while File.exist?(File.join(storage_path, directory.to_s, "#{timestamp}_#{ascii}")) Chris@1494: timestamp.succ! Chris@1494: end Chris@1494: "#{timestamp}_#{ascii}" Chris@1494: end Chris@1494: end