]> source.dussan.org Git - redmine.git/commitdiff
Adds a rake task to update attachments digests to SHA256 (#25240).
authorJean-Philippe Lang <jp_lang@yahoo.fr>
Mon, 3 Apr 2017 11:38:06 +0000 (11:38 +0000)
committerJean-Philippe Lang <jp_lang@yahoo.fr>
Mon, 3 Apr 2017 11:38:06 +0000 (11:38 +0000)
Patch by Jens Krämer.

git-svn-id: http://svn.redmine.org/redmine/trunk@16455 e93f8b46-1217-0410-a6f0-8f06a7374b81

app/models/attachment.rb
lib/tasks/redmine.rake
test/unit/attachment_test.rb

index 3bfecfc7b2e5225572283b25d866716c0a222c54..d68a050c125117e9e2eef45209a8d18f731e6561 100644 (file)
@@ -252,7 +252,7 @@ class Attachment < ActiveRecord::Base
 
   # Returns true if the file is readable
   def readable?
-    File.readable?(diskfile)
+    disk_filename.present? && File.readable?(diskfile)
   end
 
   # Returns the attachment token
@@ -352,6 +352,27 @@ class Attachment < ActiveRecord::Base
     end
   end
 
+  # Updates digests to SHA256 for all attachments that have a MD5 digest
+  # (ie. created before Redmine 3.4)
+  def self.update_digests_to_sha256
+    Attachment.where("length(digest) < 64").find_each do |attachment|
+      attachment.update_digest_to_sha256!
+    end
+  end
+
+  # Updates attachment digest to SHA256
+  def update_digest_to_sha256!
+    if readable?
+      sha = Digest::SHA256.new
+      File.open(diskfile, 'rb') do |f|
+        while buffer = f.read(8192)
+          sha.update(buffer)
+        end
+      end
+      update_column :digest, sha.hexdigest
+    end
+  end
+
   # Returns true if the extension is allowed regarding allowed/denied
   # extensions defined in application settings, otherwise false
   def self.valid_extension?(extension)
index f1827bb656c760f78a300f62895ac5ad8147431f..734cad0a4d75337b60d65a1cca223c959ac3c9f6 100644 (file)
@@ -26,6 +26,11 @@ namespace :redmine do
     task :move_to_subdirectories => :environment do
       Attachment.move_from_root_to_target_directory
     end
+
+    desc 'Updates attachment digests to SHA256'
+    task :update_digests => :environment do
+      Attachment.update_digests_to_sha256
+    end
   end
 
   namespace :tokens do
index a70009d231bd4153666e2efeb7a5bfb9fb8c541b..16f02e51a178028e7ba5ccc931c24c8d6cb990f8 100644 (file)
@@ -332,6 +332,14 @@ class AttachmentTest < ActiveSupport::TestCase
     assert_equal 'text/plain', attachment.content_type
   end
 
+  def test_update_digest_to_sha256_should_update_digest
+    set_fixtures_attachments_directory
+    attachment = Attachment.find 6
+    assert attachment.readable?
+    attachment.update_digest_to_sha256!
+    assert_equal 'ac5c6e99a21ae74b2e3f5b8e5b568be1b9107cd7153d139e822b9fe5caf50938', attachment.digest
+  end
+
   def test_update_attachments
     attachments = Attachment.where(:id => [2, 3]).to_a
 
@@ -430,4 +438,5 @@ class AttachmentTest < ActiveSupport::TestCase
   else
     puts '(ImageMagick convert not available)'
   end
+
 end