diff --git a/app/models/cms/attachment.rb b/app/models/cms/attachment.rb index fd7d385c0..659720824 100644 --- a/app/models/cms/attachment.rb +++ b/app/models/cms/attachment.rb @@ -17,7 +17,7 @@ class Attachment < ActiveRecord::Base before_validation :set_cardinality before_save :set_section, :sanitized_file_path_and_name before_create :setup_attachment - + after_save :clear_cached_files belongs_to :attachable, :polymorphic => true include DefaultAccessible @@ -269,5 +269,20 @@ def dirty! # Seems like a hack, is there a better way? self.updated_at = Time.now end + + #ensure all versions of this file are cleared from cache + def clear_cached_files + if Rails.configuration.cms.attachments.file_cache_directory + versions.each do |file| + #make sure data_file_path does not start with any ../ since this is user generated + sanitized_path=file.data_file_path.gsub(/\A(\.{2}\/)*/, '') + path = File.join(Rails.configuration.cms.attachments.file_cache_directory, file.data_file_path) + if File.exists?(path) + FileUtils.rm(path) + end + end + end + end + end end diff --git a/lib/cms/attachments/attachment_serving.rb b/lib/cms/attachments/attachment_serving.rb index 27009465b..6f82e00f2 100644 --- a/lib/cms/attachments/attachment_serving.rb +++ b/lib/cms/attachments/attachment_serving.rb @@ -32,7 +32,12 @@ def self.send_attachments_with end class FilesystemStrategy - + + def self.file_cache_directory + Rails.configuration.cms.attachments.file_cache_directory + end + + def self.attachments_storage_location Rails.configuration.cms.attachments.storage_directory end @@ -42,6 +47,7 @@ def self.send_attachment(attachment, controller) style = "original" unless style path_to_file = attachment.path(style) if File.exists?(path_to_file) + copy_file_to_cache(path_to_file, attachment.data_file_path) Rails.logger.debug "Sending file #{path_to_file}" controller.send_file(path_to_file, :filename => attachment.file_name, @@ -54,6 +60,20 @@ def self.send_attachment(attachment, controller) raise ActiveRecord::RecordNotFound.new(msg) end end + + def self.copy_file_to_cache(file_path, cache_path) + if file_cache_directory + cache_path = File.join(file_cache_directory, cache_path) + #remove the filename so we can do a mkdir -p + unless File.exists?(cache_path) + dir_path = cache_path.split("/")[1..-2].join("/") + FileUtils.mkdir_p(File.join("/", dir_path)) + FileUtils.cp(file_path, cache_path) + FileUtils.chmod(0644, cache_path) + end + end + end + end end end \ No newline at end of file