annotate app/models/attachment.rb @ 1296:038ba2d95de8 redmine-2.2

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