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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 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 = File.join(Rails.root, 'plugins')
  51. # Absolute path to the plublic directory where plugins assets are copied
  52. cattr_accessor :public_directory
  53. self.public_directory = File.join(Rails.root, 'public', 'plugin_assets')
  54. @registered_plugins = {}
  55. @used_partials = {}
  56. class << self
  57. attr_reader :registered_plugins
  58. private :new
  59. def def_field(*names)
  60. class_eval do
  61. names.each do |name|
  62. define_method(name) do |*args|
  63. args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args)
  64. end
  65. end
  66. end
  67. end
  68. end
  69. def_field :name, :description, :url, :author, :author_url, :version, :settings, :directory
  70. attr_reader :id
  71. # Plugin constructor: instanciates a new Redmine::Plugin with given +id+
  72. # and make it evaluate the given +block+
  73. #
  74. # Example
  75. # Redmine::Plugin.register :example do
  76. # name 'Example plugin'
  77. # author 'John Smith'
  78. # description 'This is an example plugin for Redmine'
  79. # version '0.0.1'
  80. # requires_redmine version_or_higher: '3.0.0'
  81. # end
  82. def self.register(id, &block)
  83. p = new(id)
  84. p.instance_eval(&block)
  85. # Set a default name if it was not provided during registration
  86. p.name(id.to_s.humanize) if p.name.nil?
  87. # Set a default directory if it was not provided during registration
  88. p.directory(File.join(self.directory, id.to_s)) if p.directory.nil?
  89. unless File.directory?(p.directory)
  90. raise PluginNotFound, "Plugin not found. The directory for plugin #{p.id} should be #{p.directory}."
  91. end
  92. # Adds plugin locales if any
  93. # YAML translation files should be found under <plugin>/config/locales/
  94. Rails.application.config.i18n.load_path += Dir.glob(File.join(p.directory, 'config', 'locales', '*.yml'))
  95. # Prepends the app/views directory of the plugin to the view path
  96. view_path = File.join(p.directory, 'app', 'views')
  97. if File.directory?(view_path)
  98. ActionController::Base.prepend_view_path(view_path)
  99. ActionMailer::Base.prepend_view_path(view_path)
  100. end
  101. # Add the plugin directories to rails autoload paths
  102. engine_cfg = Rails::Engine::Configuration.new(p.directory)
  103. engine_cfg.paths.add 'lib', eager_load: true
  104. Rails.application.config.eager_load_paths += engine_cfg.eager_load_paths
  105. Rails.application.config.autoload_once_paths += engine_cfg.autoload_once_paths
  106. Rails.application.config.autoload_paths += engine_cfg.autoload_paths
  107. ActiveSupport::Dependencies.autoload_paths += engine_cfg.eager_load_paths + engine_cfg.autoload_once_paths + engine_cfg.autoload_paths
  108. # Defines plugin setting if present
  109. if p.settings
  110. Setting.define_plugin_setting p
  111. end
  112. # Warn for potential settings[:partial] collisions
  113. if p.configurable?
  114. partial = p.settings[:partial]
  115. if @used_partials[partial]
  116. Rails.logger.warn "WARNING: settings partial '#{partial}' is declared in '#{p.id}' plugin but it is already used by plugin '#{@used_partials[partial]}'. Only one settings view will be used. You may want to contact those plugins authors to fix this."
  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 self.load
  148. Dir.glob(File.join(self.directory, '*')).sort.each do |directory|
  149. if File.directory?(directory)
  150. lib = File.join(directory, "lib")
  151. if File.directory?(lib)
  152. $:.unshift lib
  153. ActiveSupport::Dependencies.autoload_paths += [lib]
  154. end
  155. initializer = File.join(directory, "init.rb")
  156. if File.file?(initializer)
  157. require initializer
  158. end
  159. end
  160. end
  161. end
  162. def initialize(id)
  163. @id = id.to_sym
  164. end
  165. def public_directory
  166. File.join(self.class.public_directory, id.to_s)
  167. end
  168. def to_param
  169. id
  170. end
  171. # Returns the absolute path to the plugin assets directory
  172. def assets_directory
  173. File.join(directory, 'assets')
  174. end
  175. def <=>(plugin)
  176. self.id.to_s <=> plugin.id.to_s
  177. end
  178. # Sets a requirement on Redmine version
  179. # Raises a PluginRequirementError exception if the requirement is not met
  180. #
  181. # Examples
  182. # # Requires Redmine 0.7.3 or higher
  183. # requires_redmine :version_or_higher => '0.7.3'
  184. # requires_redmine '0.7.3'
  185. #
  186. # # Requires Redmine 0.7.x or higher
  187. # requires_redmine '0.7'
  188. #
  189. # # Requires a specific Redmine version
  190. # requires_redmine :version => '0.7.3' # 0.7.3 only
  191. # requires_redmine :version => '0.7' # 0.7.x
  192. # requires_redmine :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  193. #
  194. # # Requires a Redmine version within a range
  195. # requires_redmine :version => '0.7.3'..'0.9.1' # >= 0.7.3 and <= 0.9.1
  196. # requires_redmine :version => '0.7'..'0.9' # >= 0.7.x and <= 0.9.x
  197. def requires_redmine(arg)
  198. arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
  199. arg.assert_valid_keys(:version, :version_or_higher)
  200. current = Redmine::VERSION.to_a
  201. arg.each do |k, req|
  202. case k
  203. when :version_or_higher
  204. raise ArgumentError.new(":version_or_higher accepts a version string only") unless req.is_a?(String)
  205. unless compare_versions(req, current) <= 0
  206. raise PluginRequirementError.new("#{id} plugin requires Redmine #{req} or higher but current is #{current.join('.')}")
  207. end
  208. when :version
  209. req = [req] if req.is_a?(String)
  210. if req.is_a?(Array)
  211. unless req.detect {|ver| compare_versions(ver, current) == 0}
  212. raise PluginRequirementError.new("#{id} plugin requires one the following Redmine versions: #{req.join(', ')} but current is #{current.join('.')}")
  213. end
  214. elsif req.is_a?(Range)
  215. unless compare_versions(req.first, current) <= 0 && compare_versions(req.last, current) >= 0
  216. raise PluginRequirementError.new("#{id} plugin requires a Redmine version between #{req.first} and #{req.last} but current is #{current.join('.')}")
  217. end
  218. else
  219. raise ArgumentError.new(":version option accepts a version string, an array or a range of versions")
  220. end
  221. end
  222. end
  223. true
  224. end
  225. def compare_versions(requirement, current)
  226. requirement = requirement.split('.').collect(&:to_i)
  227. requirement <=> current.slice(0, requirement.size)
  228. end
  229. private :compare_versions
  230. # Sets a requirement on a Redmine plugin version
  231. # Raises a PluginRequirementError exception if the requirement is not met
  232. #
  233. # Examples
  234. # # Requires a plugin named :foo version 0.7.3 or higher
  235. # requires_redmine_plugin :foo, :version_or_higher => '0.7.3'
  236. # requires_redmine_plugin :foo, '0.7.3'
  237. #
  238. # # Requires a specific version of a Redmine plugin
  239. # requires_redmine_plugin :foo, :version => '0.7.3' # 0.7.3 only
  240. # requires_redmine_plugin :foo, :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
  241. def requires_redmine_plugin(plugin_name, arg)
  242. arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
  243. arg.assert_valid_keys(:version, :version_or_higher)
  244. begin
  245. plugin = Plugin.find(plugin_name)
  246. rescue PluginNotFound
  247. raise PluginRequirementError.new("#{id} plugin requires the #{plugin_name} plugin")
  248. end
  249. current = plugin.version.split('.').collect(&:to_i)
  250. arg.each do |k, v|
  251. v = [] << v unless v.is_a?(Array)
  252. versions = v.collect {|s| s.split('.').collect(&:to_i)}
  253. case k
  254. when :version_or_higher
  255. raise ArgumentError.new("wrong number of versions (#{versions.size} for 1)") unless versions.size == 1
  256. unless (current <=> versions.first) >= 0
  257. raise PluginRequirementError.new("#{id} plugin requires the #{plugin_name} plugin #{v} or higher but current is #{current.join('.')}")
  258. end
  259. when :version
  260. unless versions.include?(current.slice(0,3))
  261. raise PluginRequirementError.new("#{id} plugin requires one the following versions of #{plugin_name}: #{v.join(', ')} but current is #{current.join('.')}")
  262. end
  263. end
  264. end
  265. true
  266. end
  267. # Adds an item to the given +menu+.
  268. # The +id+ parameter (equals to the project id) is automatically added to the url.
  269. # menu :project_menu, :plugin_example, { :controller => 'example', :action => 'say_hello' }, :caption => 'Sample'
  270. #
  271. # +name+ parameter can be: :top_menu, :account_menu, :application_menu or :project_menu
  272. #
  273. def menu(menu, item, url, options={})
  274. Redmine::MenuManager.map(menu).push(item, url, options)
  275. end
  276. alias :add_menu_item :menu
  277. # Removes +item+ from the given +menu+.
  278. def delete_menu_item(menu, item)
  279. Redmine::MenuManager.map(menu).delete(item)
  280. end
  281. # Defines a permission called +name+ for the given +actions+.
  282. #
  283. # The +actions+ argument is a hash with controllers as keys and actions as values (a single value or an array):
  284. # permission :destroy_contacts, { :contacts => :destroy }
  285. # permission :view_contacts, { :contacts => [:index, :show] }
  286. #
  287. # The +options+ argument is a hash that accept the following keys:
  288. # * :public => the permission is public if set to true (implicitly given to any user)
  289. # * :require => can be set to one of the following values to restrict users the permission can be given to: :loggedin, :member
  290. # * :read => set it to true so that the permission is still granted on closed projects
  291. #
  292. # Examples
  293. # # A permission that is implicitly given to any user
  294. # # This permission won't appear on the Roles & Permissions setup screen
  295. # permission :say_hello, { :example => :say_hello }, :public => true, :read => true
  296. #
  297. # # A permission that can be given to any user
  298. # permission :say_hello, { :example => :say_hello }
  299. #
  300. # # A permission that can be given to registered users only
  301. # permission :say_hello, { :example => :say_hello }, :require => :loggedin
  302. #
  303. # # A permission that can be given to project members only
  304. # permission :say_hello, { :example => :say_hello }, :require => :member
  305. def permission(name, actions, options = {})
  306. if @project_module
  307. Redmine::AccessControl.map {|map| map.project_module(@project_module) {|map|map.permission(name, actions, options)}}
  308. else
  309. Redmine::AccessControl.map {|map| map.permission(name, actions, options)}
  310. end
  311. end
  312. # Defines a project module, that can be enabled/disabled for each project.
  313. # Permissions defined inside +block+ will be bind to the module.
  314. #
  315. # project_module :things do
  316. # permission :view_contacts, { :contacts => [:list, :show] }, :public => true
  317. # permission :destroy_contacts, { :contacts => :destroy }
  318. # end
  319. def project_module(name, &block)
  320. @project_module = name
  321. self.instance_eval(&block)
  322. @project_module = nil
  323. end
  324. # Registers an activity provider.
  325. #
  326. # Options:
  327. # * <tt>:class_name</tt> - one or more model(s) that provide these events (inferred from event_type by default)
  328. # * <tt>:default</tt> - setting this option to false will make the events not displayed by default
  329. #
  330. # A model can provide several activity event types.
  331. #
  332. # Examples:
  333. # register :news
  334. # register :scrums, :class_name => 'Meeting'
  335. # register :issues, :class_name => ['Issue', 'Journal']
  336. #
  337. # Retrieving events:
  338. # Associated model(s) must implement the find_events class method.
  339. # ActiveRecord models can use acts_as_activity_provider as a way to implement this class method.
  340. #
  341. # The following call should return all the scrum events visible by current user that occurred in the 5 last days:
  342. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today)
  343. # Meeting.find_events('scrums', User.current, 5.days.ago, Date.today, :project => foo) # events for project foo only
  344. #
  345. # Note that :view_scrums permission is required to view these events in the activity view.
  346. def activity_provider(*args)
  347. Redmine::Activity.register(*args)
  348. end
  349. # Registers a wiki formatter.
  350. #
  351. # Parameters:
  352. # * +name+ - formatter name
  353. # * +formatter+ - formatter class, which should have an instance method +to_html+
  354. # * +helper+ - helper module, which will be included by wiki pages (optional)
  355. # * +html_parser+ class reponsible for converting HTML to wiki text (optional)
  356. # * +options+ - a Hash of options (optional)
  357. # * :label - label for the formatter displayed in application settings
  358. #
  359. # Examples:
  360. # wiki_format_provider(:custom_formatter, CustomFormatter, :label => "My custom formatter")
  361. #
  362. def wiki_format_provider(name, *args)
  363. Redmine::WikiFormatting.register(name, *args)
  364. end
  365. # Returns +true+ if the plugin can be configured.
  366. def configurable?
  367. settings && settings.is_a?(Hash) && !settings[:partial].blank?
  368. end
  369. def mirror_assets
  370. source = assets_directory
  371. destination = public_directory
  372. return unless File.directory?(source)
  373. source_files = Dir[source + "/**/*"]
  374. source_dirs = source_files.select { |d| File.directory?(d) }
  375. source_files -= source_dirs
  376. unless source_files.empty?
  377. base_target_dir = File.join(destination, File.dirname(source_files.first).gsub(source, ''))
  378. begin
  379. FileUtils.mkdir_p(base_target_dir)
  380. rescue Exception => e
  381. raise "Could not create directory #{base_target_dir}: " + e.message
  382. end
  383. end
  384. source_dirs.each do |dir|
  385. # strip down these paths so we have simple, relative paths we can
  386. # add to the destination
  387. target_dir = File.join(destination, dir.gsub(source, ''))
  388. begin
  389. FileUtils.mkdir_p(target_dir)
  390. rescue Exception => e
  391. raise "Could not create directory #{target_dir}: " + e.message
  392. end
  393. end
  394. source_files.each do |file|
  395. begin
  396. target = File.join(destination, file.gsub(source, ''))
  397. unless File.exist?(target) && FileUtils.identical?(file, target)
  398. FileUtils.cp(file, target)
  399. end
  400. rescue Exception => e
  401. raise "Could not copy #{file} to #{target}: " + e.message
  402. end
  403. end
  404. end
  405. # Mirrors assets from one or all plugins to public/plugin_assets
  406. def self.mirror_assets(name=nil)
  407. if name.present?
  408. find(name).mirror_assets
  409. else
  410. all.each do |plugin|
  411. plugin.mirror_assets
  412. end
  413. end
  414. end
  415. # The directory containing this plugin's migrations (<tt>plugin/db/migrate</tt>)
  416. def migration_directory
  417. File.join(directory, 'db', 'migrate')
  418. end
  419. # Returns the version number of the latest migration for this plugin. Returns
  420. # nil if this plugin has no migrations.
  421. def latest_migration
  422. migrations.last
  423. end
  424. # Returns the version numbers of all migrations for this plugin.
  425. def migrations
  426. migrations = Dir[migration_directory+"/*.rb"]
  427. migrations.map { |p| File.basename(p).match(/0*(\d+)\_/)[1].to_i }.sort
  428. end
  429. # Migrate this plugin to the given version
  430. def migrate(version = nil)
  431. Redmine::Plugin::Migrator.migrate_plugin(self, version)
  432. end
  433. # Migrates all plugins or a single plugin to a given version
  434. # Exemples:
  435. # Plugin.migrate
  436. # Plugin.migrate('sample_plugin')
  437. # Plugin.migrate('sample_plugin', 1)
  438. #
  439. def self.migrate(name=nil, version=nil)
  440. if name.present?
  441. find(name).migrate(version)
  442. else
  443. all.each do |plugin|
  444. plugin.migrate
  445. end
  446. end
  447. end
  448. class MigrationContext < ActiveRecord::MigrationContext
  449. def up(target_version = nil)
  450. selected_migrations = if block_given?
  451. migrations.select { |m| yield m }
  452. else
  453. migrations
  454. end
  455. Migrator.new(:up, selected_migrations, target_version).migrate
  456. end
  457. def down(target_version = nil)
  458. selected_migrations = if block_given?
  459. migrations.select { |m| yield m }
  460. else
  461. migrations
  462. end
  463. Migrator.new(:down, selected_migrations, target_version).migrate
  464. end
  465. def run(direction, target_version)
  466. Migrator.new(direction, migrations, target_version).run
  467. end
  468. def open
  469. Migrator.new(:up, migrations, nil)
  470. end
  471. end
  472. class Migrator < ActiveRecord::Migrator
  473. # We need to be able to set the 'current' plugin being migrated.
  474. cattr_accessor :current_plugin
  475. class << self
  476. # Runs the migrations from a plugin, up (or down) to the version given
  477. def migrate_plugin(plugin, version)
  478. self.current_plugin = plugin
  479. return if current_version(plugin) == version
  480. MigrationContext.new(plugin.migration_directory).migrate(version)
  481. end
  482. def get_all_versions(plugin = current_plugin)
  483. # Delete migrations that don't match .. to_i will work because the number comes first
  484. @all_versions ||= {}
  485. @all_versions[plugin.id.to_s] ||= begin
  486. sm_table = ::ActiveRecord::SchemaMigration.table_name
  487. migration_versions = ActiveRecord::Base.connection.select_values("SELECT version FROM #{sm_table}")
  488. versions_by_plugins = migration_versions.group_by { |version| version.match(/-(.*)$/).try(:[], 1) }
  489. @all_versions = versions_by_plugins.transform_values! {|versions| versions.map!(&:to_i).sort! }
  490. @all_versions[plugin.id.to_s] || []
  491. end
  492. end
  493. def current_version(plugin = current_plugin)
  494. get_all_versions(plugin).last || 0
  495. end
  496. end
  497. def load_migrated
  498. @migrated_versions = Set.new(self.class.get_all_versions(current_plugin))
  499. end
  500. def record_version_state_after_migrating(version)
  501. super(version.to_s + "-" + current_plugin.id.to_s)
  502. end
  503. end
  504. end
  505. end