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

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