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

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