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