annotate .svn/pristine/85/8519fb0f08b4338ed0712c0e2af20a32e713969e.svn-base @ 1494:e248c7af89ec redmine-2.4

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