ExtensionManager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. /**
  3. * An extension manager to load extensions present in CORE_EXTENSIONS_PATH and THIRDPARTY_EXTENSIONS_PATH.
  4. *
  5. * @todo see coding style for methods!!
  6. */
  7. final class Minz_ExtensionManager {
  8. /** @var string */
  9. private static $ext_metaname = 'metadata.json';
  10. /** @var string */
  11. private static $ext_entry_point = 'extension.php';
  12. /** @var array<string,Minz_Extension> */
  13. private static $ext_list = array();
  14. /** @var array<string,Minz_Extension> */
  15. private static $ext_list_enabled = array();
  16. /** @var array<string,bool> */
  17. private static $ext_auto_enabled = array();
  18. /**
  19. * List of available hooks. Please keep this list sorted.
  20. * @var array<string,array{'list':array<callable>,'signature':'NoneToNone'|'NoneToString'|'OneToOne'|'PassArguments'}>
  21. */
  22. private static $hook_list = array(
  23. 'check_url_before_add' => array( // function($url) -> Url | null
  24. 'list' => array(),
  25. 'signature' => 'OneToOne',
  26. ),
  27. 'entry_before_display' => array( // function($entry) -> Entry | null
  28. 'list' => array(),
  29. 'signature' => 'OneToOne',
  30. ),
  31. 'entry_before_insert' => array( // function($entry) -> Entry | null
  32. 'list' => array(),
  33. 'signature' => 'OneToOne',
  34. ),
  35. 'feed_before_actualize' => array( // function($feed) -> Feed | null
  36. 'list' => array(),
  37. 'signature' => 'OneToOne',
  38. ),
  39. 'feed_before_insert' => array( // function($feed) -> Feed | null
  40. 'list' => array(),
  41. 'signature' => 'OneToOne',
  42. ),
  43. 'freshrss_init' => array( // function() -> none
  44. 'list' => array(),
  45. 'signature' => 'NoneToNone',
  46. ),
  47. 'freshrss_user_maintenance' => array( // function() -> none
  48. 'list' => array(),
  49. 'signature' => 'NoneToNone',
  50. ),
  51. 'js_vars' => array( // function($vars = array) -> array | null
  52. 'list' => array(),
  53. 'signature' => 'OneToOne',
  54. ),
  55. 'menu_admin_entry' => array( // function() -> string
  56. 'list' => array(),
  57. 'signature' => 'NoneToString',
  58. ),
  59. 'menu_configuration_entry' => array( // function() -> string
  60. 'list' => array(),
  61. 'signature' => 'NoneToString',
  62. ),
  63. 'menu_other_entry' => array( // function() -> string
  64. 'list' => array(),
  65. 'signature' => 'NoneToString',
  66. ),
  67. 'nav_menu' => array( // function() -> string
  68. 'list' => array(),
  69. 'signature' => 'NoneToString',
  70. ),
  71. 'nav_reading_modes' => array( // function($readingModes = array) -> array | null
  72. 'list' => array(),
  73. 'signature' => 'OneToOne',
  74. ),
  75. 'post_update' => array( // function(none) -> none
  76. 'list' => array(),
  77. 'signature' => 'NoneToNone',
  78. ),
  79. 'simplepie_before_init' => array( // function($simplePie, $feed) -> none
  80. 'list' => array(),
  81. 'signature' => 'PassArguments',
  82. ),
  83. );
  84. /** Remove extensions and hooks from a previous initialisation */
  85. private static function reset(): void {
  86. $hadAny = !empty(self::$ext_list_enabled);
  87. self::$ext_list = [];
  88. self::$ext_list_enabled = [];
  89. self::$ext_auto_enabled = [];
  90. foreach (self::$hook_list as $hook_type => $hook_data) {
  91. $hadAny |= !empty($hook_data['list']);
  92. $hook_data['list'] = [];
  93. self::$hook_list[$hook_type] = $hook_data;
  94. }
  95. if ($hadAny) {
  96. gc_collect_cycles();
  97. }
  98. }
  99. /**
  100. * Initialize the extension manager by loading extensions in EXTENSIONS_PATH.
  101. *
  102. * A valid extension is a directory containing metadata.json and
  103. * extension.php files.
  104. * metadata.json is a JSON structure where the only required fields are
  105. * `name` and `entry_point`.
  106. * extension.php should contain at least a class named <name>Extension where
  107. * <name> must match with the entry point in metadata.json. This class must
  108. * inherit from Minz_Extension class.
  109. */
  110. public static function init(): void {
  111. self::reset();
  112. $list_core_extensions = array_diff(scandir(CORE_EXTENSIONS_PATH) ?: [], [ '..', '.' ]);
  113. $list_thirdparty_extensions = array_diff(scandir(THIRDPARTY_EXTENSIONS_PATH) ?: [], [ '..', '.' ], $list_core_extensions);
  114. array_walk($list_core_extensions, function (&$s) { $s = CORE_EXTENSIONS_PATH . '/' . $s; });
  115. array_walk($list_thirdparty_extensions, function (&$s) { $s = THIRDPARTY_EXTENSIONS_PATH . '/' . $s; });
  116. /** @var array<string> */
  117. $list_potential_extensions = array_merge($list_core_extensions, $list_thirdparty_extensions);
  118. $system_conf = Minz_Configuration::get('system');
  119. self::$ext_auto_enabled = $system_conf->extensions_enabled;
  120. foreach ($list_potential_extensions as $ext_pathname) {
  121. if (!is_dir($ext_pathname)) {
  122. continue;
  123. }
  124. $metadata_filename = $ext_pathname . '/' . self::$ext_metaname;
  125. // Try to load metadata file.
  126. if (!file_exists($metadata_filename)) {
  127. // No metadata file? Invalid!
  128. continue;
  129. }
  130. $meta_raw_content = file_get_contents($metadata_filename) ?: '';
  131. /** @var array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'}|null */
  132. $meta_json = json_decode($meta_raw_content, true);
  133. if (!$meta_json || !self::isValidMetadata($meta_json)) {
  134. // metadata.json is not a json file? Invalid!
  135. // or metadata.json is invalid (no required information), invalid!
  136. Minz_Log::warning('`' . $metadata_filename . '` is not a valid metadata file');
  137. continue;
  138. }
  139. $meta_json['path'] = $ext_pathname;
  140. // Try to load extension itself
  141. $extension = self::load($meta_json);
  142. if ($extension != null) {
  143. self::register($extension);
  144. }
  145. }
  146. }
  147. /**
  148. * Indicates if the given parameter is a valid metadata array.
  149. *
  150. * Required fields are:
  151. * - `name`: the name of the extension
  152. * - `entry_point`: a class name to load the extension source code
  153. * If the extension class name is `TestExtension`, entry point will be `Test`.
  154. * `entry_point` must be composed of alphanumeric characters.
  155. *
  156. * @param array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'} $meta
  157. * is an array of values.
  158. * @return bool true if the array is valid, false else.
  159. */
  160. private static function isValidMetadata(array $meta): bool {
  161. $valid_chars = array('_');
  162. return !(empty($meta['name']) || empty($meta['entrypoint']) || !ctype_alnum(str_replace($valid_chars, '', $meta['entrypoint'])));
  163. }
  164. /**
  165. * Load the extension source code based on info metadata.
  166. *
  167. * @param array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'} $info
  168. * an array containing information about extension.
  169. * @return Minz_Extension|null an extension inheriting from Minz_Extension.
  170. */
  171. private static function load(array $info): ?Minz_Extension {
  172. $entry_point_filename = $info['path'] . '/' . self::$ext_entry_point;
  173. $ext_class_name = $info['entrypoint'] . 'Extension';
  174. include_once($entry_point_filename);
  175. // Test if the given extension class exists.
  176. if (!class_exists($ext_class_name)) {
  177. Minz_Log::warning("`{$ext_class_name}` cannot be found in `{$entry_point_filename}`");
  178. return null;
  179. }
  180. // Try to load the class.
  181. $extension = null;
  182. try {
  183. $extension = new $ext_class_name($info);
  184. } catch (Exception $e) {
  185. // We cannot load the extension? Invalid!
  186. Minz_Log::warning("Invalid extension `{$ext_class_name}`: " . $e->getMessage());
  187. return null;
  188. }
  189. // Test if class is correct.
  190. if (!($extension instanceof Minz_Extension)) {
  191. Minz_Log::warning("`{$ext_class_name}` is not an instance of `Minz_Extension`");
  192. return null;
  193. }
  194. return $extension;
  195. }
  196. /**
  197. * Add the extension to the list of the known extensions ($ext_list).
  198. *
  199. * If the extension is present in $ext_auto_enabled and if its type is "system",
  200. * it will be enabled at the same time.
  201. *
  202. * @param Minz_Extension $ext a valid extension.
  203. */
  204. private static function register(Minz_Extension $ext): void {
  205. $name = $ext->getName();
  206. self::$ext_list[$name] = $ext;
  207. if ($ext->getType() === 'system' && !empty(self::$ext_auto_enabled[$name])) {
  208. self::enable($ext->getName(), 'system');
  209. }
  210. }
  211. /**
  212. * Enable an extension so it will be called when necessary.
  213. *
  214. * The extension init() method will be called.
  215. *
  216. * @param string $ext_name is the name of a valid extension present in $ext_list.
  217. * @param 'system'|'user'|null $onlyOfType only enable if the extension matches that type. Set to null to load all.
  218. */
  219. private static function enable(string $ext_name, ?string $onlyOfType = null): void {
  220. if (isset(self::$ext_list[$ext_name])) {
  221. $ext = self::$ext_list[$ext_name];
  222. if ($onlyOfType !== null && $ext->getType() !== $onlyOfType) {
  223. // Do not enable an extension of the wrong type
  224. return;
  225. }
  226. self::$ext_list_enabled[$ext_name] = $ext;
  227. if (method_exists($ext, 'autoload')) {
  228. spl_autoload_register([$ext, 'autoload']);
  229. }
  230. $ext->enable();
  231. $ext->init();
  232. }
  233. }
  234. /**
  235. * Enable a list of extensions.
  236. *
  237. * @param array<string,bool> $ext_list the names of extensions we want to load.
  238. * @param 'system'|'user'|null $onlyOfType limit the extensions to load to those of those type. Set to null string to load all.
  239. */
  240. public static function enableByList(?array $ext_list, ?string $onlyOfType = null): void {
  241. if (empty($ext_list)) {
  242. return;
  243. }
  244. foreach ($ext_list as $ext_name => $ext_status) {
  245. if ($ext_status) {
  246. self::enable($ext_name, $onlyOfType);
  247. }
  248. }
  249. }
  250. /**
  251. * Return a list of extensions.
  252. *
  253. * @param bool $only_enabled if true returns only the enabled extensions (false by default).
  254. * @return Minz_Extension[] an array of extensions.
  255. */
  256. public static function listExtensions(bool $only_enabled = false): array {
  257. if ($only_enabled) {
  258. return self::$ext_list_enabled;
  259. } else {
  260. return self::$ext_list;
  261. }
  262. }
  263. /**
  264. * Return an extension by its name.
  265. *
  266. * @param string $ext_name the name of the extension.
  267. * @return Minz_Extension|null the corresponding extension or null if it doesn't exist.
  268. */
  269. public static function findExtension(string $ext_name): ?Minz_Extension {
  270. if (!isset(self::$ext_list[$ext_name])) {
  271. return null;
  272. }
  273. return self::$ext_list[$ext_name];
  274. }
  275. /**
  276. * Add a hook function to a given hook.
  277. *
  278. * The hook name must be a valid one. For the valid list, see self::$hook_list
  279. * array keys.
  280. *
  281. * @param string $hook_name the hook name (must exist).
  282. * @param callable $hook_function the function name to call (must be callable).
  283. */
  284. public static function addHook(string $hook_name, $hook_function): void {
  285. if (isset(self::$hook_list[$hook_name]) && is_callable($hook_function)) {
  286. self::$hook_list[$hook_name]['list'][] = $hook_function;
  287. }
  288. }
  289. /**
  290. * Call functions related to a given hook.
  291. *
  292. * The hook name must be a valid one. For the valid list, see self::$hook_list
  293. * array keys.
  294. *
  295. * @param string $hook_name the hook to call.
  296. * @param mixed ...$args additional parameters (for signature, please see self::$hook_list).
  297. * @return mixed|void|null final result of the called hook.
  298. */
  299. public static function callHook(string $hook_name, ...$args) {
  300. if (!isset(self::$hook_list[$hook_name])) {
  301. return;
  302. }
  303. $signature = self::$hook_list[$hook_name]['signature'];
  304. if ($signature === 'OneToOne') {
  305. return self::callOneToOne($hook_name, $args[0] ?? null);
  306. } elseif ($signature === 'PassArguments') {
  307. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  308. call_user_func($function, ...$args);
  309. }
  310. } elseif ($signature === 'NoneToString') {
  311. return self::callNoneToString($hook_name);
  312. } elseif ($signature === 'NoneToNone') {
  313. self::callNoneToNone($hook_name);
  314. }
  315. return;
  316. }
  317. /**
  318. * Call a hook which takes one argument and return a result.
  319. *
  320. * The result is chained between the extension, for instance, first extension
  321. * hook will receive the initial argument and return a result which will be
  322. * passed as an argument to the next extension hook and so on.
  323. *
  324. * If a hook return a null value, the method is stopped and return null.
  325. *
  326. * @param string $hook_name is the hook to call.
  327. * @param mixed $arg is the argument to pass to the first extension hook.
  328. * @return mixed|null final chained result of the hooks. If nothing is changed,
  329. * the initial argument is returned.
  330. */
  331. private static function callOneToOne(string $hook_name, $arg) {
  332. $result = $arg;
  333. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  334. $result = call_user_func($function, $arg);
  335. if ($result === null) {
  336. break;
  337. }
  338. $arg = $result;
  339. }
  340. return $result;
  341. }
  342. /**
  343. * Call a hook which takes no argument and returns a string.
  344. *
  345. * The result is concatenated between each hook and the final string is
  346. * returned.
  347. *
  348. * @param string $hook_name is the hook to call.
  349. * @return string concatenated result of the call to all the hooks.
  350. */
  351. private static function callNoneToString(string $hook_name): string {
  352. $result = '';
  353. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  354. $result = $result . call_user_func($function);
  355. }
  356. return $result;
  357. }
  358. /**
  359. * Call a hook which takes no argument and returns nothing.
  360. *
  361. * This case is simpler than callOneToOne because hooks are called one by
  362. * one, without any consideration of argument nor result.
  363. *
  364. * @param string $hook_name is the hook to call.
  365. */
  366. private static function callNoneToNone(string $hook_name): void {
  367. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  368. call_user_func($function);
  369. }
  370. }
  371. }