annotate app/models/attachment.rb @ 1477:f2ad2199b49a bibplugin_integration

Close obsolete branch bibplugin_integration
author Chris Cannam
date Fri, 30 Nov 2012 14:41:31 +0000
parents cbb26bc654de
children ef882e222003 433d4f72a19b
rev   line source
Chris@441 1 # Redmine - project management software
Chris@441 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@441 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@441 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@0 18 require "digest/md5"
Chris@0 19
Chris@0 20 class Attachment < ActiveRecord::Base
Chris@0 21 belongs_to :container, :polymorphic => true
Chris@0 22 belongs_to :author, :class_name => "User", :foreign_key => "author_id"
Chris@441 23
Chris@0 24 validates_presence_of :container, :filename, :author
Chris@0 25 validates_length_of :filename, :maximum => 255
Chris@0 26 validates_length_of :disk_filename, :maximum => 255
Chris@909 27 validate :validate_max_file_size
Chris@0 28
Chris@0 29 acts_as_event :title => :filename,
Chris@0 30 :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}}
Chris@0 31
Chris@0 32 acts_as_activity_provider :type => 'files',
Chris@0 33 :permission => :view_files,
Chris@0 34 :author_key => :author_id,
Chris@441 35 :find_options => {:select => "#{Attachment.table_name}.*",
Chris@0 36 :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 37 "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 38
Chris@0 39 acts_as_activity_provider :type => 'documents',
Chris@0 40 :permission => :view_documents,
Chris@0 41 :author_key => :author_id,
Chris@441 42 :find_options => {:select => "#{Attachment.table_name}.*",
Chris@0 43 :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 44 "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"}
Chris@0 45
Chris@0 46 cattr_accessor :storage_path
Chris@909 47 @@storage_path = Redmine::Configuration['attachments_storage_path'] || "#{Rails.root}/files"
Chris@441 48
Chris@909 49 before_save :files_to_final_location
Chris@909 50 after_destroy :delete_from_disk
Chris@909 51
Chris@909 52 def validate_max_file_size
Chris@0 53 if self.filesize > Setting.attachment_max_size.to_i.kilobytes
Chris@0 54 errors.add(:base, :too_long, :count => Setting.attachment_max_size.to_i.kilobytes)
Chris@0 55 end
Chris@0 56 end
Chris@0 57
Chris@0 58 def file=(incoming_file)
Chris@0 59 unless incoming_file.nil?
Chris@0 60 @temp_file = incoming_file
Chris@0 61 if @temp_file.size > 0
Chris@0 62 self.filename = sanitize_filename(@temp_file.original_filename)
Chris@0 63 self.disk_filename = Attachment.disk_filename(filename)
Chris@0 64 self.content_type = @temp_file.content_type.to_s.chomp
Chris@0 65 if content_type.blank?
Chris@0 66 self.content_type = Redmine::MimeType.of(filename)
Chris@0 67 end
Chris@0 68 self.filesize = @temp_file.size
Chris@0 69 end
Chris@0 70 end
Chris@0 71 end
Chris@0 72
Chris@0 73 def file
Chris@0 74 nil
Chris@0 75 end
Chris@0 76
Chris@0 77 # Copies the temporary file to its final location
Chris@0 78 # and computes its MD5 hash
Chris@909 79 def files_to_final_location
Chris@0 80 if @temp_file && (@temp_file.size > 0)
Chris@909 81 logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)")
Chris@0 82 md5 = Digest::MD5.new
Chris@441 83 File.open(diskfile, "wb") do |f|
Chris@0 84 buffer = ""
Chris@0 85 while (buffer = @temp_file.read(8192))
Chris@0 86 f.write(buffer)
Chris@0 87 md5.update(buffer)
Chris@0 88 end
Chris@0 89 end
Chris@0 90 self.digest = md5.hexdigest
Chris@0 91 end
Chris@909 92 @temp_file = nil
Chris@0 93 # Don't save the content type if it's longer than the authorized length
Chris@0 94 if self.content_type && self.content_type.length > 255
Chris@0 95 self.content_type = nil
Chris@0 96 end
Chris@0 97 end
Chris@0 98
Chris@0 99 # Deletes file on the disk
Chris@909 100 def delete_from_disk
Chris@0 101 File.delete(diskfile) if !filename.blank? && File.exist?(diskfile)
Chris@0 102 end
Chris@0 103
Chris@0 104 # Returns file's location on disk
Chris@0 105 def diskfile
Chris@0 106 "#{@@storage_path}/#{self.disk_filename}"
Chris@0 107 end
Chris@441 108
Chris@0 109 def increment_download
Chris@0 110 increment!(:downloads)
Chris@0 111 end
Chris@0 112
Chris@0 113 def project
Chris@0 114 container.project
Chris@0 115 end
Chris@441 116
Chris@0 117 def visible?(user=User.current)
Chris@0 118 container.attachments_visible?(user)
Chris@0 119 end
Chris@441 120
Chris@0 121 def deletable?(user=User.current)
Chris@0 122 container.attachments_deletable?(user)
Chris@0 123 end
Chris@441 124
Chris@0 125 def image?
Chris@909 126 self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i
Chris@0 127 end
Chris@441 128
Chris@0 129 def is_text?
Chris@0 130 Redmine::MimeType.is_type?('text', filename)
Chris@0 131 end
Chris@441 132
Chris@0 133 def is_diff?
Chris@0 134 self.filename =~ /\.(patch|diff)$/i
Chris@0 135 end
Chris@441 136
Chris@0 137 # Returns true if the file is readable
Chris@0 138 def readable?
Chris@0 139 File.readable?(diskfile)
Chris@0 140 end
Chris@0 141
Chris@0 142 # Bulk attaches a set of files to an object
Chris@0 143 #
Chris@0 144 # Returns a Hash of the results:
Chris@0 145 # :files => array of the attached files
Chris@0 146 # :unsaved => array of the files that could not be attached
Chris@0 147 def self.attach_files(obj, attachments)
Chris@0 148 attached = []
Chris@0 149 if attachments && attachments.is_a?(Hash)
Chris@0 150 attachments.each_value do |attachment|
Chris@0 151 file = attachment['file']
Chris@0 152 next unless file && file.size > 0
Chris@441 153 a = Attachment.create(:container => obj,
Chris@0 154 :file => file,
Chris@0 155 :description => attachment['description'].to_s.strip,
Chris@0 156 :author => User.current)
Chris@909 157 obj.attachments << a
Chris@0 158
Chris@0 159 if a.new_record?
Chris@0 160 obj.unsaved_attachments ||= []
Chris@0 161 obj.unsaved_attachments << a
Chris@0 162 else
Chris@0 163 attached << a
Chris@0 164 end
Chris@0 165 end
Chris@0 166 end
Chris@0 167 {:files => attached, :unsaved => obj.unsaved_attachments}
Chris@0 168 end
Chris@441 169
Chris@909 170 def self.latest_attach(attachments, filename)
Chris@909 171 attachments.sort_by(&:created_on).reverse.detect {
Chris@909 172 |att| att.filename.downcase == filename.downcase
Chris@909 173 }
Chris@909 174 end
Chris@909 175
Chris@0 176 private
Chris@0 177 def sanitize_filename(value)
Chris@0 178 # get only the filename, not the whole path
Chris@0 179 just_filename = value.gsub(/^.*(\\|\/)/, '')
Chris@0 180
Chris@909 181 # Finally, replace invalid characters with underscore
Chris@909 182 @filename = just_filename.gsub(/[\/\?\%\*\:\|\"\'<>]+/, '_')
Chris@0 183 end
Chris@441 184
Chris@0 185 # Returns an ASCII or hashed filename
Chris@0 186 def self.disk_filename(filename)
Chris@0 187 timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
Chris@0 188 ascii = ''
Chris@0 189 if filename =~ %r{^[a-zA-Z0-9_\.\-]*$}
Chris@0 190 ascii = filename
Chris@0 191 else
Chris@0 192 ascii = Digest::MD5.hexdigest(filename)
Chris@0 193 # keep the extension if any
Chris@0 194 ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
Chris@0 195 end
Chris@0 196 while File.exist?(File.join(@@storage_path, "#{timestamp}_#{ascii}"))
Chris@0 197 timestamp.succ!
Chris@0 198 end
Chris@0 199 "#{timestamp}_#{ascii}"
Chris@0 200 end
Chris@0 201 end