Plugin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. 'classBase' => 'src',
  122. 'ignoreMissing' => false,
  123. 'name' => $plugin
  124. ];
  125. if (!isset($config['path'])) {
  126. $config['path'] = Configure::read('plugins.' . $plugin);
  127. }
  128. if (empty($config['path'])) {
  129. $paths = App::path('Plugin');
  130. $pluginPath = str_replace('/', DIRECTORY_SEPARATOR, $plugin);
  131. foreach ($paths as $path) {
  132. if (is_dir($path . $pluginPath)) {
  133. $config['path'] = $path . $pluginPath . DIRECTORY_SEPARATOR;
  134. break;
  135. }
  136. }
  137. }
  138. if (empty($config['path'])) {
  139. throw new MissingPluginException(['plugin' => $plugin]);
  140. }
  141. $config['classPath'] = $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR;
  142. if (!isset($config['configPath'])) {
  143. $config['configPath'] = $config['path'] . 'config' . DIRECTORY_SEPARATOR;
  144. }
  145. // Use stub plugins as this method will be removed long term.
  146. static::getCollection()->add(new PluginApp($config));
  147. if ($config['autoload'] === true) {
  148. if (empty(static::$_loader)) {
  149. static::$_loader = new ClassLoader();
  150. static::$_loader->register();
  151. }
  152. static::$_loader->addNamespace(
  153. str_replace('/', '\\', $plugin),
  154. $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR
  155. );
  156. static::$_loader->addNamespace(
  157. str_replace('/', '\\', $plugin) . '\Test',
  158. $config['path'] . 'tests' . DIRECTORY_SEPARATOR
  159. );
  160. }
  161. if ($config['bootstrap'] === true) {
  162. static::bootstrap($plugin);
  163. }
  164. }
  165. /**
  166. * Load the plugin path configuration file.
  167. *
  168. * @return void
  169. */
  170. protected static function _loadConfig()
  171. {
  172. if (Configure::check('plugins')) {
  173. return;
  174. }
  175. $vendorFile = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'cakephp-plugins.php';
  176. if (!file_exists($vendorFile)) {
  177. $vendorFile = dirname(dirname(dirname(dirname(__DIR__)))) . DIRECTORY_SEPARATOR . 'cakephp-plugins.php';
  178. if (!file_exists($vendorFile)) {
  179. Configure::write(['plugins' => []]);
  180. return;
  181. }
  182. }
  183. $config = require $vendorFile;
  184. Configure::write($config);
  185. }
  186. /**
  187. * Will load all the plugins located in the default plugin folder.
  188. *
  189. * If passed an options array, it will be used as a common default for all plugins to be loaded
  190. * It is possible to set specific defaults for each plugins in the options array. Examples:
  191. *
  192. * ```
  193. * Plugin::loadAll([
  194. * ['bootstrap' => true],
  195. * 'DebugKit' => ['routes' => true],
  196. * ]);
  197. * ```
  198. *
  199. * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load the routes file
  200. * and will not look for any bootstrap script.
  201. *
  202. * If a plugin has been loaded already, it will not be reloaded by loadAll().
  203. *
  204. * @param array $options Options.
  205. * @return void
  206. * @throws \Cake\Core\Exception\MissingPluginException
  207. */
  208. public static function loadAll(array $options = [])
  209. {
  210. static::_loadConfig();
  211. $plugins = [];
  212. foreach (App::path('Plugin') as $path) {
  213. if (!is_dir($path)) {
  214. continue;
  215. }
  216. $dir = new DirectoryIterator($path);
  217. foreach ($dir as $dirPath) {
  218. if ($dirPath->isDir() && !$dirPath->isDot()) {
  219. $plugins[] = $dirPath->getBasename();
  220. }
  221. }
  222. }
  223. if (Configure::check('plugins')) {
  224. $plugins = array_merge($plugins, array_keys(Configure::read('plugins')));
  225. $plugins = array_unique($plugins);
  226. }
  227. foreach ($plugins as $p) {
  228. $opts = isset($options[$p]) ? $options[$p] : null;
  229. if ($opts === null && isset($options[0])) {
  230. $opts = $options[0];
  231. }
  232. if (isset(static::$_plugins[$p])) {
  233. continue;
  234. }
  235. static::load($p, (array)$opts);
  236. }
  237. }
  238. /**
  239. * Returns the filesystem path for a plugin
  240. *
  241. * @param string $name name of the plugin in CamelCase format
  242. * @return string path to the plugin folder
  243. * @throws \Cake\Core\Exception\MissingPluginException if the folder for plugin was not found or plugin has not been loaded
  244. */
  245. public static function path($name)
  246. {
  247. $plugin = static::getCollection()->get($name);
  248. return $plugin->getPath();
  249. }
  250. /**
  251. * Returns the filesystem path for plugin's folder containing class folders.
  252. *
  253. * @param string $name name of the plugin in CamelCase format.
  254. * @return string Path to the plugin folder container class folders.
  255. * @throws \Cake\Core\Exception\MissingPluginException If plugin has not been loaded.
  256. */
  257. public static function classPath($name)
  258. {
  259. $plugin = static::getCollection()->get($name);
  260. return $plugin->getClassPath();
  261. }
  262. /**
  263. * Returns the filesystem path for plugin's folder containing config files.
  264. *
  265. * @param string $name name of the plugin in CamelCase format.
  266. * @return string Path to the plugin folder container config files.
  267. * @throws \Cake\Core\Exception\MissingPluginException If plugin has not been loaded.
  268. */
  269. public static function configPath($name)
  270. {
  271. $plugin = static::getCollection()->get($name);
  272. return $plugin->getConfigPath();
  273. }
  274. /**
  275. * Loads the bootstrapping files for a plugin, or calls the initialization setup in the configuration
  276. *
  277. * @param string $name name of the plugin
  278. * @return mixed
  279. * @see \Cake\Core\Plugin::load() for examples of bootstrap configuration
  280. */
  281. public static function bootstrap($name)
  282. {
  283. $plugin = static::getCollection()->get($name);
  284. if (!$plugin->isBootstrapEnabled()) {
  285. return false;
  286. }
  287. return static::_includeFile(
  288. $plugin->getConfigPath() . 'bootstrap.php',
  289. true
  290. );
  291. }
  292. /**
  293. * Loads the routes file for a plugin, or all plugins configured to load their respective routes file.
  294. *
  295. * If you need fine grained control over how routes are loaded for plugins, you
  296. * can use {@see Cake\Routing\RouteBuilder::loadPlugin()}
  297. *
  298. * @param string|null $name name of the plugin, if null will operate on all
  299. * plugins having enabled the loading of routes files.
  300. * @return bool
  301. */
  302. public static function routes($name = null)
  303. {
  304. if ($name === null) {
  305. foreach (static::loaded() as $p) {
  306. static::routes($p);
  307. }
  308. return true;
  309. }
  310. $plugin = static::getCollection()->get($name);
  311. if (!$plugin->isRoutesEnabled()) {
  312. return false;
  313. }
  314. return (bool)static::_includeFile(
  315. $plugin->getConfigPath() . 'routes.php',
  316. true
  317. );
  318. }
  319. /**
  320. * Returns true if the plugin $plugin is already loaded
  321. * If plugin is null, it will return a list of all loaded plugins
  322. *
  323. * @param string|null $plugin Plugin name.
  324. * @return bool|array Boolean true if $plugin is already loaded.
  325. * If $plugin is null, returns a list of plugins that have been loaded
  326. */
  327. public static function loaded($plugin = null)
  328. {
  329. if ($plugin !== null) {
  330. return static::getCollection()->has($plugin);
  331. }
  332. $names = [];
  333. foreach (static::getCollection() as $plugin) {
  334. $names[] = $plugin->getName();
  335. }
  336. sort($names);
  337. return $names;
  338. }
  339. /**
  340. * Forgets a loaded plugin or all of them if first parameter is null
  341. *
  342. * @param string|null $plugin name of the plugin to forget
  343. * @return void
  344. */
  345. public static function unload($plugin = null)
  346. {
  347. if ($plugin === null) {
  348. static::$plugins = null;
  349. } else {
  350. static::getCollection()->remove($plugin);
  351. }
  352. }
  353. /**
  354. * Include file, ignoring include error if needed if file is missing
  355. *
  356. * @param string $file File to include
  357. * @param bool $ignoreMissing Whether to ignore include error for missing files
  358. * @return mixed
  359. */
  360. protected static function _includeFile($file, $ignoreMissing = false)
  361. {
  362. if ($ignoreMissing && !is_file($file)) {
  363. return false;
  364. }
  365. return include $file;
  366. }
  367. /**
  368. * Get the shared plugin collection.
  369. *
  370. * @return \Cake\Core\PluginCollection
  371. */
  372. public static function getCollection()
  373. {
  374. if (!isset(static::$plugins)) {
  375. static::$plugins = new PluginCollection();
  376. }
  377. return static::$plugins;
  378. }
  379. }