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.
 
 
 
 
 

416 lines
14 KiB

  1. <?php
  2. namespace dokuwiki\Extension;
  3. use dokuwiki\ErrorHandler;
  4. /**
  5. * Class to encapsulate access to dokuwiki plugins
  6. *
  7. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  8. * @author Christopher Smith <chris@jalakai.co.uk>
  9. */
  10. class PluginController
  11. {
  12. /** @var array the types of plugins DokuWiki supports */
  13. public const PLUGIN_TYPES = ['auth', 'admin', 'syntax', 'action', 'renderer', 'helper', 'remote', 'cli'];
  14. protected $listByType = [];
  15. /** @var array all installed plugins and their enabled state [plugin=>enabled] */
  16. protected $masterList = [];
  17. protected $pluginCascade = ['default' => [], 'local' => [], 'protected' => []];
  18. protected $lastLocalConfigFile = '';
  19. /**
  20. * Populates the master list of plugins
  21. */
  22. public function __construct()
  23. {
  24. $this->loadConfig();
  25. $this->populateMasterList();
  26. $this->initAutoloaders();
  27. }
  28. /**
  29. * Returns a list of available plugins of given type
  30. *
  31. * @param $type string, plugin_type name;
  32. * the type of plugin to return,
  33. * use empty string for all types
  34. * @param $all bool;
  35. * false to only return enabled plugins,
  36. * true to return both enabled and disabled plugins
  37. *
  38. * @return array of
  39. * - plugin names when $type = ''
  40. * - or plugin component names when a $type is given
  41. *
  42. * @author Andreas Gohr <andi@splitbrain.org>
  43. */
  44. public function getList($type = '', $all = false)
  45. {
  46. // request the complete list
  47. if (!$type) {
  48. return $all ? array_keys($this->masterList) : array_keys(array_filter($this->masterList));
  49. }
  50. if (!isset($this->listByType[$type]['enabled'])) {
  51. $this->listByType[$type]['enabled'] = $this->getListByType($type, true);
  52. }
  53. if ($all && !isset($this->listByType[$type]['disabled'])) {
  54. $this->listByType[$type]['disabled'] = $this->getListByType($type, false);
  55. }
  56. return $all
  57. ? array_merge($this->listByType[$type]['enabled'], $this->listByType[$type]['disabled'])
  58. : $this->listByType[$type]['enabled'];
  59. }
  60. /**
  61. * Loads the given plugin and creates an object of it
  62. *
  63. * @param $type string type of plugin to load
  64. * @param $name string name of the plugin to load
  65. * @param $new bool true to return a new instance of the plugin, false to use an already loaded instance
  66. * @param $disabled bool true to load even disabled plugins
  67. * @return PluginInterface|null the plugin object or null on failure
  68. * @author Andreas Gohr <andi@splitbrain.org>
  69. *
  70. */
  71. public function load($type, $name, $new = false, $disabled = false)
  72. {
  73. //we keep all loaded plugins available in global scope for reuse
  74. global $DOKU_PLUGINS;
  75. [$plugin, /* component */ ] = $this->splitName($name);
  76. // check if disabled
  77. if (!$disabled && !$this->isEnabled($plugin)) {
  78. return null;
  79. }
  80. $class = $type . '_plugin_' . $name;
  81. try {
  82. //plugin already loaded?
  83. if (!empty($DOKU_PLUGINS[$type][$name])) {
  84. if ($new || !$DOKU_PLUGINS[$type][$name]->isSingleton()) {
  85. return class_exists($class, true) ? new $class() : null;
  86. }
  87. return $DOKU_PLUGINS[$type][$name];
  88. }
  89. //construct class and instantiate
  90. if (!class_exists($class, true)) {
  91. # the plugin might be in the wrong directory
  92. $inf = confToHash(DOKU_PLUGIN . "$plugin/plugin.info.txt");
  93. if ($inf['base'] && $inf['base'] != $plugin) {
  94. msg(
  95. sprintf(
  96. "Plugin installed incorrectly. Rename plugin directory '%s' to '%s'.",
  97. hsc($plugin),
  98. hsc(
  99. $inf['base']
  100. )
  101. ),
  102. -1
  103. );
  104. } elseif (preg_match('/^' . DOKU_PLUGIN_NAME_REGEX . '$/', $plugin) !== 1) {
  105. msg(sprintf(
  106. 'Plugin name \'%s\' is not a valid plugin name, only the characters a-z and 0-9 are allowed. ' .
  107. 'Maybe the plugin has been installed in the wrong directory?',
  108. hsc($plugin)
  109. ), -1);
  110. }
  111. return null;
  112. }
  113. $DOKU_PLUGINS[$type][$name] = new $class();
  114. } catch (\Throwable $e) {
  115. ErrorHandler::showExceptionMsg($e, sprintf('Failed to load plugin %s', $plugin));
  116. return null;
  117. }
  118. return $DOKU_PLUGINS[$type][$name];
  119. }
  120. /**
  121. * Whether plugin is disabled
  122. *
  123. * @param string $plugin name of plugin
  124. * @return bool true disabled, false enabled
  125. * @deprecated in favor of the more sensible isEnabled where the return value matches the enabled state
  126. */
  127. public function isDisabled($plugin)
  128. {
  129. dbg_deprecated('isEnabled()');
  130. return !$this->isEnabled($plugin);
  131. }
  132. /**
  133. * Check whether plugin is disabled
  134. *
  135. * @param string $plugin name of plugin
  136. * @return bool true enabled, false disabled
  137. */
  138. public function isEnabled($plugin)
  139. {
  140. return !empty($this->masterList[$plugin]);
  141. }
  142. /**
  143. * Disable the plugin
  144. *
  145. * @param string $plugin name of plugin
  146. * @return bool true saving succeed, false saving failed
  147. */
  148. public function disable($plugin)
  149. {
  150. if (array_key_exists($plugin, $this->pluginCascade['protected'])) return false;
  151. $this->masterList[$plugin] = 0;
  152. return $this->saveList();
  153. }
  154. /**
  155. * Enable the plugin
  156. *
  157. * @param string $plugin name of plugin
  158. * @return bool true saving succeed, false saving failed
  159. */
  160. public function enable($plugin)
  161. {
  162. if (array_key_exists($plugin, $this->pluginCascade['protected'])) return false;
  163. $this->masterList[$plugin] = 1;
  164. return $this->saveList();
  165. }
  166. /**
  167. * Returns cascade of the config files
  168. *
  169. * @return array with arrays of plugin configs
  170. */
  171. public function getCascade()
  172. {
  173. return $this->pluginCascade;
  174. }
  175. /**
  176. * Read all installed plugins and their current enabled state
  177. */
  178. protected function populateMasterList()
  179. {
  180. if ($dh = @opendir(DOKU_PLUGIN)) {
  181. $all_plugins = [];
  182. while (false !== ($plugin = readdir($dh))) {
  183. if ($plugin[0] === '.') continue; // skip hidden entries
  184. if (is_file(DOKU_PLUGIN . $plugin)) continue; // skip files, we're only interested in directories
  185. if (array_key_exists($plugin, $this->masterList) && $this->masterList[$plugin] == 0) {
  186. $all_plugins[$plugin] = 0;
  187. } elseif (array_key_exists($plugin, $this->masterList) && $this->masterList[$plugin] == 1) {
  188. $all_plugins[$plugin] = 1;
  189. } else {
  190. $all_plugins[$plugin] = 1;
  191. }
  192. }
  193. $this->masterList = $all_plugins;
  194. if (!file_exists($this->lastLocalConfigFile)) {
  195. $this->saveList(true);
  196. }
  197. }
  198. }
  199. /**
  200. * Includes the plugin config $files
  201. * and returns the entries of the $plugins array set in these files
  202. *
  203. * @param array $files list of files to include, latter overrides previous
  204. * @return array with entries of the $plugins arrays of the included files
  205. */
  206. protected function checkRequire($files)
  207. {
  208. $plugins = [];
  209. foreach ($files as $file) {
  210. if (file_exists($file)) {
  211. include_once($file);
  212. }
  213. }
  214. return $plugins;
  215. }
  216. /**
  217. * Save the current list of plugins
  218. *
  219. * @param bool $forceSave ;
  220. * false to save only when config changed
  221. * true to always save
  222. * @return bool true saving succeed, false saving failed
  223. */
  224. protected function saveList($forceSave = false)
  225. {
  226. global $conf;
  227. if (empty($this->masterList)) return false;
  228. // Rebuild list of local settings
  229. $local_plugins = $this->rebuildLocal();
  230. if ($local_plugins != $this->pluginCascade['local'] || $forceSave) {
  231. $file = $this->lastLocalConfigFile;
  232. $out = "<?php\n/*\n * Local plugin enable/disable settings\n" .
  233. " * Auto-generated through plugin/extension manager\n *\n" .
  234. " * NOTE: Plugins will not be added to this file unless there " .
  235. "is a need to override a default setting. Plugins are\n" .
  236. " * enabled by default.\n */\n";
  237. foreach ($local_plugins as $plugin => $value) {
  238. $out .= "\$plugins['$plugin'] = $value;\n";
  239. }
  240. // backup current file (remove any existing backup)
  241. if (file_exists($file)) {
  242. $backup = $file . '.bak';
  243. if (file_exists($backup)) @unlink($backup);
  244. if (!@copy($file, $backup)) return false;
  245. if ($conf['fperm']) chmod($backup, $conf['fperm']);
  246. }
  247. //check if can open for writing, else restore
  248. return io_saveFile($file, $out);
  249. }
  250. return false;
  251. }
  252. /**
  253. * Rebuild the set of local plugins
  254. *
  255. * @return array array of plugins to be saved in end($config_cascade['plugins']['local'])
  256. */
  257. protected function rebuildLocal()
  258. {
  259. //assign to local variable to avoid overwriting
  260. $backup = $this->masterList;
  261. //Can't do anything about protected one so rule them out completely
  262. $local_default = array_diff_key($backup, $this->pluginCascade['protected']);
  263. //Diff between local+default and default
  264. //gives us the ones we need to check and save
  265. $diffed_ones = array_diff_key($local_default, $this->pluginCascade['default']);
  266. //The ones which we are sure of (list of 0s not in default)
  267. $sure_plugins = array_filter($diffed_ones, [$this, 'negate']);
  268. //the ones in need of diff
  269. $conflicts = array_diff_key($local_default, $diffed_ones);
  270. //The final list
  271. return array_merge($sure_plugins, array_diff_assoc($conflicts, $this->pluginCascade['default']));
  272. }
  273. /**
  274. * Build the list of plugins and cascade
  275. *
  276. */
  277. protected function loadConfig()
  278. {
  279. global $config_cascade;
  280. foreach (['default', 'protected'] as $type) {
  281. if (array_key_exists($type, $config_cascade['plugins'])) {
  282. $this->pluginCascade[$type] = $this->checkRequire($config_cascade['plugins'][$type]);
  283. }
  284. }
  285. $local = $config_cascade['plugins']['local'];
  286. $this->lastLocalConfigFile = array_pop($local);
  287. $this->pluginCascade['local'] = $this->checkRequire([$this->lastLocalConfigFile]);
  288. $this->pluginCascade['default'] = array_merge(
  289. $this->pluginCascade['default'],
  290. $this->checkRequire($local)
  291. );
  292. $this->masterList = array_merge(
  293. $this->pluginCascade['default'],
  294. $this->pluginCascade['local'],
  295. $this->pluginCascade['protected']
  296. );
  297. }
  298. /**
  299. * Returns a list of available plugin components of given type
  300. *
  301. * @param string $type plugin_type name; the type of plugin to return,
  302. * @param bool $enabled true to return enabled plugins,
  303. * false to return disabled plugins
  304. * @return array of plugin components of requested type
  305. */
  306. protected function getListByType($type, $enabled)
  307. {
  308. $master_list = $enabled
  309. ? array_keys(array_filter($this->masterList))
  310. : array_keys(array_filter($this->masterList, [$this, 'negate']));
  311. $plugins = [];
  312. foreach ($master_list as $plugin) {
  313. if (file_exists(DOKU_PLUGIN . "$plugin/$type.php")) {
  314. $plugins[] = $plugin;
  315. continue;
  316. }
  317. $typedir = DOKU_PLUGIN . "$plugin/$type/";
  318. if (is_dir($typedir)) {
  319. if ($dp = opendir($typedir)) {
  320. while (false !== ($component = readdir($dp))) {
  321. if (
  322. str_starts_with($component, '.') ||
  323. !str_ends_with(strtolower($component), '.php')
  324. ) continue;
  325. if (is_file($typedir . $component)) {
  326. $plugins[] = $plugin . '_' . substr($component, 0, -4);
  327. }
  328. }
  329. closedir($dp);
  330. }
  331. }
  332. }//foreach
  333. return $plugins;
  334. }
  335. /**
  336. * Split name in a plugin name and a component name
  337. *
  338. * @param string $name
  339. * @return array with
  340. * - plugin name
  341. * - and component name when available, otherwise empty string
  342. */
  343. protected function splitName($name)
  344. {
  345. if (!isset($this->masterList[$name])) {
  346. return sexplode('_', $name, 2, '');
  347. }
  348. return [$name, ''];
  349. }
  350. /**
  351. * Returns inverse boolean value of the input
  352. *
  353. * @param mixed $input
  354. * @return bool inversed boolean value of input
  355. */
  356. protected function negate($input)
  357. {
  358. return !(bool)$input;
  359. }
  360. /**
  361. * Initialize vendor autoloaders for all plugins that have them
  362. */
  363. protected function initAutoloaders()
  364. {
  365. $plugins = $this->getList();
  366. foreach ($plugins as $plugin) {
  367. if (file_exists(DOKU_PLUGIN . $plugin . '/vendor/autoload.php')) {
  368. try {
  369. require_once(DOKU_PLUGIN . $plugin . '/vendor/autoload.php');
  370. } catch (\Throwable $e) {
  371. ErrorHandler::showExceptionMsg($e, sprintf('Failed to init plugin %s autoloader', $plugin));
  372. }
  373. }
  374. }
  375. }
  376. }