You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

plugin.rb 19KB

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