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