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

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