annotate app/models/attachment.rb @ 1295:622f24f53b42 redmine-2.3

Update to Redmine SVN revision 11972 on 2.3-stable branch
author Chris Cannam
date Fri, 14 Jun 2013 09:02:21 +0100
parents 433d4f72a19b
children
rev   line source
Chris@441 1 # Redmine - project management software
Chris@1295 2 # Copyright (C) 2006-2013 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@1295 19 require "fileutils"
Chris@0 20
Chris@0 21 class Attachment < ActiveRecord::Base
Chris@0 22 belongs_to :container, :polymorphic => true
Chris@0 23 belongs_to :author, :class_name => "User", :foreign_key => "author_id"
Chris@441 24
Chris@1115 25 validates_presence_of :filename, :author
Chris@0 26 validates_length_of :filename, :maximum => 255
Chris@0 27 validates_length_of :disk_filename, :maximum => 255
Chris@1115 28 validates_length_of :description, :maximum => 255
Chris@909 29 validate :validate_max_file_size
Chris@0 30
Chris@0 31 acts_as_event :title => :filename,
Chris@0 32 :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}}
Chris@0 33
Chris@0 34 acts_as_activity_provider :type => 'files',
Chris@0 35 :permission => :view_files,
Chris@0 36 :author_key => :author_id,
Chris@441 37 :find_options => {:select => "#{Attachment.table_name}.*",
Chris@0 38 :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 39 "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 40
Chris@0 41 acts_as_activity_provider :type => 'documents',
Chris@0 42 :permission => :view_documents,
Chris@0 43 :author_key => :author_id,
Chris@441 44 :find_options => {:select => "#{Attachment.table_name}.*",
Chris@0 45 :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 46 "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"}
Chris@0 47
Chris@0 48 cattr_accessor :storage_path
Chris@1115 49 @@storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
Chris@1115 50
Chris@1115 51 cattr_accessor :thumbnails_storage_path
Chris@1115 52 @@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails")
Chris@441 53
Chris@909 54 before_save :files_to_final_location
Chris@909 55 after_destroy :delete_from_disk
Chris@909 56
Chris@1115 57 # Returns an unsaved copy of the attachment
Chris@1115 58 def copy(attributes=nil)
Chris@1115 59 copy = self.class.new
Chris@1115 60 copy.attributes = self.attributes.dup.except("id", "downloads")
Chris@1115 61 copy.attributes = attributes if attributes
Chris@1115 62 copy
Chris@1115 63 end
Chris@1115 64
Chris@909 65 def validate_max_file_size
Chris@1115 66 if @temp_file && self.filesize > Setting.attachment_max_size.to_i.kilobytes
Chris@1115 67 errors.add(:base, l(:error_attachment_too_big, :max_size => Setting.attachment_max_size.to_i.kilobytes))
Chris@0 68 end
Chris@0 69 end
Chris@0 70
Chris@0 71 def file=(incoming_file)
Chris@0 72 unless incoming_file.nil?
Chris@0 73 @temp_file = incoming_file
Chris@0 74 if @temp_file.size > 0
Chris@1115 75 if @temp_file.respond_to?(:original_filename)
Chris@1115 76 self.filename = @temp_file.original_filename
Chris@1115 77 self.filename.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
Chris@1115 78 end
Chris@1115 79 if @temp_file.respond_to?(:content_type)
Chris@1115 80 self.content_type = @temp_file.content_type.to_s.chomp
Chris@1115 81 end
Chris@1115 82 if content_type.blank? && filename.present?
Chris@0 83 self.content_type = Redmine::MimeType.of(filename)
Chris@0 84 end
Chris@0 85 self.filesize = @temp_file.size
Chris@0 86 end
Chris@0 87 end
Chris@0 88 end
Chris@1115 89
Chris@0 90 def file
Chris@0 91 nil
Chris@0 92 end
Chris@0 93
Chris@1115 94 def filename=(arg)
Chris@1115 95 write_attribute :filename, sanitize_filename(arg.to_s)
Chris@1115 96 filename
Chris@1115 97 end
Chris@1115 98
Chris@0 99 # Copies the temporary file to its final location
Chris@0 100 # and computes its MD5 hash
Chris@909 101 def files_to_final_location
Chris@0 102 if @temp_file && (@temp_file.size > 0)
Chris@1295 103 self.disk_directory = target_directory
Chris@1295 104 self.disk_filename = Attachment.disk_filename(filename, disk_directory)
Chris@909 105 logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)")
Chris@1295 106 path = File.dirname(diskfile)
Chris@1295 107 unless File.directory?(path)
Chris@1295 108 FileUtils.mkdir_p(path)
Chris@1295 109 end
Chris@0 110 md5 = Digest::MD5.new
Chris@441 111 File.open(diskfile, "wb") do |f|
Chris@1115 112 if @temp_file.respond_to?(:read)
Chris@1115 113 buffer = ""
Chris@1115 114 while (buffer = @temp_file.read(8192))
Chris@1115 115 f.write(buffer)
Chris@1115 116 md5.update(buffer)
Chris@1115 117 end
Chris@1115 118 else
Chris@1115 119 f.write(@temp_file)
Chris@1115 120 md5.update(@temp_file)
Chris@0 121 end
Chris@0 122 end
Chris@0 123 self.digest = md5.hexdigest
Chris@0 124 end
Chris@909 125 @temp_file = nil
Chris@0 126 # Don't save the content type if it's longer than the authorized length
Chris@0 127 if self.content_type && self.content_type.length > 255
Chris@0 128 self.content_type = nil
Chris@0 129 end
Chris@0 130 end
Chris@0 131
Chris@1115 132 # Deletes the file from the file system if it's not referenced by other attachments
Chris@909 133 def delete_from_disk
Chris@1115 134 if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty?
Chris@1115 135 delete_from_disk!
Chris@1115 136 end
Chris@0 137 end
Chris@0 138
Chris@0 139 # Returns file's location on disk
Chris@0 140 def diskfile
Chris@1295 141 File.join(self.class.storage_path, disk_directory.to_s, disk_filename.to_s)
Chris@1115 142 end
Chris@1115 143
Chris@1115 144 def title
Chris@1115 145 title = filename.to_s
Chris@1115 146 if description.present?
Chris@1115 147 title << " (#{description})"
Chris@1115 148 end
Chris@1115 149 title
Chris@0 150 end
Chris@441 151
Chris@0 152 def increment_download
Chris@0 153 increment!(:downloads)
Chris@0 154 end
Chris@0 155
Chris@0 156 def project
Chris@1115 157 container.try(:project)
Chris@0 158 end
Chris@441 159
Chris@0 160 def visible?(user=User.current)
Chris@1295 161 if container_id
Chris@1295 162 container && container.attachments_visible?(user)
Chris@1295 163 else
Chris@1295 164 author == user
Chris@1295 165 end
Chris@0 166 end
Chris@441 167
Chris@0 168 def deletable?(user=User.current)
Chris@1295 169 if container_id
Chris@1295 170 container && container.attachments_deletable?(user)
Chris@1295 171 else
Chris@1295 172 author == user
Chris@1295 173 end
Chris@0 174 end
Chris@441 175
Chris@0 176 def image?
Chris@1115 177 !!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i)
Chris@1115 178 end
Chris@1115 179
Chris@1115 180 def thumbnailable?
Chris@1115 181 image?
Chris@1115 182 end
Chris@1115 183
Chris@1115 184 # Returns the full path the attachment thumbnail, or nil
Chris@1115 185 # if the thumbnail cannot be generated.
Chris@1115 186 def thumbnail(options={})
Chris@1115 187 if thumbnailable? && readable?
Chris@1115 188 size = options[:size].to_i
Chris@1115 189 if size > 0
Chris@1115 190 # Limit the number of thumbnails per image
Chris@1115 191 size = (size / 50) * 50
Chris@1115 192 # Maximum thumbnail size
Chris@1115 193 size = 800 if size > 800
Chris@1115 194 else
Chris@1115 195 size = Setting.thumbnails_size.to_i
Chris@1115 196 end
Chris@1115 197 size = 100 unless size > 0
Chris@1115 198 target = File.join(self.class.thumbnails_storage_path, "#{id}_#{digest}_#{size}.thumb")
Chris@1115 199
Chris@1115 200 begin
Chris@1115 201 Redmine::Thumbnail.generate(self.diskfile, target, size)
Chris@1115 202 rescue => e
Chris@1115 203 logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger
Chris@1115 204 return nil
Chris@1115 205 end
Chris@1115 206 end
Chris@1115 207 end
Chris@1115 208
Chris@1115 209 # Deletes all thumbnails
Chris@1115 210 def self.clear_thumbnails
Chris@1115 211 Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file|
Chris@1115 212 File.delete file
Chris@1115 213 end
Chris@0 214 end
Chris@441 215
Chris@0 216 def is_text?
Chris@0 217 Redmine::MimeType.is_type?('text', filename)
Chris@0 218 end
Chris@441 219
Chris@0 220 def is_diff?
Chris@0 221 self.filename =~ /\.(patch|diff)$/i
Chris@0 222 end
Chris@441 223
Chris@0 224 # Returns true if the file is readable
Chris@0 225 def readable?
Chris@0 226 File.readable?(diskfile)
Chris@0 227 end
Chris@0 228
Chris@1115 229 # Returns the attachment token
Chris@1115 230 def token
Chris@1115 231 "#{id}.#{digest}"
Chris@1115 232 end
Chris@1115 233
Chris@1115 234 # Finds an attachment that matches the given token and that has no container
Chris@1115 235 def self.find_by_token(token)
Chris@1115 236 if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/
Chris@1115 237 attachment_id, attachment_digest = $1, $2
Chris@1115 238 attachment = Attachment.where(:id => attachment_id, :digest => attachment_digest).first
Chris@1115 239 if attachment && attachment.container.nil?
Chris@1115 240 attachment
Chris@1115 241 end
Chris@1115 242 end
Chris@1115 243 end
Chris@1115 244
Chris@0 245 # Bulk attaches a set of files to an object
Chris@0 246 #
Chris@0 247 # Returns a Hash of the results:
Chris@0 248 # :files => array of the attached files
Chris@0 249 # :unsaved => array of the files that could not be attached
Chris@0 250 def self.attach_files(obj, attachments)
Chris@1115 251 result = obj.save_attachments(attachments, User.current)
Chris@1115 252 obj.attach_saved_attachments
Chris@1115 253 result
Chris@0 254 end
Chris@441 255
Chris@909 256 def self.latest_attach(attachments, filename)
Chris@1115 257 attachments.sort_by(&:created_on).reverse.detect {
Chris@909 258 |att| att.filename.downcase == filename.downcase
Chris@909 259 }
Chris@909 260 end
Chris@909 261
Chris@1115 262 def self.prune(age=1.day)
Chris@1115 263 Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all
Chris@1115 264 end
Chris@1115 265
Chris@1295 266 # Moves an existing attachment to its target directory
Chris@1295 267 def move_to_target_directory!
Chris@1295 268 if !new_record? & readable?
Chris@1295 269 src = diskfile
Chris@1295 270 self.disk_directory = target_directory
Chris@1295 271 dest = diskfile
Chris@1295 272 if src != dest && FileUtils.mkdir_p(File.dirname(dest)) && FileUtils.mv(src, dest)
Chris@1295 273 update_column :disk_directory, disk_directory
Chris@1295 274 end
Chris@1295 275 end
Chris@1295 276 end
Chris@1295 277
Chris@1295 278 # Moves existing attachments that are stored at the root of the files
Chris@1295 279 # directory (ie. created before Redmine 2.3) to their target subdirectories
Chris@1295 280 def self.move_from_root_to_target_directory
Chris@1295 281 Attachment.where("disk_directory IS NULL OR disk_directory = ''").find_each do |attachment|
Chris@1295 282 attachment.move_to_target_directory!
Chris@1295 283 end
Chris@1295 284 end
Chris@1295 285
Chris@1115 286 private
Chris@1115 287
Chris@1115 288 # Physically deletes the file from the file system
Chris@1115 289 def delete_from_disk!
Chris@1115 290 if disk_filename.present? && File.exist?(diskfile)
Chris@1115 291 File.delete(diskfile)
Chris@1115 292 end
Chris@1115 293 end
Chris@1115 294
Chris@0 295 def sanitize_filename(value)
Chris@0 296 # get only the filename, not the whole path
Chris@0 297 just_filename = value.gsub(/^.*(\\|\/)/, '')
Chris@0 298
Chris@909 299 # Finally, replace invalid characters with underscore
Chris@909 300 @filename = just_filename.gsub(/[\/\?\%\*\:\|\"\'<>]+/, '_')
Chris@0 301 end
Chris@441 302
Chris@1295 303 # Returns the subdirectory in which the attachment will be saved
Chris@1295 304 def target_directory
Chris@1295 305 time = created_on || DateTime.now
Chris@1295 306 time.strftime("%Y/%m")
Chris@1295 307 end
Chris@1295 308
Chris@1295 309 # Returns an ASCII or hashed filename that do not
Chris@1295 310 # exists yet in the given subdirectory
Chris@1295 311 def self.disk_filename(filename, directory=nil)
Chris@0 312 timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
Chris@0 313 ascii = ''
Chris@0 314 if filename =~ %r{^[a-zA-Z0-9_\.\-]*$}
Chris@0 315 ascii = filename
Chris@0 316 else
Chris@0 317 ascii = Digest::MD5.hexdigest(filename)
Chris@0 318 # keep the extension if any
Chris@0 319 ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
Chris@0 320 end
Chris@1295 321 while File.exist?(File.join(storage_path, directory.to_s, "#{timestamp}_#{ascii}"))
Chris@0 322 timestamp.succ!
Chris@0 323 end
Chris@0 324 "#{timestamp}_#{ascii}"
Chris@0 325 end
Chris@0 326 end