Chris@909: # Redmine - project management software
Chris@1115: # Copyright (C) 2006-2012 Jean-Philippe Lang
Chris@0: #
Chris@0: # This program is free software; you can redistribute it and/or
Chris@0: # modify it under the terms of the GNU General Public License
Chris@0: # as published by the Free Software Foundation; either version 2
Chris@0: # of the License, or (at your option) any later version.
Chris@909: #
Chris@0: # This program is distributed in the hope that it will be useful,
Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0: # GNU General Public License for more details.
Chris@909: #
Chris@0: # You should have received a copy of the GNU General Public License
Chris@0: # along with this program; if not, write to the Free Software
Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0:
Chris@0: module Redmine #:nodoc:
Chris@0:
Chris@0: class PluginNotFound < StandardError; end
Chris@0: class PluginRequirementError < StandardError; end
Chris@909:
Chris@0: # Base class for Redmine plugins.
Chris@0: # Plugins are registered using the register class method that acts as the public constructor.
Chris@909: #
Chris@0: # Redmine::Plugin.register :example do
Chris@0: # name 'Example plugin'
Chris@0: # author 'John Smith'
Chris@0: # description 'This is an example plugin for Redmine'
Chris@0: # version '0.0.1'
Chris@0: # settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
Chris@0: # end
Chris@909: #
Chris@0: # === Plugin attributes
Chris@909: #
Chris@0: # +settings+ is an optional attribute that let the plugin be configurable.
Chris@0: # It must be a hash with the following keys:
Chris@0: # * :default: default value for the plugin settings
Chris@0: # * :partial: path of the configuration partial view, relative to the plugin app/views directory
Chris@0: # Example:
Chris@0: # settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
Chris@0: # In this example, the settings partial will be found here in the plugin directory: app/views/settings/_settings.rhtml.
Chris@909: #
Chris@0: # When rendered, the plugin settings value is available as the local variable +settings+
Chris@0: class Plugin
Chris@1115: cattr_accessor :directory
Chris@1115: self.directory = File.join(Rails.root, 'plugins')
Chris@1115:
Chris@1115: cattr_accessor :public_directory
Chris@1115: self.public_directory = File.join(Rails.root, 'public', 'plugin_assets')
Chris@1115:
Chris@0: @registered_plugins = {}
Chris@0: class << self
Chris@0: attr_reader :registered_plugins
Chris@0: private :new
Chris@0:
Chris@0: def def_field(*names)
Chris@909: class_eval do
Chris@0: names.each do |name|
Chris@909: define_method(name) do |*args|
Chris@0: args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args)
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: def_field :name, :description, :url, :author, :author_url, :version, :settings
Chris@0: attr_reader :id
Chris@909:
Chris@0: # Plugin constructor
Chris@0: def self.register(id, &block)
Chris@0: p = new(id)
Chris@0: p.instance_eval(&block)
Chris@0: # Set a default name if it was not provided during registration
Chris@0: p.name(id.to_s.humanize) if p.name.nil?
Chris@1115:
Chris@0: # Adds plugin locales if any
Chris@0: # YAML translation files should be found under /config/locales/
Chris@1115: ::I18n.load_path += Dir.glob(File.join(p.directory, 'config', 'locales', '*.yml'))
Chris@1115:
Chris@1115: # Prepends the app/views directory of the plugin to the view path
Chris@1115: view_path = File.join(p.directory, 'app', 'views')
Chris@1115: if File.directory?(view_path)
Chris@1115: ActionController::Base.prepend_view_path(view_path)
Chris@1115: ActionMailer::Base.prepend_view_path(view_path)
Chris@1115: end
Chris@1115:
Chris@1115: # Adds the app/{controllers,helpers,models} directories of the plugin to the autoload path
Chris@1115: Dir.glob File.expand_path(File.join(p.directory, 'app', '{controllers,helpers,models}')) do |dir|
Chris@1115: ActiveSupport::Dependencies.autoload_paths += [dir]
Chris@1115: end
Chris@1115:
Chris@0: registered_plugins[id] = p
Chris@0: end
Chris@909:
Chris@909: # Returns an array of all registered plugins
Chris@0: def self.all
Chris@0: registered_plugins.values.sort
Chris@0: end
Chris@909:
Chris@0: # Finds a plugin by its id
Chris@0: # Returns a PluginNotFound exception if the plugin doesn't exist
Chris@0: def self.find(id)
Chris@0: registered_plugins[id.to_sym] || raise(PluginNotFound)
Chris@0: end
Chris@909:
Chris@0: # Clears the registered plugins hash
Chris@0: # It doesn't unload installed plugins
Chris@0: def self.clear
Chris@0: @registered_plugins = {}
Chris@0: end
chris@37:
chris@37: # Checks if a plugin is installed
chris@37: #
chris@37: # @param [String] id name of the plugin
chris@37: def self.installed?(id)
chris@37: registered_plugins[id.to_sym].present?
chris@37: end
Chris@909:
Chris@1115: def self.load
Chris@1115: Dir.glob(File.join(self.directory, '*')).sort.each do |directory|
Chris@1115: if File.directory?(directory)
Chris@1115: lib = File.join(directory, "lib")
Chris@1115: if File.directory?(lib)
Chris@1115: $:.unshift lib
Chris@1115: ActiveSupport::Dependencies.autoload_paths += [lib]
Chris@1115: end
Chris@1115: initializer = File.join(directory, "init.rb")
Chris@1115: if File.file?(initializer)
Chris@1115: require initializer
Chris@1115: end
Chris@1115: end
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@0: def initialize(id)
Chris@0: @id = id.to_sym
Chris@0: end
Chris@909:
Chris@1115: def directory
Chris@1115: File.join(self.class.directory, id.to_s)
Chris@1115: end
Chris@1115:
Chris@1115: def public_directory
Chris@1115: File.join(self.class.public_directory, id.to_s)
Chris@1115: end
Chris@1115:
Chris@1115: def assets_directory
Chris@1115: File.join(directory, 'assets')
Chris@1115: end
Chris@1115:
Chris@0: def <=>(plugin)
Chris@0: self.id.to_s <=> plugin.id.to_s
Chris@0: end
Chris@909:
Chris@0: # Sets a requirement on Redmine version
Chris@0: # Raises a PluginRequirementError exception if the requirement is not met
Chris@0: #
Chris@0: # Examples
Chris@0: # # Requires Redmine 0.7.3 or higher
Chris@0: # requires_redmine :version_or_higher => '0.7.3'
Chris@0: # requires_redmine '0.7.3'
Chris@0: #
Chris@1115: # # Requires Redmine 0.7.x or higher
Chris@1115: # requires_redmine '0.7'
Chris@1115: #
Chris@0: # # Requires a specific Redmine version
Chris@0: # requires_redmine :version => '0.7.3' # 0.7.3 only
Chris@1115: # requires_redmine :version => '0.7' # 0.7.x
Chris@0: # requires_redmine :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
Chris@1115: #
Chris@1115: # # Requires a Redmine version within a range
Chris@1115: # requires_redmine :version => '0.7.3'..'0.9.1' # >= 0.7.3 and <= 0.9.1
Chris@1115: # requires_redmine :version => '0.7'..'0.9' # >= 0.7.x and <= 0.9.x
Chris@0: def requires_redmine(arg)
Chris@0: arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
Chris@0: arg.assert_valid_keys(:version, :version_or_higher)
Chris@909:
Chris@0: current = Redmine::VERSION.to_a
Chris@1115: arg.each do |k, req|
Chris@0: case k
Chris@0: when :version_or_higher
Chris@1115: raise ArgumentError.new(":version_or_higher accepts a version string only") unless req.is_a?(String)
Chris@1115: unless compare_versions(req, current) <= 0
Chris@1115: raise PluginRequirementError.new("#{id} plugin requires Redmine #{req} or higher but current is #{current.join('.')}")
Chris@0: end
Chris@0: when :version
Chris@1115: req = [req] if req.is_a?(String)
Chris@1115: if req.is_a?(Array)
Chris@1115: unless req.detect {|ver| compare_versions(ver, current) == 0}
Chris@1115: raise PluginRequirementError.new("#{id} plugin requires one the following Redmine versions: #{req.join(', ')} but current is #{current.join('.')}")
Chris@1115: end
Chris@1115: elsif req.is_a?(Range)
Chris@1115: unless compare_versions(req.first, current) <= 0 && compare_versions(req.last, current) >= 0
Chris@1115: raise PluginRequirementError.new("#{id} plugin requires a Redmine version between #{req.first} and #{req.last} but current is #{current.join('.')}")
Chris@1115: end
Chris@1115: else
Chris@1115: raise ArgumentError.new(":version option accepts a version string, an array or a range of versions")
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: true
Chris@0: end
Chris@0:
Chris@1115: def compare_versions(requirement, current)
Chris@1115: requirement = requirement.split('.').collect(&:to_i)
Chris@1115: requirement <=> current.slice(0, requirement.size)
Chris@1115: end
Chris@1115: private :compare_versions
Chris@1115:
Chris@0: # Sets a requirement on a Redmine plugin version
Chris@0: # Raises a PluginRequirementError exception if the requirement is not met
Chris@0: #
Chris@0: # Examples
Chris@0: # # Requires a plugin named :foo version 0.7.3 or higher
Chris@0: # requires_redmine_plugin :foo, :version_or_higher => '0.7.3'
Chris@0: # requires_redmine_plugin :foo, '0.7.3'
Chris@0: #
Chris@0: # # Requires a specific version of a Redmine plugin
Chris@0: # requires_redmine_plugin :foo, :version => '0.7.3' # 0.7.3 only
Chris@0: # requires_redmine_plugin :foo, :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
Chris@0: def requires_redmine_plugin(plugin_name, arg)
Chris@0: arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
Chris@0: arg.assert_valid_keys(:version, :version_or_higher)
Chris@0:
Chris@0: plugin = Plugin.find(plugin_name)
Chris@0: current = plugin.version.split('.').collect(&:to_i)
Chris@0:
Chris@0: arg.each do |k, v|
Chris@0: v = [] << v unless v.is_a?(Array)
Chris@0: versions = v.collect {|s| s.split('.').collect(&:to_i)}
Chris@0: case k
Chris@0: when :version_or_higher
Chris@0: raise ArgumentError.new("wrong number of versions (#{versions.size} for 1)") unless versions.size == 1
Chris@0: unless (current <=> versions.first) >= 0
Chris@0: raise PluginRequirementError.new("#{id} plugin requires the #{plugin_name} plugin #{v} or higher but current is #{current.join('.')}")
Chris@0: end
Chris@0: when :version
Chris@0: unless versions.include?(current.slice(0,3))
Chris@0: raise PluginRequirementError.new("#{id} plugin requires one the following versions of #{plugin_name}: #{v.join(', ')} but current is #{current.join('.')}")
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: true
Chris@0: end
Chris@0:
Chris@0: # Adds an item to the given +menu+.
Chris@0: # The +id+ parameter (equals to the project id) is automatically added to the url.
Chris@0: # menu :project_menu, :plugin_example, { :controller => 'example', :action => 'say_hello' }, :caption => 'Sample'
Chris@909: #
Chris@0: # +name+ parameter can be: :top_menu, :account_menu, :application_menu or :project_menu
Chris@909: #
Chris@0: def menu(menu, item, url, options={})
Chris@0: Redmine::MenuManager.map(menu).push(item, url, options)
Chris@0: end
Chris@0: alias :add_menu_item :menu
Chris@909:
Chris@0: # Removes +item+ from the given +menu+.
Chris@0: def delete_menu_item(menu, item)
Chris@0: Redmine::MenuManager.map(menu).delete(item)
Chris@0: end
Chris@0:
Chris@0: # Defines a permission called +name+ for the given +actions+.
Chris@909: #
Chris@0: # The +actions+ argument is a hash with controllers as keys and actions as values (a single value or an array):
Chris@0: # permission :destroy_contacts, { :contacts => :destroy }
Chris@0: # permission :view_contacts, { :contacts => [:index, :show] }
Chris@909: #
Chris@1115: # The +options+ argument is a hash that accept the following keys:
Chris@1115: # * :public => the permission is public if set to true (implicitly given to any user)
Chris@1115: # * :require => can be set to one of the following values to restrict users the permission can be given to: :loggedin, :member
Chris@1115: # * :read => set it to true so that the permission is still granted on closed projects
Chris@909: #
Chris@0: # Examples
Chris@0: # # A permission that is implicitly given to any user
Chris@0: # # This permission won't appear on the Roles & Permissions setup screen
Chris@1115: # permission :say_hello, { :example => :say_hello }, :public => true, :read => true
Chris@909: #
Chris@0: # # A permission that can be given to any user
Chris@0: # permission :say_hello, { :example => :say_hello }
Chris@909: #
Chris@0: # # A permission that can be given to registered users only
Chris@0: # permission :say_hello, { :example => :say_hello }, :require => :loggedin
Chris@909: #
Chris@0: # # A permission that can be given to project members only
Chris@0: # permission :say_hello, { :example => :say_hello }, :require => :member
Chris@0: def permission(name, actions, options = {})
Chris@0: if @project_module
Chris@0: Redmine::AccessControl.map {|map| map.project_module(@project_module) {|map|map.permission(name, actions, options)}}
Chris@0: else
Chris@0: Redmine::AccessControl.map {|map| map.permission(name, actions, options)}
Chris@0: end
Chris@0: end
Chris@909:
Chris@0: # Defines a project module, that can be enabled/disabled for each project.
Chris@0: # Permissions defined inside +block+ will be bind to the module.
Chris@909: #
Chris@0: # project_module :things do
Chris@0: # permission :view_contacts, { :contacts => [:list, :show] }, :public => true
Chris@0: # permission :destroy_contacts, { :contacts => :destroy }
Chris@0: # end
Chris@0: def project_module(name, &block)
Chris@0: @project_module = name
Chris@0: self.instance_eval(&block)
Chris@0: @project_module = nil
Chris@0: end
Chris@909:
Chris@0: # Registers an activity provider.
Chris@0: #
Chris@0: # Options:
Chris@0: # * :class_name - one or more model(s) that provide these events (inferred from event_type by default)
Chris@0: # * :default - setting this option to false will make the events not displayed by default
Chris@909: #
Chris@0: # A model can provide several activity event types.
Chris@909: #
Chris@0: # Examples:
Chris@0: # register :news
Chris@0: # register :scrums, :class_name => 'Meeting'
Chris@0: # register :issues, :class_name => ['Issue', 'Journal']
Chris@909: #
Chris@0: # Retrieving events:
Chris@0: # Associated model(s) must implement the find_events class method.
Chris@0: # ActiveRecord models can use acts_as_activity_provider as a way to implement this class method.
Chris@909: #
Chris@909: # The following call should return all the scrum events visible by current user that occured in the 5 last days:
Chris@0: # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today)
Chris@0: # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today, :project => foo) # events for project foo only
Chris@909: #
Chris@0: # Note that :view_scrums permission is required to view these events in the activity view.
Chris@0: def activity_provider(*args)
Chris@0: Redmine::Activity.register(*args)
Chris@0: end
Chris@909:
Chris@0: # Registers a wiki formatter.
Chris@0: #
Chris@0: # Parameters:
Chris@0: # * +name+ - human-readable name
Chris@0: # * +formatter+ - formatter class, which should have an instance method +to_html+
Chris@0: # * +helper+ - helper module, which will be included by wiki pages
Chris@0: def wiki_format_provider(name, formatter, helper)
Chris@0: Redmine::WikiFormatting.register(name, formatter, helper)
Chris@0: end
Chris@0:
Chris@0: # Returns +true+ if the plugin can be configured.
Chris@0: def configurable?
Chris@0: settings && settings.is_a?(Hash) && !settings[:partial].blank?
Chris@0: end
Chris@1115:
Chris@1115: def mirror_assets
Chris@1115: source = assets_directory
Chris@1115: destination = public_directory
Chris@1115: return unless File.directory?(source)
Chris@1115:
Chris@1115: source_files = Dir[source + "/**/*"]
Chris@1115: source_dirs = source_files.select { |d| File.directory?(d) }
Chris@1115: source_files -= source_dirs
Chris@1115:
Chris@1115: unless source_files.empty?
Chris@1115: base_target_dir = File.join(destination, File.dirname(source_files.first).gsub(source, ''))
Chris@1115: begin
Chris@1115: FileUtils.mkdir_p(base_target_dir)
Chris@1115: rescue Exception => e
Chris@1115: raise "Could not create directory #{base_target_dir}: " + e.message
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: source_dirs.each do |dir|
Chris@1115: # strip down these paths so we have simple, relative paths we can
Chris@1115: # add to the destination
Chris@1115: target_dir = File.join(destination, dir.gsub(source, ''))
Chris@1115: begin
Chris@1115: FileUtils.mkdir_p(target_dir)
Chris@1115: rescue Exception => e
Chris@1115: raise "Could not create directory #{target_dir}: " + e.message
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: source_files.each do |file|
Chris@1115: begin
Chris@1115: target = File.join(destination, file.gsub(source, ''))
Chris@1115: unless File.exist?(target) && FileUtils.identical?(file, target)
Chris@1115: FileUtils.cp(file, target)
Chris@1115: end
Chris@1115: rescue Exception => e
Chris@1115: raise "Could not copy #{file} to #{target}: " + e.message
Chris@1115: end
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: # Mirrors assets from one or all plugins to public/plugin_assets
Chris@1115: def self.mirror_assets(name=nil)
Chris@1115: if name.present?
Chris@1115: find(name).mirror_assets
Chris@1115: else
Chris@1115: all.each do |plugin|
Chris@1115: plugin.mirror_assets
Chris@1115: end
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: # The directory containing this plugin's migrations (plugin/db/migrate)
Chris@1115: def migration_directory
Chris@1115: File.join(Rails.root, 'plugins', id.to_s, 'db', 'migrate')
Chris@1115: end
Chris@1115:
Chris@1115: # Returns the version number of the latest migration for this plugin. Returns
Chris@1115: # nil if this plugin has no migrations.
Chris@1115: def latest_migration
Chris@1115: migrations.last
Chris@1115: end
Chris@1115:
Chris@1115: # Returns the version numbers of all migrations for this plugin.
Chris@1115: def migrations
Chris@1115: migrations = Dir[migration_directory+"/*.rb"]
Chris@1115: migrations.map { |p| File.basename(p).match(/0*(\d+)\_/)[1].to_i }.sort
Chris@1115: end
Chris@1115:
Chris@1115: # Migrate this plugin to the given version
Chris@1115: def migrate(version = nil)
Chris@1115: puts "Migrating #{id} (#{name})..."
Chris@1115: Redmine::Plugin::Migrator.migrate_plugin(self, version)
Chris@1115: end
Chris@1115:
Chris@1115: # Migrates all plugins or a single plugin to a given version
Chris@1115: # Exemples:
Chris@1115: # Plugin.migrate
Chris@1115: # Plugin.migrate('sample_plugin')
Chris@1115: # Plugin.migrate('sample_plugin', 1)
Chris@1115: #
Chris@1115: def self.migrate(name=nil, version=nil)
Chris@1115: if name.present?
Chris@1115: find(name).migrate(version)
Chris@1115: else
Chris@1115: all.each do |plugin|
Chris@1115: plugin.migrate
Chris@1115: end
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: class Migrator < ActiveRecord::Migrator
Chris@1115: # We need to be able to set the 'current' plugin being migrated.
Chris@1115: cattr_accessor :current_plugin
Chris@1115:
Chris@1115: class << self
Chris@1115: # Runs the migrations from a plugin, up (or down) to the version given
Chris@1115: def migrate_plugin(plugin, version)
Chris@1115: self.current_plugin = plugin
Chris@1115: return if current_version(plugin) == version
Chris@1115: migrate(plugin.migration_directory, version)
Chris@1115: end
Chris@1115:
Chris@1115: def current_version(plugin=current_plugin)
Chris@1115: # Delete migrations that don't match .. to_i will work because the number comes first
Chris@1115: ::ActiveRecord::Base.connection.select_values(
Chris@1115: "SELECT version FROM #{schema_migrations_table_name}"
Chris@1115: ).delete_if{ |v| v.match(/-#{plugin.id}/) == nil }.map(&:to_i).max || 0
Chris@1115: end
Chris@1115: end
Chris@1115:
Chris@1115: def migrated
Chris@1115: sm_table = self.class.schema_migrations_table_name
Chris@1115: ::ActiveRecord::Base.connection.select_values(
Chris@1115: "SELECT version FROM #{sm_table}"
Chris@1115: ).delete_if{ |v| v.match(/-#{current_plugin.id}/) == nil }.map(&:to_i).sort
Chris@1115: end
Chris@1115:
Chris@1115: def record_version_state_after_migrating(version)
Chris@1115: super(version.to_s + "-" + current_plugin.id.to_s)
Chris@1115: end
Chris@1115: end
Chris@0: end
Chris@0: end