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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require "digest"
  19. require "fileutils"
  20. class Attachment < ActiveRecord::Base
  21. include Redmine::SafeAttributes
  22. belongs_to :container, :polymorphic => true
  23. belongs_to :author, :class_name => "User"
  24. validates_presence_of :filename, :author
  25. validates_length_of :filename, :maximum => 255
  26. validates_length_of :disk_filename, :maximum => 255
  27. validates_length_of :description, :maximum => 255
  28. validate :validate_max_file_size, :validate_file_extension
  29. acts_as_event :title => :filename,
  30. :url => Proc.new {|o| {:controller => 'attachments', :action => 'show', :id => o.id, :filename => o.filename}}
  31. acts_as_activity_provider :type => 'files',
  32. :permission => :view_files,
  33. :author_key => :author_id,
  34. :scope => select("#{Attachment.table_name}.*").
  35. joins("LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " +
  36. "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 )")
  37. acts_as_activity_provider :type => 'documents',
  38. :permission => :view_documents,
  39. :author_key => :author_id,
  40. :scope => select("#{Attachment.table_name}.*").
  41. joins("LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " +
  42. "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id")
  43. cattr_accessor :storage_path
  44. @@storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
  45. cattr_accessor :thumbnails_storage_path
  46. @@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails")
  47. before_create :files_to_final_location
  48. after_rollback :delete_from_disk, :on => :create
  49. after_commit :delete_from_disk, :on => :destroy
  50. after_commit :reuse_existing_file_if_possible, :on => :create
  51. safe_attributes 'filename', 'content_type', 'description'
  52. # Returns an unsaved copy of the attachment
  53. def copy(attributes=nil)
  54. copy = self.class.new
  55. copy.attributes = self.attributes.dup.except("id", "downloads")
  56. copy.attributes = attributes if attributes
  57. copy
  58. end
  59. def validate_max_file_size
  60. if @temp_file && self.filesize > Setting.attachment_max_size.to_i.kilobytes
  61. errors.add(:base, l(:error_attachment_too_big, :max_size => Setting.attachment_max_size.to_i.kilobytes))
  62. end
  63. end
  64. def validate_file_extension
  65. if @temp_file
  66. extension = File.extname(filename)
  67. unless self.class.valid_extension?(extension)
  68. errors.add(:base, l(:error_attachment_extension_not_allowed, :extension => extension))
  69. end
  70. end
  71. end
  72. def file=(incoming_file)
  73. unless incoming_file.nil?
  74. @temp_file = incoming_file
  75. if @temp_file.respond_to?(:original_filename)
  76. self.filename = @temp_file.original_filename
  77. self.filename.force_encoding("UTF-8")
  78. end
  79. if @temp_file.respond_to?(:content_type)
  80. self.content_type = @temp_file.content_type.to_s.chomp
  81. end
  82. self.filesize = @temp_file.size
  83. end
  84. end
  85. def file
  86. nil
  87. end
  88. def filename=(arg)
  89. write_attribute :filename, sanitize_filename(arg.to_s)
  90. filename
  91. end
  92. # Copies the temporary file to its final location
  93. # and computes its MD5 hash
  94. def files_to_final_location
  95. if @temp_file
  96. self.disk_directory = target_directory
  97. self.disk_filename = Attachment.disk_filename(filename, disk_directory)
  98. logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)") if logger
  99. path = File.dirname(diskfile)
  100. unless File.directory?(path)
  101. FileUtils.mkdir_p(path)
  102. end
  103. sha = Digest::SHA256.new
  104. File.open(diskfile, "wb") do |f|
  105. if @temp_file.respond_to?(:read)
  106. buffer = ""
  107. while (buffer = @temp_file.read(8192))
  108. f.write(buffer)
  109. sha.update(buffer)
  110. end
  111. else
  112. f.write(@temp_file)
  113. sha.update(@temp_file)
  114. end
  115. end
  116. self.digest = sha.hexdigest
  117. end
  118. @temp_file = nil
  119. if content_type.blank? && filename.present?
  120. self.content_type = Redmine::MimeType.of(filename)
  121. end
  122. # Don't save the content type if it's longer than the authorized length
  123. if self.content_type && self.content_type.length > 255
  124. self.content_type = nil
  125. end
  126. end
  127. # Deletes the file from the file system if it's not referenced by other attachments
  128. def delete_from_disk
  129. if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty?
  130. delete_from_disk!
  131. end
  132. end
  133. # Returns file's location on disk
  134. def diskfile
  135. File.join(self.class.storage_path, disk_directory.to_s, disk_filename.to_s)
  136. end
  137. def title
  138. title = filename.dup
  139. if description.present?
  140. title << " (#{description})"
  141. end
  142. title
  143. end
  144. def increment_download
  145. increment!(:downloads)
  146. end
  147. def project
  148. container.try(:project)
  149. end
  150. def visible?(user=User.current)
  151. if container_id
  152. container && container.attachments_visible?(user)
  153. else
  154. author == user
  155. end
  156. end
  157. def editable?(user=User.current)
  158. if container_id
  159. container && container.attachments_editable?(user)
  160. else
  161. author == user
  162. end
  163. end
  164. def deletable?(user=User.current)
  165. if container_id
  166. container && container.attachments_deletable?(user)
  167. else
  168. author == user
  169. end
  170. end
  171. def image?
  172. !!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i)
  173. end
  174. def thumbnailable?
  175. image? || (is_pdf? && Redmine::Thumbnail.gs_available?)
  176. end
  177. # Returns the full path the attachment thumbnail, or nil
  178. # if the thumbnail cannot be generated.
  179. def thumbnail(options={})
  180. if thumbnailable? && readable?
  181. size = options[:size].to_i
  182. if size > 0
  183. # Limit the number of thumbnails per image
  184. size = (size / 50.0).ceil * 50
  185. # Maximum thumbnail size
  186. size = 800 if size > 800
  187. else
  188. size = Setting.thumbnails_size.to_i
  189. end
  190. size = 100 unless size > 0
  191. target = thumbnail_path(size)
  192. begin
  193. Redmine::Thumbnail.generate(self.diskfile, target, size, is_pdf?)
  194. rescue => e
  195. logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger
  196. return nil
  197. end
  198. end
  199. end
  200. # Deletes all thumbnails
  201. def self.clear_thumbnails
  202. Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file|
  203. File.delete file
  204. end
  205. end
  206. def is_text?
  207. Redmine::MimeType.is_type?('text', filename) || Redmine::SyntaxHighlighting.filename_supported?(filename)
  208. end
  209. def is_image?
  210. Redmine::MimeType.is_type?('image', filename)
  211. end
  212. def is_diff?
  213. /\.(patch|diff)$/i.match?(filename)
  214. end
  215. def is_pdf?
  216. Redmine::MimeType.of(filename) == "application/pdf"
  217. end
  218. def is_video?
  219. Redmine::MimeType.is_type?('video', filename)
  220. end
  221. def is_audio?
  222. Redmine::MimeType.is_type?('audio', filename)
  223. end
  224. def previewable?
  225. is_text? || is_image? || is_video? || is_audio?
  226. end
  227. # Returns true if the file is readable
  228. def readable?
  229. disk_filename.present? && File.readable?(diskfile)
  230. end
  231. # Returns the attachment token
  232. def token
  233. "#{id}.#{digest}"
  234. end
  235. # Finds an attachment that matches the given token and that has no container
  236. def self.find_by_token(token)
  237. if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/
  238. attachment_id, attachment_digest = $1, $2
  239. attachment = Attachment.find_by(:id => attachment_id, :digest => attachment_digest)
  240. if attachment && attachment.container.nil?
  241. attachment
  242. end
  243. end
  244. end
  245. # Bulk attaches a set of files to an object
  246. #
  247. # Returns a Hash of the results:
  248. # :files => array of the attached files
  249. # :unsaved => array of the files that could not be attached
  250. def self.attach_files(obj, attachments)
  251. result = obj.save_attachments(attachments, User.current)
  252. obj.attach_saved_attachments
  253. result
  254. end
  255. # Updates the filename and description of a set of attachments
  256. # with the given hash of attributes. Returns true if all
  257. # attachments were updated.
  258. #
  259. # Example:
  260. # Attachment.update_attachments(attachments, {
  261. # 4 => {:filename => 'foo'},
  262. # 7 => {:filename => 'bar', :description => 'file description'}
  263. # })
  264. #
  265. def self.update_attachments(attachments, params)
  266. params = params.transform_keys {|key| key.to_i}
  267. saved = true
  268. transaction do
  269. attachments.each do |attachment|
  270. if p = params[attachment.id]
  271. attachment.filename = p[:filename] if p.key?(:filename)
  272. attachment.description = p[:description] if p.key?(:description)
  273. saved &&= attachment.save
  274. end
  275. end
  276. unless saved
  277. raise ActiveRecord::Rollback
  278. end
  279. end
  280. saved
  281. end
  282. def self.latest_attach(attachments, filename)
  283. attachments.sort_by(&:created_on).reverse.detect do |att|
  284. filename.casecmp(att.filename) == 0
  285. end
  286. end
  287. def self.prune(age=1.day)
  288. Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all
  289. end
  290. # Moves an existing attachment to its target directory
  291. def move_to_target_directory!
  292. return unless !new_record? & readable?
  293. src = diskfile
  294. self.disk_directory = target_directory
  295. dest = diskfile
  296. return if src == dest
  297. if !FileUtils.mkdir_p(File.dirname(dest))
  298. logger.error "Could not create directory #{File.dirname(dest)}" if logger
  299. return
  300. end
  301. if !FileUtils.mv(src, dest)
  302. logger.error "Could not move attachment from #{src} to #{dest}" if logger
  303. return
  304. end
  305. update_column :disk_directory, disk_directory
  306. end
  307. # Moves existing attachments that are stored at the root of the files
  308. # directory (ie. created before Redmine 2.3) to their target subdirectories
  309. def self.move_from_root_to_target_directory
  310. Attachment.where("disk_directory IS NULL OR disk_directory = ''").find_each do |attachment|
  311. attachment.move_to_target_directory!
  312. end
  313. end
  314. # Updates digests to SHA256 for all attachments that have a MD5 digest
  315. # (ie. created before Redmine 3.4)
  316. def self.update_digests_to_sha256
  317. Attachment.where("length(digest) < 64").find_each do |attachment|
  318. attachment.update_digest_to_sha256!
  319. end
  320. end
  321. # Updates attachment digest to SHA256
  322. def update_digest_to_sha256!
  323. if readable?
  324. sha = Digest::SHA256.new
  325. File.open(diskfile, 'rb') do |f|
  326. while buffer = f.read(8192)
  327. sha.update(buffer)
  328. end
  329. end
  330. update_column :digest, sha.hexdigest
  331. end
  332. end
  333. # Returns true if the extension is allowed regarding allowed/denied
  334. # extensions defined in application settings, otherwise false
  335. def self.valid_extension?(extension)
  336. denied, allowed = [:attachment_extensions_denied, :attachment_extensions_allowed].map do |setting|
  337. Setting.send(setting)
  338. end
  339. if denied.present? && extension_in?(extension, denied)
  340. return false
  341. end
  342. if allowed.present? && !extension_in?(extension, allowed)
  343. return false
  344. end
  345. true
  346. end
  347. # Returns true if extension belongs to extensions list.
  348. def self.extension_in?(extension, extensions)
  349. extension = extension.downcase.sub(/\A\.+/, '')
  350. unless extensions.is_a?(Array)
  351. extensions = extensions.to_s.split(",").map(&:strip)
  352. end
  353. extensions = extensions.map {|s| s.downcase.sub(/\A\.+/, '')}.reject(&:blank?)
  354. extensions.include?(extension)
  355. end
  356. # Returns true if attachment's extension belongs to extensions list.
  357. def extension_in?(extensions)
  358. self.class.extension_in?(File.extname(filename), extensions)
  359. end
  360. # returns either MD5 or SHA256 depending on the way self.digest was computed
  361. def digest_type
  362. digest.size < 64 ? "MD5" : "SHA256" if digest.present?
  363. end
  364. private
  365. def reuse_existing_file_if_possible
  366. original_diskfile = nil
  367. reused = with_lock do
  368. if existing = Attachment
  369. .where(digest: self.digest, filesize: self.filesize)
  370. .where('id <> ? and disk_filename <> ?',
  371. self.id, self.disk_filename)
  372. .first
  373. existing.with_lock do
  374. original_diskfile = self.diskfile
  375. existing_diskfile = existing.diskfile
  376. if File.readable?(original_diskfile) &&
  377. File.readable?(existing_diskfile) &&
  378. FileUtils.identical?(original_diskfile, existing_diskfile)
  379. self.update_columns disk_directory: existing.disk_directory,
  380. disk_filename: existing.disk_filename
  381. end
  382. end
  383. end
  384. end
  385. if reused
  386. File.delete(original_diskfile)
  387. end
  388. rescue ActiveRecord::StatementInvalid, ActiveRecord::RecordNotFound
  389. # Catch and ignore lock errors. It is not critical if deduplication does
  390. # not happen, therefore we do not retry.
  391. # with_lock throws ActiveRecord::RecordNotFound if the record isnt there
  392. # anymore, thats why this is caught and ignored as well.
  393. end
  394. # Physically deletes the file from the file system
  395. def delete_from_disk!
  396. if disk_filename.present? && File.exist?(diskfile)
  397. File.delete(diskfile)
  398. end
  399. Dir[thumbnail_path("*")].each do |thumb|
  400. File.delete(thumb)
  401. end
  402. end
  403. def thumbnail_path(size)
  404. File.join(self.class.thumbnails_storage_path,
  405. "#{digest}_#{filesize}_#{size}.thumb")
  406. end
  407. def sanitize_filename(value)
  408. # get only the filename, not the whole path
  409. just_filename = value.gsub(/\A.*(\\|\/)/m, '')
  410. # Finally, replace invalid characters with underscore
  411. just_filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_')
  412. end
  413. # Returns the subdirectory in which the attachment will be saved
  414. def target_directory
  415. time = created_on || DateTime.now
  416. time.strftime("%Y/%m")
  417. end
  418. # Returns an ASCII or hashed filename that do not
  419. # exists yet in the given subdirectory
  420. def self.disk_filename(filename, directory=nil)
  421. timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
  422. ascii = ''
  423. if %r{^[a-zA-Z0-9_\.\-]*$}.match?(filename) && filename.length <= 50
  424. ascii = filename
  425. else
  426. ascii = Digest::MD5.hexdigest(filename)
  427. # keep the extension if any
  428. ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
  429. end
  430. while File.exist?(File.join(storage_path, directory.to_s, "#{timestamp}_#{ascii}"))
  431. timestamp.succ!
  432. end
  433. "#{timestamp}_#{ascii}"
  434. end
  435. end