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

plugin.rb 18 kB

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

软件技术创新是当今国家整体创新能力的重要基础和发展引擎。近年来,大众参与的软件创新与创业活动已经成为网络时代软件开发和应用的新形态,正在快速改变着全球软件创新模式和软件产业格局。 ...