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

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