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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2023 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 public 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 asset_prefix
  161. File.join(self.class.public_directory.basename, id.to_s)
  162. end
  163. def asset_paths
  164. if path.has_assets_dir?
  165. base_dir = Pathname.new(path.assets_dir)
  166. paths = base_dir.children.filter_map{|child| child if child.directory? }
  167. Redmine::AssetPath.new(base_dir, paths, asset_prefix)
  168. end
  169. end
  170. def <=>(plugin)
  171. return nil unless plugin.is_a?(Plugin)
  172. self.id.to_s <=> plugin.id.to_s
  173. end
  174. # Sets a requirement on Redmine version
  175. # Raises a PluginRequirementError exception if the requirement is not met
  176. #
  177. # Examples
  178. # # Requires Redmine 0.7.3 or higher
  179. # requires_redmine :version_or_higher => '0.7.3'
  180. # requires_redmine '0.7.3'
  181. #
  182. # # Requires Redmine 0.7.x or higher
  183. # requires_redmine '0.7'
  184. #
  185. # # Requires a specific Redmine version
  186. # requires_redmine :version => '0.7.3' # 0.7.3 only
  187. # requires_redmine :version => '0.7' # 0.7.x
  188. # requires_redmine :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  189. #
  190. # # Requires a Redmine version within a range
  191. # requires_redmine :version => '0.7.3'..'0.9.1' # >= 0.7.3 and <= 0.9.1
  192. # requires_redmine :version => '0.7'..'0.9' # >= 0.7.x and <= 0.9.x
  193. def requires_redmine(arg)
  194. arg = {:version_or_higher => arg} unless arg.is_a?(Hash)
  195. arg.assert_valid_keys(:version, :version_or_higher)
  196. current = Redmine::VERSION.to_a
  197. arg.each do |k, req|
  198. case k
  199. when :version_or_higher
  200. unless req.is_a?(String)
  201. raise ArgumentError.new(":version_or_higher accepts a version string only")
  202. end
  203. unless compare_versions(req, current) <= 0
  204. raise PluginRequirementError.new(
  205. "#{id} plugin requires Redmine #{req} or higher " \
  206. "but current is #{current.join('.')}"
  207. )
  208. end
  209. when :version
  210. req = [req] if req.is_a?(String)
  211. if req.is_a?(Array)
  212. unless req.detect {|ver| compare_versions(ver, current) == 0}
  213. raise PluginRequirementError.new(
  214. "#{id} plugin requires one the following Redmine versions: " \
  215. "#{req.join(', ')} but current is #{current.join('.')}"
  216. )
  217. end
  218. elsif req.is_a?(Range)
  219. unless compare_versions(req.first, current) <= 0 && compare_versions(req.last, current) >= 0
  220. raise PluginRequirementError.new(
  221. "#{id} plugin requires a Redmine version between #{req.first} " \
  222. "and #{req.last} but current is #{current.join('.')}"
  223. )
  224. end
  225. else
  226. raise ArgumentError.new(":version option accepts a version string, an array or a range of versions")
  227. end
  228. end
  229. end
  230. true
  231. end
  232. def compare_versions(requirement, current)
  233. requirement = requirement.split('.').collect(&:to_i)
  234. requirement <=> current.slice(0, requirement.size)
  235. end
  236. private :compare_versions
  237. # Sets a requirement on a Redmine plugin version
  238. # Raises a PluginRequirementError exception if the requirement is not met
  239. #
  240. # Examples
  241. # # Requires a plugin named :foo version 0.7.3 or higher
  242. # requires_redmine_plugin :foo, :version_or_higher => '0.7.3'
  243. # requires_redmine_plugin :foo, '0.7.3'
  244. #
  245. # # Requires a specific version of a Redmine plugin
  246. # requires_redmine_plugin :foo, :version => '0.7.3' # 0.7.3 only
  247. # requires_redmine_plugin :foo, :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  248. def requires_redmine_plugin(plugin_name, arg)
  249. arg = {:version_or_higher => arg} unless arg.is_a?(Hash)
  250. arg.assert_valid_keys(:version, :version_or_higher)
  251. begin
  252. plugin = Plugin.find(plugin_name)
  253. rescue PluginNotFound
  254. raise PluginRequirementError.new("#{id} plugin requires the #{plugin_name} plugin")
  255. end
  256. current = plugin.version.split('.').collect(&:to_i)
  257. arg.each do |k, v|
  258. v = [] << v unless v.is_a?(Array)
  259. versions = v.collect {|s| s.split('.').collect(&:to_i)}
  260. case k
  261. when :version_or_higher
  262. unless versions.size == 1
  263. raise ArgumentError.new("wrong number of versions (#{versions.size} for 1)")
  264. end
  265. unless (current <=> versions.first) >= 0
  266. raise PluginRequirementError.new(
  267. "#{id} plugin requires the #{plugin_name} plugin #{v} or higher " \
  268. "but current is #{current.join('.')}"
  269. )
  270. end
  271. when :version
  272. unless versions.include?(current.slice(0, 3))
  273. raise PluginRequirementError.new(
  274. "#{id} plugin requires one the following versions of #{plugin_name}: " \
  275. "#{v.join(', ')} but current is #{current.join('.')}"
  276. )
  277. end
  278. end
  279. end
  280. true
  281. end
  282. # Adds an item to the given +menu+.
  283. # The +id+ parameter (equals to the project id) is automatically added to the url.
  284. # menu :project_menu, :plugin_example, { :controller => 'example', :action => 'say_hello' }, :caption => 'Sample'
  285. #
  286. # +name+ parameter can be: :top_menu, :account_menu, :application_menu or :project_menu
  287. #
  288. def menu(menu, item, url, options={})
  289. Redmine::MenuManager.map(menu).push(item, url, options)
  290. end
  291. alias :add_menu_item :menu
  292. # Removes +item+ from the given +menu+.
  293. def delete_menu_item(menu, item)
  294. Redmine::MenuManager.map(menu).delete(item)
  295. end
  296. # Defines a permission called +name+ for the given +actions+.
  297. #
  298. # The +actions+ argument is a hash with controllers as keys and actions as values (a single value or an array):
  299. # permission :destroy_contacts, { :contacts => :destroy }
  300. # permission :view_contacts, { :contacts => [:index, :show] }
  301. #
  302. # The +options+ argument is a hash that accept the following keys:
  303. # * :public => the permission is public if set to true (implicitly given to any user)
  304. # * :require => can be set to one of the following values to restrict users the permission can be given to: :loggedin, :member
  305. # * :read => set it to true so that the permission is still granted on closed projects
  306. #
  307. # Examples
  308. # # A permission that is implicitly given to any user
  309. # # This permission won't appear on the Roles & Permissions setup screen
  310. # permission :say_hello, { :example => :say_hello }, :public => true, :read => true
  311. #
  312. # # A permission that can be given to any user
  313. # permission :say_hello, { :example => :say_hello }
  314. #
  315. # # A permission that can be given to registered users only
  316. # permission :say_hello, { :example => :say_hello }, :require => :loggedin
  317. #
  318. # # A permission that can be given to project members only
  319. # permission :say_hello, { :example => :say_hello }, :require => :member
  320. def permission(name, actions, options = {})
  321. if @project_module
  322. Redmine::AccessControl.map do |map|
  323. map.project_module(@project_module) do |map|
  324. map.permission(name, actions, options)
  325. end
  326. end
  327. else
  328. Redmine::AccessControl.map {|map| map.permission(name, actions, options)}
  329. end
  330. end
  331. # Defines a project module, that can be enabled/disabled for each project.
  332. # Permissions defined inside +block+ will be bind to the module.
  333. #
  334. # project_module :things do
  335. # permission :view_contacts, { :contacts => [:list, :show] }, :public => true
  336. # permission :destroy_contacts, { :contacts => :destroy }
  337. # end
  338. def project_module(name, &block)
  339. @project_module = name
  340. self.instance_eval(&block)
  341. @project_module = nil
  342. end
  343. # Registers an activity provider.
  344. #
  345. # Options:
  346. # * <tt>:class_name</tt> - one or more model(s) that provide these events (inferred from event_type by default)
  347. # * <tt>:default</tt> - setting this option to false will make the events not displayed by default
  348. #
  349. # A model can provide several activity event types.
  350. #
  351. # Examples:
  352. # register :news
  353. # register :scrums, :class_name => 'Meeting'
  354. # register :issues, :class_name => ['Issue', 'Journal']
  355. #
  356. # Retrieving events:
  357. # Associated model(s) must implement the find_events class method.
  358. # ActiveRecord models can use acts_as_activity_provider as a way to implement this class method.
  359. #
  360. # The following call should return all the scrum events visible by current user that occurred in the 5 last days:
  361. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today)
  362. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today, :project => foo) # events for project foo only
  363. #
  364. # Note that :view_scrums permission is required to view these events in the activity view.
  365. def activity_provider(*args)
  366. Redmine::Activity.register(*args)
  367. end
  368. # Registers a wiki formatter.
  369. #
  370. # Parameters:
  371. # * +name+ - formatter name
  372. # * +formatter+ - formatter class, which should have an instance method +to_html+
  373. # * +helper+ - helper module, which will be included by wiki pages (optional)
  374. # * +html_parser+ class reponsible for converting HTML to wiki text (optional)
  375. # * +options+ - a Hash of options (optional)
  376. # * :label - label for the formatter displayed in application settings
  377. #
  378. # Examples:
  379. # wiki_format_provider(:custom_formatter, CustomFormatter, :label => "My custom formatter")
  380. #
  381. def wiki_format_provider(name, *args)
  382. Redmine::WikiFormatting.register(name, *args)
  383. end
  384. # Returns +true+ if the plugin can be configured.
  385. def configurable?
  386. settings && settings.is_a?(Hash) && settings[:partial].present?
  387. end
  388. # The directory containing this plugin's migrations (<tt>plugin/db/migrate</tt>)
  389. def migration_directory
  390. File.join(directory, 'db', 'migrate')
  391. end
  392. # Returns the version number of the latest migration for this plugin. Returns
  393. # nil if this plugin has no migrations.
  394. def latest_migration
  395. migrations.last
  396. end
  397. # Returns the version numbers of all migrations for this plugin.
  398. def migrations
  399. migrations = Dir[migration_directory+"/*.rb"]
  400. migrations.map {|p| File.basename(p).match(/0*(\d+)\_/)[1].to_i}.sort
  401. end
  402. # Migrate this plugin to the given version
  403. def migrate(version = nil)
  404. Redmine::Plugin::Migrator.migrate_plugin(self, version)
  405. end
  406. # Migrates all plugins or a single plugin to a given version
  407. # Exemples:
  408. # Plugin.migrate
  409. # Plugin.migrate('sample_plugin')
  410. # Plugin.migrate('sample_plugin', 1)
  411. #
  412. def self.migrate(name=nil, version=nil)
  413. if name.present?
  414. find(name).migrate(version)
  415. else
  416. all.each do |plugin|
  417. plugin.migrate
  418. end
  419. end
  420. end
  421. class MigrationContext < ActiveRecord::MigrationContext
  422. def up(target_version = nil)
  423. selected_migrations =
  424. if block_given?
  425. migrations.select {|m| yield m}
  426. else
  427. migrations
  428. end
  429. Migrator.new(:up, selected_migrations, schema_migration, internal_metadata, target_version).migrate
  430. end
  431. def down(target_version = nil)
  432. selected_migrations =
  433. if block_given?
  434. migrations.select {|m| yield m}
  435. else
  436. migrations
  437. end
  438. Migrator.new(:down, selected_migrations, schema_migration, internal_metadata, target_version).migrate
  439. end
  440. def run(direction, target_version)
  441. Migrator.new(direction, migrations, schema_migration, internal_metadata, target_version).run
  442. end
  443. def open
  444. Migrator.new(:up, migrations, schema_migration, internal_metadata)
  445. end
  446. def current_version
  447. Migrator.current_version
  448. end
  449. end
  450. class Migrator < ActiveRecord::Migrator
  451. # We need to be able to set the 'current' plugin being migrated.
  452. cattr_accessor :current_plugin
  453. class << self
  454. # Runs the migrations from a plugin, up (or down) to the version given
  455. def migrate_plugin(plugin, version)
  456. self.current_plugin = plugin
  457. return if current_version(plugin) == version
  458. MigrationContext.new(plugin.migration_directory, ::ActiveRecord::Base.connection.schema_migration).migrate(version)
  459. end
  460. def get_all_versions(plugin = current_plugin)
  461. # Delete migrations that don't match .. to_i will work because the number comes first
  462. @all_versions ||= {}
  463. @all_versions[plugin.id.to_s] ||= begin
  464. sm_table = ::ActiveRecord::Base.connection.schema_migration.table_name
  465. migration_versions = ActiveRecord::Base.connection.select_values("SELECT version FROM #{sm_table}")
  466. versions_by_plugins = migration_versions.group_by {|version| version.match(/-(.*)$/).try(:[], 1)}
  467. @all_versions = versions_by_plugins.transform_values! {|versions| versions.map!(&:to_i).sort!}
  468. @all_versions[plugin.id.to_s] || []
  469. end
  470. end
  471. def current_version(plugin = current_plugin)
  472. get_all_versions(plugin).last || 0
  473. end
  474. end
  475. def load_migrated
  476. @migrated_versions = Set.new(self.class.get_all_versions(current_plugin))
  477. end
  478. def record_version_state_after_migrating(version)
  479. super(version.to_s + "-" + current_plugin.id.to_s)
  480. end
  481. end
  482. end
  483. end