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

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