Plugin.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Core;
  16. use Cake\Core\Exception\MissingPluginException;
  17. use DirectoryIterator;
  18. /**
  19. * Plugin is used to load and locate plugins.
  20. *
  21. * It also can retrieve plugin paths and load their bootstrap and routes files.
  22. *
  23. * @link https://book.cakephp.org/3.0/en/plugins.html
  24. */
  25. class Plugin
  26. {
  27. /**
  28. * Holds a list of all loaded plugins and their configuration
  29. *
  30. * @var \Cake\Core\PluginCollection
  31. */
  32. protected static $plugins;
  33. /**
  34. * Class loader instance
  35. *
  36. * @var \Cake\Core\ClassLoader
  37. */
  38. protected static $_loader;
  39. /**
  40. * Loads a plugin and optionally loads bootstrapping,
  41. * routing files or runs an initialization function.
  42. *
  43. * Plugins only need to be loaded if you want bootstrapping/routes/cli commands to
  44. * be exposed. If your plugin does not expose any of these features you do not need
  45. * to load them.
  46. *
  47. * This method does not configure any autoloaders. That must be done separately either
  48. * through composer, or your own code during config/bootstrap.php.
  49. *
  50. * ### Examples:
  51. *
  52. * `Plugin::load('DebugKit')`
  53. *
  54. * Will load the DebugKit plugin and will not load any bootstrap nor route files.
  55. * However, the plugin will be part of the framework default routes, and have its
  56. * CLI tools (if any) available for use.
  57. *
  58. * `Plugin::load('DebugKit', ['bootstrap' => true, 'routes' => true])`
  59. *
  60. * Will load the bootstrap.php and routes.php files.
  61. *
  62. * `Plugin::load('DebugKit', ['bootstrap' => false, 'routes' => true])`
  63. *
  64. * Will load routes.php file but not bootstrap.php
  65. *
  66. * `Plugin::load('FOC/Authenticate')`
  67. *
  68. * Will load plugin from `plugins/FOC/Authenticate`.
  69. *
  70. * It is also possible to load multiple plugins at once. Examples:
  71. *
  72. * `Plugin::load(['DebugKit', 'ApiGenerator'])`
  73. *
  74. * Will load the DebugKit and ApiGenerator plugins.
  75. *
  76. * `Plugin::load(['DebugKit', 'ApiGenerator'], ['bootstrap' => true])`
  77. *
  78. * Will load bootstrap file for both plugins
  79. *
  80. * ```
  81. * Plugin::load([
  82. * 'DebugKit' => ['routes' => true],
  83. * 'ApiGenerator'
  84. * ],
  85. * ['bootstrap' => true])
  86. * ```
  87. *
  88. * Will only load the bootstrap for ApiGenerator and only the routes for DebugKit
  89. *
  90. * ### Configuration options
  91. *
  92. * - `bootstrap` - array - Whether or not you want the $plugin/config/bootstrap.php file loaded.
  93. * - `routes` - boolean - Whether or not you want to load the $plugin/config/routes.php file.
  94. * - `ignoreMissing` - boolean - Set to true to ignore missing bootstrap/routes files.
  95. * - `path` - string - The path the plugin can be found on. If empty the default plugin path (App.pluginPaths) will be used.
  96. * - `classBase` - The path relative to `path` which contains the folders with class files.
  97. * Defaults to "src".
  98. * - `autoload` - boolean - Whether or not you want an autoloader registered. This defaults to false. The framework
  99. * assumes you have configured autoloaders using composer. However, if your application source tree is made up of
  100. * plugins, this can be a useful option.
  101. *
  102. * @param string|array $plugin name of the plugin to be loaded in CamelCase format or array or plugins to load
  103. * @param array $config configuration options for the plugin
  104. * @throws \Cake\Core\Exception\MissingPluginException if the folder for the plugin to be loaded is not found
  105. * @return void
  106. */
  107. public static function load($plugin, array $config = [])
  108. {
  109. if (is_array($plugin)) {
  110. foreach ($plugin as $name => $conf) {
  111. list($name, $conf) = is_numeric($name) ? [$conf, $config] : [$name, $conf];
  112. static::load($name, $conf);
  113. }
  114. return;
  115. }
  116. static::_loadConfig();
  117. $config += [
  118. 'autoload' => false,
  119. 'bootstrap' => false,
  120. 'routes' => false,
  121. 'console' => true,
  122. 'classBase' => 'src',
  123. 'ignoreMissing' => false,
  124. 'name' => $plugin
  125. ];
  126. if (!isset($config['path'])) {
  127. $config['path'] = Configure::read('plugins.' . $plugin);
  128. }
  129. if (empty($config['path'])) {
  130. $paths = App::path('Plugin');
  131. $pluginPath = str_replace('/', DIRECTORY_SEPARATOR, $plugin);
  132. foreach ($paths as $path) {
  133. if (is_dir($path . $pluginPath)) {
  134. $config['path'] = $path . $pluginPath . DIRECTORY_SEPARATOR;
  135. break;
  136. }
  137. }
  138. }
  139. if (empty($config['path'])) {
  140. throw new MissingPluginException(['plugin' => $plugin]);
  141. }
  142. $config['classPath'] = $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR;
  143. if (!isset($config['configPath'])) {
  144. $config['configPath'] = $config['path'] . 'config' . DIRECTORY_SEPARATOR;
  145. }
  146. // Use stub plugins as this method will be removed long term.
  147. static::getCollection()->add(new BasePlugin($config));
  148. if ($config['autoload'] === true) {
  149. if (empty(static::$_loader)) {
  150. static::$_loader = new ClassLoader();
  151. static::$_loader->register();
  152. }
  153. static::$_loader->addNamespace(
  154. str_replace('/', '\\', $plugin),
  155. $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR
  156. );
  157. static::$_loader->addNamespace(
  158. str_replace('/', '\\', $plugin) . '\Test',
  159. $config['path'] . 'tests' . DIRECTORY_SEPARATOR
  160. );
  161. }
  162. // Defer the bootstrap process if an Application class exists.
  163. // Immediate plugin bootstrapping is deprecated and will be removed in 4.x
  164. $appClass = Configure::read('App.namespace') . '\\' . 'Application';
  165. if ($config['bootstrap'] === true && !class_exists($appClass)) {
  166. static::bootstrap($plugin);
  167. }
  168. }
  169. /**
  170. * Load the plugin path configuration file.
  171. *
  172. * @return void
  173. */
  174. protected static function _loadConfig()
  175. {
  176. if (Configure::check('plugins')) {
  177. return;
  178. }
  179. $vendorFile = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'cakephp-plugins.php';
  180. if (!file_exists($vendorFile)) {
  181. $vendorFile = dirname(dirname(dirname(dirname(__DIR__)))) . DIRECTORY_SEPARATOR . 'cakephp-plugins.php';
  182. if (!file_exists($vendorFile)) {
  183. Configure::write(['plugins' => []]);
  184. return;
  185. }
  186. }
  187. $config = require $vendorFile;
  188. Configure::write($config);
  189. }
  190. /**
  191. * Will load all the plugins located in the default plugin folder.
  192. *
  193. * If passed an options array, it will be used as a common default for all plugins to be loaded
  194. * It is possible to set specific defaults for each plugins in the options array. Examples:
  195. *
  196. * ```
  197. * Plugin::loadAll([
  198. * ['bootstrap' => true],
  199. * 'DebugKit' => ['routes' => true],
  200. * ]);
  201. * ```
  202. *
  203. * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load the routes file
  204. * and will not look for any bootstrap script.
  205. *
  206. * If a plugin has been loaded already, it will not be reloaded by loadAll().
  207. *
  208. * @param array $options Options.
  209. * @return void
  210. * @throws \Cake\Core\Exception\MissingPluginException
  211. */
  212. public static function loadAll(array $options = [])
  213. {
  214. static::_loadConfig();
  215. $plugins = [];
  216. foreach (App::path('Plugin') as $path) {
  217. if (!is_dir($path)) {
  218. continue;
  219. }
  220. $dir = new DirectoryIterator($path);
  221. foreach ($dir as $dirPath) {
  222. if ($dirPath->isDir() && !$dirPath->isDot()) {
  223. $plugins[] = $dirPath->getBasename();
  224. }
  225. }
  226. }
  227. if (Configure::check('plugins')) {
  228. $plugins = array_merge($plugins, array_keys(Configure::read('plugins')));
  229. $plugins = array_unique($plugins);
  230. }
  231. $collection = static::getCollection();
  232. foreach ($plugins as $p) {
  233. $opts = isset($options[$p]) ? $options[$p] : null;
  234. if ($opts === null && isset($options[0])) {
  235. $opts = $options[0];
  236. }
  237. if ($collection->has($p)) {
  238. continue;
  239. }
  240. static::load($p, (array)$opts);
  241. }
  242. }
  243. /**
  244. * Returns the filesystem path for a plugin
  245. *
  246. * @param string $name name of the plugin in CamelCase format
  247. * @return string path to the plugin folder
  248. * @throws \Cake\Core\Exception\MissingPluginException if the folder for plugin was not found or plugin has not been loaded
  249. */
  250. public static function path($name)
  251. {
  252. $plugin = static::getCollection()->get($name);
  253. return $plugin->getPath();
  254. }
  255. /**
  256. * Returns the filesystem path for plugin's folder containing class folders.
  257. *
  258. * @param string $name name of the plugin in CamelCase format.
  259. * @return string Path to the plugin folder container class folders.
  260. * @throws \Cake\Core\Exception\MissingPluginException If plugin has not been loaded.
  261. */
  262. public static function classPath($name)
  263. {
  264. $plugin = static::getCollection()->get($name);
  265. return $plugin->getClassPath();
  266. }
  267. /**
  268. * Returns the filesystem path for plugin's folder containing config files.
  269. *
  270. * @param string $name name of the plugin in CamelCase format.
  271. * @return string Path to the plugin folder container config files.
  272. * @throws \Cake\Core\Exception\MissingPluginException If plugin has not been loaded.
  273. */
  274. public static function configPath($name)
  275. {
  276. $plugin = static::getCollection()->get($name);
  277. return $plugin->getConfigPath();
  278. }
  279. /**
  280. * Loads the bootstrapping files for a plugin, or calls the initialization setup in the configuration
  281. *
  282. * @param string $name name of the plugin
  283. * @return mixed
  284. * @see \Cake\Core\Plugin::load() for examples of bootstrap configuration
  285. */
  286. public static function bootstrap($name)
  287. {
  288. $plugin = static::getCollection()->get($name);
  289. if (!$plugin->isEnabled('bootstrap')) {
  290. return false;
  291. }
  292. return static::_includeFile(
  293. $plugin->getConfigPath() . 'bootstrap.php',
  294. true
  295. );
  296. }
  297. /**
  298. * Loads the routes file for a plugin, or all plugins configured to load their respective routes file.
  299. *
  300. * If you need fine grained control over how routes are loaded for plugins, you
  301. * can use {@see Cake\Routing\RouteBuilder::loadPlugin()}
  302. *
  303. * @param string|null $name name of the plugin, if null will operate on all
  304. * plugins having enabled the loading of routes files.
  305. * @return bool
  306. */
  307. public static function routes($name = null)
  308. {
  309. if ($name === null) {
  310. foreach (static::loaded() as $p) {
  311. static::routes($p);
  312. }
  313. return true;
  314. }
  315. $plugin = static::getCollection()->get($name);
  316. if (!$plugin->isEnabled('routes')) {
  317. return false;
  318. }
  319. return (bool)static::_includeFile(
  320. $plugin->getConfigPath() . 'routes.php',
  321. true
  322. );
  323. }
  324. /**
  325. * Returns true if the plugin $plugin is already loaded
  326. * If plugin is null, it will return a list of all loaded plugins
  327. *
  328. * @param string|null $plugin Plugin name.
  329. * @return bool|array Boolean true if $plugin is already loaded.
  330. * If $plugin is null, returns a list of plugins that have been loaded
  331. */
  332. public static function loaded($plugin = null)
  333. {
  334. if ($plugin !== null) {
  335. return static::getCollection()->has($plugin);
  336. }
  337. $names = [];
  338. foreach (static::getCollection() as $plugin) {
  339. $names[] = $plugin->getName();
  340. }
  341. sort($names);
  342. return $names;
  343. }
  344. /**
  345. * Forgets a loaded plugin or all of them if first parameter is null
  346. *
  347. * @param string|null $plugin name of the plugin to forget
  348. * @return void
  349. */
  350. public static function unload($plugin = null)
  351. {
  352. if ($plugin === null) {
  353. static::$plugins = null;
  354. } else {
  355. static::getCollection()->remove($plugin);
  356. }
  357. }
  358. /**
  359. * Include file, ignoring include error if needed if file is missing
  360. *
  361. * @param string $file File to include
  362. * @param bool $ignoreMissing Whether to ignore include error for missing files
  363. * @return mixed
  364. */
  365. protected static function _includeFile($file, $ignoreMissing = false)
  366. {
  367. if ($ignoreMissing && !is_file($file)) {
  368. return false;
  369. }
  370. return include $file;
  371. }
  372. /**
  373. * Get the shared plugin collection.
  374. *
  375. * @return \Cake\Core\PluginCollection
  376. */
  377. public static function getCollection()
  378. {
  379. if (!isset(static::$plugins)) {
  380. static::$plugins = new PluginCollection();
  381. }
  382. return static::$plugins;
  383. }
  384. }