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

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