annotate .svn/pristine/28/2840fb98174d2a4d326c6f441324c06bb7ec4f82.svn-base @ 1298:4f746d8966dd redmine_2.3_integration

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