PageRenderTime 936ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/redmine/plugin.rb

https://bitbucket.org/eimajenthat/redmine
Ruby | 476 lines | 259 code | 51 blank | 166 comment | 18 complexity | cf72830850d639263592533bc4aa2729 MD5 | raw file
Possible License(s): GPL-2.0
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. module Redmine #:nodoc:
  18. class PluginNotFound < StandardError; end
  19. class PluginRequirementError < StandardError; end
  20. # Base class for Redmine plugins.
  21. # Plugins are registered using the <tt>register</tt> class method that acts as the public constructor.
  22. #
  23. # Redmine::Plugin.register :example do
  24. # name 'Example plugin'
  25. # author 'John Smith'
  26. # description 'This is an example plugin for Redmine'
  27. # version '0.0.1'
  28. # settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
  29. # end
  30. #
  31. # === Plugin attributes
  32. #
  33. # +settings+ is an optional attribute that let the plugin be configurable.
  34. # It must be a hash with the following keys:
  35. # * <tt>:default</tt>: default value for the plugin settings
  36. # * <tt>:partial</tt>: path of the configuration partial view, relative to the plugin <tt>app/views</tt> directory
  37. # Example:
  38. # settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
  39. # In this example, the settings partial will be found here in the plugin directory: <tt>app/views/settings/_settings.rhtml</tt>.
  40. #
  41. # When rendered, the plugin settings value is available as the local variable +settings+
  42. class Plugin
  43. cattr_accessor :directory
  44. self.directory = File.join(Rails.root, 'plugins')
  45. cattr_accessor :public_directory
  46. self.public_directory = File.join(Rails.root, 'public', 'plugin_assets')
  47. @registered_plugins = {}
  48. class << self
  49. attr_reader :registered_plugins
  50. private :new
  51. def def_field(*names)
  52. class_eval do
  53. names.each do |name|
  54. define_method(name) do |*args|
  55. args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args)
  56. end
  57. end
  58. end
  59. end
  60. end
  61. def_field :name, :description, :url, :author, :author_url, :version, :settings
  62. attr_reader :id
  63. # Plugin constructor
  64. def self.register(id, &block)
  65. p = new(id)
  66. p.instance_eval(&block)
  67. # Set a default name if it was not provided during registration
  68. p.name(id.to_s.humanize) if p.name.nil?
  69. # Adds plugin locales if any
  70. # YAML translation files should be found under <plugin>/config/locales/
  71. ::I18n.load_path += Dir.glob(File.join(p.directory, 'config', 'locales', '*.yml'))
  72. # Prepends the app/views directory of the plugin to the view path
  73. view_path = File.join(p.directory, 'app', 'views')
  74. if File.directory?(view_path)
  75. ActionController::Base.prepend_view_path(view_path)
  76. ActionMailer::Base.prepend_view_path(view_path)
  77. end
  78. # Adds the app/{controllers,helpers,models} directories of the plugin to the autoload path
  79. Dir.glob File.expand_path(File.join(p.directory, 'app', '{controllers,helpers,models}')) do |dir|
  80. ActiveSupport::Dependencies.autoload_paths += [dir]
  81. end
  82. registered_plugins[id] = p
  83. end
  84. # Returns an array of all registered plugins
  85. def self.all
  86. registered_plugins.values.sort
  87. end
  88. # Finds a plugin by its id
  89. # Returns a PluginNotFound exception if the plugin doesn't exist
  90. def self.find(id)
  91. registered_plugins[id.to_sym] || raise(PluginNotFound)
  92. end
  93. # Clears the registered plugins hash
  94. # It doesn't unload installed plugins
  95. def self.clear
  96. @registered_plugins = {}
  97. end
  98. # Checks if a plugin is installed
  99. #
  100. # @param [String] id name of the plugin
  101. def self.installed?(id)
  102. registered_plugins[id.to_sym].present?
  103. end
  104. def self.load
  105. Dir.glob(File.join(self.directory, '*')).sort.each do |directory|
  106. if File.directory?(directory)
  107. lib = File.join(directory, "lib")
  108. if File.directory?(lib)
  109. $:.unshift lib
  110. ActiveSupport::Dependencies.autoload_paths += [lib]
  111. end
  112. initializer = File.join(directory, "init.rb")
  113. if File.file?(initializer)
  114. require initializer
  115. end
  116. end
  117. end
  118. end
  119. def initialize(id)
  120. @id = id.to_sym
  121. end
  122. def directory
  123. File.join(self.class.directory, id.to_s)
  124. end
  125. def public_directory
  126. File.join(self.class.public_directory, id.to_s)
  127. end
  128. def to_param
  129. id
  130. end
  131. def assets_directory
  132. File.join(directory, 'assets')
  133. end
  134. def <=>(plugin)
  135. self.id.to_s <=> plugin.id.to_s
  136. end
  137. # Sets a requirement on Redmine version
  138. # Raises a PluginRequirementError exception if the requirement is not met
  139. #
  140. # Examples
  141. # # Requires Redmine 0.7.3 or higher
  142. # requires_redmine :version_or_higher => '0.7.3'
  143. # requires_redmine '0.7.3'
  144. #
  145. # # Requires Redmine 0.7.x or higher
  146. # requires_redmine '0.7'
  147. #
  148. # # Requires a specific Redmine version
  149. # requires_redmine :version => '0.7.3' # 0.7.3 only
  150. # requires_redmine :version => '0.7' # 0.7.x
  151. # requires_redmine :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  152. #
  153. # # Requires a Redmine version within a range
  154. # requires_redmine :version => '0.7.3'..'0.9.1' # >= 0.7.3 and <= 0.9.1
  155. # requires_redmine :version => '0.7'..'0.9' # >= 0.7.x and <= 0.9.x
  156. def requires_redmine(arg)
  157. arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
  158. arg.assert_valid_keys(:version, :version_or_higher)
  159. current = Redmine::VERSION.to_a
  160. arg.each do |k, req|
  161. case k
  162. when :version_or_higher
  163. raise ArgumentError.new(":version_or_higher accepts a version string only") unless req.is_a?(String)
  164. unless compare_versions(req, current) <= 0
  165. raise PluginRequirementError.new("#{id} plugin requires Redmine #{req} or higher but current is #{current.join('.')}")
  166. end
  167. when :version
  168. req = [req] if req.is_a?(String)
  169. if req.is_a?(Array)
  170. unless req.detect {|ver| compare_versions(ver, current) == 0}
  171. raise PluginRequirementError.new("#{id} plugin requires one the following Redmine versions: #{req.join(', ')} but current is #{current.join('.')}")
  172. end
  173. elsif req.is_a?(Range)
  174. unless compare_versions(req.first, current) <= 0 && compare_versions(req.last, current) >= 0
  175. raise PluginRequirementError.new("#{id} plugin requires a Redmine version between #{req.first} and #{req.last} but current is #{current.join('.')}")
  176. end
  177. else
  178. raise ArgumentError.new(":version option accepts a version string, an array or a range of versions")
  179. end
  180. end
  181. end
  182. true
  183. end
  184. def compare_versions(requirement, current)
  185. requirement = requirement.split('.').collect(&:to_i)
  186. requirement <=> current.slice(0, requirement.size)
  187. end
  188. private :compare_versions
  189. # Sets a requirement on a Redmine plugin version
  190. # Raises a PluginRequirementError exception if the requirement is not met
  191. #
  192. # Examples
  193. # # Requires a plugin named :foo version 0.7.3 or higher
  194. # requires_redmine_plugin :foo, :version_or_higher => '0.7.3'
  195. # requires_redmine_plugin :foo, '0.7.3'
  196. #
  197. # # Requires a specific version of a Redmine plugin
  198. # requires_redmine_plugin :foo, :version => '0.7.3' # 0.7.3 only
  199. # requires_redmine_plugin :foo, :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  200. def requires_redmine_plugin(plugin_name, arg)
  201. arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
  202. arg.assert_valid_keys(:version, :version_or_higher)
  203. plugin = Plugin.find(plugin_name)
  204. current = plugin.version.split('.').collect(&:to_i)
  205. arg.each do |k, v|
  206. v = [] << v unless v.is_a?(Array)
  207. versions = v.collect {|s| s.split('.').collect(&:to_i)}
  208. case k
  209. when :version_or_higher
  210. raise ArgumentError.new("wrong number of versions (#{versions.size} for 1)") unless versions.size == 1
  211. unless (current <=> versions.first) >= 0
  212. raise PluginRequirementError.new("#{id} plugin requires the #{plugin_name} plugin #{v} or higher but current is #{current.join('.')}")
  213. end
  214. when :version
  215. unless versions.include?(current.slice(0,3))
  216. raise PluginRequirementError.new("#{id} plugin requires one the following versions of #{plugin_name}: #{v.join(', ')} but current is #{current.join('.')}")
  217. end
  218. end
  219. end
  220. true
  221. end
  222. # Adds an item to the given +menu+.
  223. # The +id+ parameter (equals to the project id) is automatically added to the url.
  224. # menu :project_menu, :plugin_example, { :controller => 'example', :action => 'say_hello' }, :caption => 'Sample'
  225. #
  226. # +name+ parameter can be: :top_menu, :account_menu, :application_menu or :project_menu
  227. #
  228. def menu(menu, item, url, options={})
  229. Redmine::MenuManager.map(menu).push(item, url, options)
  230. end
  231. alias :add_menu_item :menu
  232. # Removes +item+ from the given +menu+.
  233. def delete_menu_item(menu, item)
  234. Redmine::MenuManager.map(menu).delete(item)
  235. end
  236. # Defines a permission called +name+ for the given +actions+.
  237. #
  238. # The +actions+ argument is a hash with controllers as keys and actions as values (a single value or an array):
  239. # permission :destroy_contacts, { :contacts => :destroy }
  240. # permission :view_contacts, { :contacts => [:index, :show] }
  241. #
  242. # The +options+ argument is a hash that accept the following keys:
  243. # * :public => the permission is public if set to true (implicitly given to any user)
  244. # * :require => can be set to one of the following values to restrict users the permission can be given to: :loggedin, :member
  245. # * :read => set it to true so that the permission is still granted on closed projects
  246. #
  247. # Examples
  248. # # A permission that is implicitly given to any user
  249. # # This permission won't appear on the Roles & Permissions setup screen
  250. # permission :say_hello, { :example => :say_hello }, :public => true, :read => true
  251. #
  252. # # A permission that can be given to any user
  253. # permission :say_hello, { :example => :say_hello }
  254. #
  255. # # A permission that can be given to registered users only
  256. # permission :say_hello, { :example => :say_hello }, :require => :loggedin
  257. #
  258. # # A permission that can be given to project members only
  259. # permission :say_hello, { :example => :say_hello }, :require => :member
  260. def permission(name, actions, options = {})
  261. if @project_module
  262. Redmine::AccessControl.map {|map| map.project_module(@project_module) {|map|map.permission(name, actions, options)}}
  263. else
  264. Redmine::AccessControl.map {|map| map.permission(name, actions, options)}
  265. end
  266. end
  267. # Defines a project module, that can be enabled/disabled for each project.
  268. # Permissions defined inside +block+ will be bind to the module.
  269. #
  270. # project_module :things do
  271. # permission :view_contacts, { :contacts => [:list, :show] }, :public => true
  272. # permission :destroy_contacts, { :contacts => :destroy }
  273. # end
  274. def project_module(name, &block)
  275. @project_module = name
  276. self.instance_eval(&block)
  277. @project_module = nil
  278. end
  279. # Registers an activity provider.
  280. #
  281. # Options:
  282. # * <tt>:class_name</tt> - one or more model(s) that provide these events (inferred from event_type by default)
  283. # * <tt>:default</tt> - setting this option to false will make the events not displayed by default
  284. #
  285. # A model can provide several activity event types.
  286. #
  287. # Examples:
  288. # register :news
  289. # register :scrums, :class_name => 'Meeting'
  290. # register :issues, :class_name => ['Issue', 'Journal']
  291. #
  292. # Retrieving events:
  293. # Associated model(s) must implement the find_events class method.
  294. # ActiveRecord models can use acts_as_activity_provider as a way to implement this class method.
  295. #
  296. # The following call should return all the scrum events visible by current user that occured in the 5 last days:
  297. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today)
  298. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today, :project => foo) # events for project foo only
  299. #
  300. # Note that :view_scrums permission is required to view these events in the activity view.
  301. def activity_provider(*args)
  302. Redmine::Activity.register(*args)
  303. end
  304. # Registers a wiki formatter.
  305. #
  306. # Parameters:
  307. # * +name+ - human-readable name
  308. # * +formatter+ - formatter class, which should have an instance method +to_html+
  309. # * +helper+ - helper module, which will be included by wiki pages
  310. def wiki_format_provider(name, formatter, helper)
  311. Redmine::WikiFormatting.register(name, formatter, helper)
  312. end
  313. # Returns +true+ if the plugin can be configured.
  314. def configurable?
  315. settings && settings.is_a?(Hash) && !settings[:partial].blank?
  316. end
  317. def mirror_assets
  318. source = assets_directory
  319. destination = public_directory
  320. return unless File.directory?(source)
  321. source_files = Dir[source + "/**/*"]
  322. source_dirs = source_files.select { |d| File.directory?(d) }
  323. source_files -= source_dirs
  324. unless source_files.empty?
  325. base_target_dir = File.join(destination, File.dirname(source_files.first).gsub(source, ''))
  326. begin
  327. FileUtils.mkdir_p(base_target_dir)
  328. rescue Exception => e
  329. raise "Could not create directory #{base_target_dir}: " + e.message
  330. end
  331. end
  332. source_dirs.each do |dir|
  333. # strip down these paths so we have simple, relative paths we can
  334. # add to the destination
  335. target_dir = File.join(destination, dir.gsub(source, ''))
  336. begin
  337. FileUtils.mkdir_p(target_dir)
  338. rescue Exception => e
  339. raise "Could not create directory #{target_dir}: " + e.message
  340. end
  341. end
  342. source_files.each do |file|
  343. begin
  344. target = File.join(destination, file.gsub(source, ''))
  345. unless File.exist?(target) && FileUtils.identical?(file, target)
  346. FileUtils.cp(file, target)
  347. end
  348. rescue Exception => e
  349. raise "Could not copy #{file} to #{target}: " + e.message
  350. end
  351. end
  352. end
  353. # Mirrors assets from one or all plugins to public/plugin_assets
  354. def self.mirror_assets(name=nil)
  355. if name.present?
  356. find(name).mirror_assets
  357. else
  358. all.each do |plugin|
  359. plugin.mirror_assets
  360. end
  361. end
  362. end
  363. # The directory containing this plugin's migrations (<tt>plugin/db/migrate</tt>)
  364. def migration_directory
  365. File.join(Rails.root, 'plugins', id.to_s, 'db', 'migrate')
  366. end
  367. # Returns the version number of the latest migration for this plugin. Returns
  368. # nil if this plugin has no migrations.
  369. def latest_migration
  370. migrations.last
  371. end
  372. # Returns the version numbers of all migrations for this plugin.
  373. def migrations
  374. migrations = Dir[migration_directory+"/*.rb"]
  375. migrations.map { |p| File.basename(p).match(/0*(\d+)\_/)[1].to_i }.sort
  376. end
  377. # Migrate this plugin to the given version
  378. def migrate(version = nil)
  379. puts "Migrating #{id} (#{name})..."
  380. Redmine::Plugin::Migrator.migrate_plugin(self, version)
  381. end
  382. # Migrates all plugins or a single plugin to a given version
  383. # Exemples:
  384. # Plugin.migrate
  385. # Plugin.migrate('sample_plugin')
  386. # Plugin.migrate('sample_plugin', 1)
  387. #
  388. def self.migrate(name=nil, version=nil)
  389. if name.present?
  390. find(name).migrate(version)
  391. else
  392. all.each do |plugin|
  393. plugin.migrate
  394. end
  395. end
  396. end
  397. class Migrator < ActiveRecord::Migrator
  398. # We need to be able to set the 'current' plugin being migrated.
  399. cattr_accessor :current_plugin
  400. class << self
  401. # Runs the migrations from a plugin, up (or down) to the version given
  402. def migrate_plugin(plugin, version)
  403. self.current_plugin = plugin
  404. return if current_version(plugin) == version
  405. migrate(plugin.migration_directory, version)
  406. end
  407. def current_version(plugin=current_plugin)
  408. # Delete migrations that don't match .. to_i will work because the number comes first
  409. ::ActiveRecord::Base.connection.select_values(
  410. "SELECT version FROM #{schema_migrations_table_name}"
  411. ).delete_if{ |v| v.match(/-#{plugin.id}/) == nil }.map(&:to_i).max || 0
  412. end
  413. end
  414. def migrated
  415. sm_table = self.class.schema_migrations_table_name
  416. ::ActiveRecord::Base.connection.select_values(
  417. "SELECT version FROM #{sm_table}"
  418. ).delete_if{ |v| v.match(/-#{current_plugin.id}/) == nil }.map(&:to_i).sort
  419. end
  420. def record_version_state_after_migrating(version)
  421. super(version.to_s + "-" + current_plugin.id.to_s)
  422. end
  423. end
  424. end
  425. end