Chris@909: # Redmine - project management software Chris@909: # Copyright (C) 2006-2011 Jean-Philippe Lang Chris@909: # Chris@909: # This program is free software; you can redistribute it and/or Chris@909: # modify it under the terms of the GNU General Public License Chris@909: # as published by the Free Software Foundation; either version 2 Chris@909: # of the License, or (at your option) any later version. Chris@909: # Chris@909: # This program is distributed in the hope that it will be useful, Chris@909: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@909: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@909: # GNU General Public License for more details. Chris@909: # Chris@909: # You should have received a copy of the GNU General Public License Chris@909: # along with this program; if not, write to the Free Software Chris@909: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@909: Chris@909: require "digest/md5" Chris@909: Chris@909: class Attachment < ActiveRecord::Base Chris@909: belongs_to :container, :polymorphic => true Chris@909: belongs_to :author, :class_name => "User", :foreign_key => "author_id" Chris@909: Chris@909: validates_presence_of :container, :filename, :author Chris@909: validates_length_of :filename, :maximum => 255 Chris@909: validates_length_of :disk_filename, :maximum => 255 Chris@909: validate :validate_max_file_size Chris@909: Chris@909: acts_as_event :title => :filename, Chris@909: :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}} Chris@909: Chris@909: acts_as_activity_provider :type => 'files', Chris@909: :permission => :view_files, Chris@909: :author_key => :author_id, Chris@909: :find_options => {:select => "#{Attachment.table_name}.*", Chris@909: :joins => "LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " + Chris@909: "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@909: Chris@909: acts_as_activity_provider :type => 'documents', Chris@909: :permission => :view_documents, Chris@909: :author_key => :author_id, Chris@909: :find_options => {:select => "#{Attachment.table_name}.*", Chris@909: :joins => "LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " + Chris@909: "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"} Chris@909: Chris@909: cattr_accessor :storage_path Chris@909: @@storage_path = Redmine::Configuration['attachments_storage_path'] || "#{Rails.root}/files" Chris@909: Chris@909: before_save :files_to_final_location Chris@909: after_destroy :delete_from_disk Chris@909: Chris@909: def validate_max_file_size Chris@909: if self.filesize > Setting.attachment_max_size.to_i.kilobytes Chris@909: errors.add(:base, :too_long, :count => Setting.attachment_max_size.to_i.kilobytes) Chris@909: end Chris@909: end Chris@909: Chris@909: def file=(incoming_file) Chris@909: unless incoming_file.nil? Chris@909: @temp_file = incoming_file Chris@909: if @temp_file.size > 0 Chris@909: self.filename = sanitize_filename(@temp_file.original_filename) Chris@909: self.disk_filename = Attachment.disk_filename(filename) Chris@909: self.content_type = @temp_file.content_type.to_s.chomp Chris@909: if content_type.blank? Chris@909: self.content_type = Redmine::MimeType.of(filename) Chris@909: end Chris@909: self.filesize = @temp_file.size Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: def file Chris@909: nil Chris@909: end Chris@909: Chris@909: # Copies the temporary file to its final location Chris@909: # and computes its MD5 hash Chris@909: def files_to_final_location Chris@909: if @temp_file && (@temp_file.size > 0) Chris@909: logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)") Chris@909: md5 = Digest::MD5.new Chris@909: File.open(diskfile, "wb") do |f| Chris@909: buffer = "" Chris@909: while (buffer = @temp_file.read(8192)) Chris@909: f.write(buffer) Chris@909: md5.update(buffer) Chris@909: end Chris@909: end Chris@909: self.digest = md5.hexdigest Chris@909: end Chris@909: @temp_file = nil Chris@909: # Don't save the content type if it's longer than the authorized length Chris@909: if self.content_type && self.content_type.length > 255 Chris@909: self.content_type = nil Chris@909: end Chris@909: end Chris@909: Chris@909: # Deletes file on the disk Chris@909: def delete_from_disk Chris@909: File.delete(diskfile) if !filename.blank? && File.exist?(diskfile) Chris@909: end Chris@909: Chris@909: # Returns file's location on disk Chris@909: def diskfile Chris@909: "#{@@storage_path}/#{self.disk_filename}" Chris@909: end Chris@909: Chris@909: def increment_download Chris@909: increment!(:downloads) Chris@909: end Chris@909: Chris@909: def project Chris@909: container.project Chris@909: end Chris@909: Chris@909: def visible?(user=User.current) Chris@909: container.attachments_visible?(user) Chris@909: end Chris@909: Chris@909: def deletable?(user=User.current) Chris@909: container.attachments_deletable?(user) Chris@909: end Chris@909: Chris@909: def image? Chris@909: self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i Chris@909: end Chris@909: Chris@909: def is_text? Chris@909: Redmine::MimeType.is_type?('text', filename) Chris@909: end Chris@909: Chris@909: def is_diff? Chris@909: self.filename =~ /\.(patch|diff)$/i Chris@909: end Chris@909: Chris@909: # Returns true if the file is readable Chris@909: def readable? Chris@909: File.readable?(diskfile) Chris@909: end Chris@909: Chris@909: # Bulk attaches a set of files to an object Chris@909: # Chris@909: # Returns a Hash of the results: Chris@909: # :files => array of the attached files Chris@909: # :unsaved => array of the files that could not be attached Chris@909: def self.attach_files(obj, attachments) Chris@909: attached = [] Chris@909: if attachments && attachments.is_a?(Hash) Chris@909: attachments.each_value do |attachment| Chris@909: file = attachment['file'] Chris@909: next unless file && file.size > 0 Chris@909: a = Attachment.create(:container => obj, Chris@909: :file => file, Chris@909: :description => attachment['description'].to_s.strip, Chris@909: :author => User.current) Chris@909: obj.attachments << a Chris@909: Chris@909: if a.new_record? Chris@909: obj.unsaved_attachments ||= [] Chris@909: obj.unsaved_attachments << a Chris@909: else Chris@909: attached << a Chris@909: end Chris@909: end Chris@909: end Chris@909: {:files => attached, :unsaved => obj.unsaved_attachments} Chris@909: end Chris@909: Chris@909: def self.latest_attach(attachments, filename) Chris@909: attachments.sort_by(&:created_on).reverse.detect { Chris@909: |att| att.filename.downcase == filename.downcase Chris@909: } Chris@909: end Chris@909: Chris@909: private Chris@909: def sanitize_filename(value) Chris@909: # get only the filename, not the whole path Chris@909: just_filename = value.gsub(/^.*(\\|\/)/, '') Chris@909: Chris@909: # Finally, replace invalid characters with underscore Chris@909: @filename = just_filename.gsub(/[\/\?\%\*\:\|\"\'<>]+/, '_') Chris@909: end Chris@909: Chris@909: # Returns an ASCII or hashed filename Chris@909: def self.disk_filename(filename) Chris@909: timestamp = DateTime.now.strftime("%y%m%d%H%M%S") Chris@909: ascii = '' Chris@909: if filename =~ %r{^[a-zA-Z0-9_\.\-]*$} Chris@909: ascii = filename Chris@909: else Chris@909: ascii = Digest::MD5.hexdigest(filename) Chris@909: # keep the extension if any Chris@909: ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$} Chris@909: end Chris@909: while File.exist?(File.join(@@storage_path, "#{timestamp}_#{ascii}")) Chris@909: timestamp.succ! Chris@909: end Chris@909: "#{timestamp}_#{ascii}" Chris@909: end Chris@909: end