X-Git-Url: https://projects.mako.cc/source/selectricity/blobdiff_plain/9129a21b28c88064edfcfc8a8fa23a640f29819c..e6fe35a13a73266debac4ce0cc42121b6845ab83:/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb index 013e225..e282825 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb @@ -1,8 +1,38 @@ module Technoweenie # :nodoc: module AttachmentFu # :nodoc: - @@default_processors = %w(ImageScience Rmagick MiniMagick) + @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage) @@tempfile_path = File.join(RAILS_ROOT, 'tmp', 'attachment_fu') - @@content_types = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'] + @@content_types = [ + 'image/jpeg', + 'image/pjpeg', + 'image/jpg', + 'image/gif', + 'image/png', + 'image/x-png', + 'image/jpg', + 'image/x-ms-bmp', + 'image/bmp', + 'image/x-bmp', + 'image/x-bitmap', + 'image/x-xbitmap', + 'image/x-win-bitmap', + 'image/x-windows-bmp', + 'image/ms-bmp', + 'application/bmp', + 'application/x-bmp', + 'application/x-win-bitmap', + 'application/preview', + 'image/jp_', + 'application/jpg', + 'application/x-jpg', + 'image/pipeg', + 'image/vnd.swiftview-jpeg', + 'image/x-xbitmap', + 'application/png', + 'application/x-png', + 'image/gi_', + 'image/x-citrix-pjpeg' + ] mattr_reader :content_types, :tempfile_path, :default_processors mattr_writer :tempfile_path @@ -10,7 +40,7 @@ module Technoweenie # :nodoc: class AttachmentError < StandardError; end module ActMethods - # Options: + # Options: # * :content_type - Allowed content types. Allows all by default. Use :image to allow all standard image types. # * :min_size - Minimum size allowed. 1 byte is the default. # * :max_size - Maximum size allowed. 1.megabyte is the default. @@ -20,7 +50,15 @@ module Technoweenie # :nodoc: # * :thumbnail_class - Set what class to use for thumbnails. This attachment class is used by default. # * :path_prefix - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name} # for the S3 backend. Setting this sets the :storage to :file_system. + # * :storage - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system. + # * :cloundfront - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to + # set a distribution domain in the amazon_s3.yml config file. Defaults to false + # * :bucket_key - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use + # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding + # bucket in the amazon_s3.yml file. + + # * :keep_profile By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data. # # Examples: # has_attachment :max_size => 1.kilobyte @@ -31,7 +69,7 @@ module Technoweenie # :nodoc: # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50' # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } # has_attachment :storage => :file_system, :path_prefix => 'public/files' - # has_attachment :storage => :file_system, :path_prefix => 'public/files', + # has_attachment :storage => :file_system, :path_prefix => 'public/files', # :content_type => :image, :resize_to => [50,50] # has_attachment :storage => :file_system, :path_prefix => 'public/files', # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } @@ -44,62 +82,84 @@ module Technoweenie # :nodoc: options[:thumbnails] ||= {} options[:thumbnail_class] ||= self options[:s3_access] ||= :public_read + options[:cloudfront] ||= false options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil? - + unless options[:thumbnails].is_a?(Hash) raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }" end - + + extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods) + include InstanceMethods unless included_modules.include?(InstanceMethods) + + parent_options = attachment_options || {} # doing these shenanigans so that #attachment_options is available to processors and backends - class_inheritable_accessor :attachment_options self.attachment_options = options - # only need to define these once on a class - unless included_modules.include?(InstanceMethods) - attr_accessor :thumbnail_resize_options + attr_accessor :thumbnail_resize_options - attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file - attachment_options[:path_prefix] ||= attachment_options[:file_system_path] - if attachment_options[:path_prefix].nil? - attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name) + attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file + attachment_options[:storage] ||= parent_options[:storage] + attachment_options[:path_prefix] ||= attachment_options[:file_system_path] + if attachment_options[:path_prefix].nil? + attachment_options[:path_prefix] = case attachment_options[:storage] + when :s3 then table_name + when :cloud_files then table_name + else File.join("public", table_name) end - attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/' + end + attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/' - with_options :foreign_key => 'parent_id' do |m| - m.has_many :thumbnails, :class_name => attachment_options[:thumbnail_class].to_s - m.belongs_to :parent, :class_name => base_class.to_s + association_options = { :foreign_key => 'parent_id' } + if attachment_options[:association_options] + association_options.merge!(attachment_options[:association_options]) + end + with_options(association_options) do |m| + m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}" + m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty? + end + + storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") + include storage_mod unless included_modules.include?(storage_mod) + + case attachment_options[:processor] + when :none, nil + processors = Technoweenie::AttachmentFu.default_processors.dup + begin + if processors.any? + attachment_options[:processor] = processors.first + processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") + include processor_mod unless included_modules.include?(processor_mod) + end + rescue Object, Exception + raise unless load_related_exception?($!) + + processors.shift + retry end - before_destroy :destroy_thumbnails - - before_validation :set_size_from_temp_path - after_save :after_process_attachment - after_destroy :destroy_file - extend ClassMethods - include InstanceMethods - include Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") - case attachment_options[:processor] - when :none - when nil - processors = Technoweenie::AttachmentFu.default_processors.dup - begin - if processors.any? - attachment_options[:processor] = "#{processors.first}Processor" - include Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor]) - end - rescue LoadError, MissingSourceFile - processors.shift - retry - end - else - begin - include Technoweenie::AttachmentFu::Processors.const_get("#{options[:processor].to_s.classify}Processor") - rescue LoadError, MissingSourceFile - puts "Problems loading #{options[:processor]}Processor: #{$!}" - end + else + begin + processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") + include processor_mod unless included_modules.include?(processor_mod) + rescue Object, Exception + raise unless load_related_exception?($!) + + puts "Problems loading #{options[:processor]}Processor: #{$!}" end - after_validation :process_attachment + end unless parent_options[:processor] # Don't let child override processor + end + + def load_related_exception?(e) #:nodoc: implementation specific + case + when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError" + # We can't rescue CompilationError directly, as it is part of the RubyInline library. + # We must instead rescue RuntimeError, and check the class' name. + true + else + false end end + private :load_related_exception? end module ClassMethods @@ -116,41 +176,56 @@ module Technoweenie # :nodoc: content_types.include?(content_type) end - # Callback after an image has been resized. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # after_resize do |record, img| - # record.aspect_ratio = img.columns.to_f / img.rows.to_f - # end - # end - def after_resize(&block) - write_inheritable_array(:after_resize, [block]) + def self.extended(base) + base.class_inheritable_accessor :attachment_options + base.before_destroy :destroy_thumbnails + base.before_validation :set_size_from_temp_path + base.after_save :after_process_attachment + base.after_destroy :destroy_file + base.after_validation :process_attachment + if defined?(::ActiveSupport::Callbacks) + base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved + end end - # Callback after an attachment has been saved either to the file system or the DB. - # Only called if the file has been changed, not necessarily if the record is updated. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # after_attachment_saved do |record| - # ... - # end - # end - def after_attachment_saved(&block) - write_inheritable_array(:after_attachment_saved, [block]) - end + unless defined?(::ActiveSupport::Callbacks) + # Callback after an image has been resized. + # + # class Foo < ActiveRecord::Base + # acts_as_attachment + # after_resize do |record, img| + # record.aspect_ratio = img.columns.to_f / img.rows.to_f + # end + # end + def after_resize(&block) + write_inheritable_array(:after_resize, [block]) + end - # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # before_thumbnail_saved do |record, thumbnail| - # ... - # end - # end - def before_thumbnail_saved(&block) - write_inheritable_array(:before_thumbnail_saved, [block]) + # Callback after an attachment has been saved either to the file system or the DB. + # Only called if the file has been changed, not necessarily if the record is updated. + # + # class Foo < ActiveRecord::Base + # acts_as_attachment + # after_attachment_saved do |record| + # ... + # end + # end + def after_attachment_saved(&block) + write_inheritable_array(:after_attachment_saved, [block]) + end + + # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required. + # + # class Foo < ActiveRecord::Base + # acts_as_attachment + # before_thumbnail_saved do |thumbnail| + # record = thumbnail.parent + # ... + # end + # end + def before_thumbnail_saved(&block) + write_inheritable_array(:before_thumbnail_saved, [block]) + end end # Get the thumbnail class, which is the current attachment class by default. @@ -167,7 +242,7 @@ module Technoweenie # :nodoc: FileUtils.cp file, tmp.path end end - + # Writes the given data to a new tempfile, returning the closed tempfile. def write_to_temp_file(data, temp_base_name) returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp| @@ -179,11 +254,15 @@ module Technoweenie # :nodoc: end module InstanceMethods + def self.included(base) + base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks) + end + # Checks whether the attachment's content type is an image content type def image? self.class.image?(content_type) end - + # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute. def thumbnailable? image? && respond_to?(:parent_id) && parent_id.nil? @@ -202,7 +281,7 @@ module Technoweenie # :nodoc: ext = s; '' end # ImageScience doesn't create gif thumbnails, only pngs - ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScienceProcessor" + ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience" "#{basename}_#{thumbnail}#{ext}" end @@ -210,12 +289,12 @@ module Technoweenie # :nodoc: def create_or_update_thumbnail(temp_file, file_name_suffix, *size) thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column")) returning find_or_initialize_thumbnail(file_name_suffix) do |thumb| - thumb.attributes = { - :content_type => content_type, - :filename => thumbnail_name_for(file_name_suffix), - :temp_path => temp_file, + thumb.temp_paths.unshift temp_file + thumb.send(:'attributes=', { + :content_type => content_type, + :filename => thumbnail_name_for(file_name_suffix), :thumbnail_resize_options => size - } + }, false) callback_with_args :before_thumbnail_saved, thumb thumb.save! end @@ -225,7 +304,7 @@ module Technoweenie # :nodoc: def content_type=(new_type) write_attribute :content_type, new_type.to_s.strip end - + # Sanitizes a filename. def filename=(new_name) write_attribute :filename, sanitize_filename(new_name) @@ -256,14 +335,21 @@ module Technoweenie # :nodoc: # # TODO: Allow it to work with Merb tempfiles too. def uploaded_data=(file_data) - return nil if file_data.nil? || file_data.size == 0 - self.content_type = file_data.content_type - self.filename = file_data.original_filename if respond_to?(:filename) + if file_data.respond_to?(:content_type) + return nil if file_data.size == 0 + self.content_type = file_data.content_type + self.filename = file_data.original_filename if respond_to?(:filename) + else + return nil if file_data.blank? || file_data['size'] == 0 + self.content_type = file_data['content_type'] + self.filename = file_data['filename'] + file_data = file_data['tempfile'] + end if file_data.is_a?(StringIO) file_data.rewind - self.temp_data = file_data.read + set_temp_data file_data.read else - self.temp_path = file_data.path + self.temp_paths.unshift file_data end end @@ -275,40 +361,33 @@ module Technoweenie # :nodoc: p = temp_paths.first p.respond_to?(:path) ? p.path : p.to_s end - + # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename. def temp_paths - @temp_paths ||= (new_record? || !File.exist?(full_filename)) ? [] : [copy_to_temp_file(full_filename)] - end - - # Adds a new temp_path to the array. This should take a string or a Tempfile. This class makes no - # attempt to remove the files, so Tempfiles should be used. Tempfiles remove themselves when they go out of scope. - # You can also use string paths for temporary files, such as those used for uploaded files in a web server. - def temp_path=(value) - temp_paths.unshift value - temp_path + @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ? + [] : [copy_to_temp_file(full_filename)]) end # Gets the data from the latest temp file. This will read the file into memory. def temp_data save_attachment? ? File.read(temp_path) : nil end - + # Writes the given data to a Tempfile and adds it to the collection of temp files. - def temp_data=(data) - self.temp_path = write_to_temp_file data unless data.nil? + def set_temp_data(data) + temp_paths.unshift write_to_temp_file data unless data.nil? end - + # Copies the given file to a randomly named Tempfile. def copy_to_temp_file(file) self.class.copy_to_temp_file file, random_tempfile_filename end - + # Writes the given file to a randomly named Tempfile. def write_to_temp_file(data) self.class.write_to_temp_file data, random_tempfile_filename end - + # Stub for creating a temp file from the attachment data. This should be defined in the backend module. def create_temp_file() end @@ -323,19 +402,20 @@ module Technoweenie # :nodoc: end protected - # Generates a unique filename for a Tempfile. + # Generates a unique filename for a Tempfile. def random_tempfile_filename "#{rand Time.now.to_i}#{filename || 'attachment'}" end def sanitize_filename(filename) + return unless filename returning filename.strip do |name| # NOTE: File.basename doesn't work right with Windows paths on Unix # get only the filename, not the whole path name.gsub! /^.*(\\|\/)/, '' - + # Finally, replace all non alphanumeric, underscore or periods with underscore - name.gsub! /[^\w\.\-]/, '_' + name.gsub! /[^A-Za-z0-9\.\-]/, '_' end end @@ -348,7 +428,11 @@ module Technoweenie # :nodoc: def attachment_attributes_valid? [:size, :content_type].each do |attr_name| enum = attachment_options[attr_name] - errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) + if Object.const_defined?(:I18n) # Rails >= 2.2 + errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name)) + else + errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) + end end end @@ -383,24 +467,44 @@ module Technoweenie # :nodoc: if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image resize_image(img, attachment_options[:resize_to]) elsif thumbnail_resize_options # thumbnail - resize_image(img, thumbnail_resize_options) + resize_image(img, thumbnail_resize_options) end end # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self. # Only accept blocks, however - def callback_with_args(method, arg = self) - notify(method) + if ActiveSupport.const_defined?(:Callbacks) + # Rails 2.1 and beyond! + def callback_with_args(method, arg = self) + notify(method) + + result = run_callbacks(method, { :object => arg }) { |result, object| result == false } - result = nil - callbacks_for(method).each do |callback| - result = callback.call(self, arg) - return false if result == false + if result != false && respond_to_without_attributes?(method) + result = send(method) + end + + result end - return result + def run_callbacks(kind, options = {}, &block) + options.reverse_merge!( :object => self ) + self.class.send("#{kind}_callback_chain").run(options[:object], options, &block) + end + else + # Rails 2.0 + def callback_with_args(method, arg = self) + notify(method) + + result = nil + callbacks_for(method).each do |callback| + result = callback.call(self, arg) + return false if result == false + end + result + end end - + # Removes the thumbnails for the attachment, if it has any def destroy_thumbnails self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?