You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

attachment.rb 10KB

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