ExtensionManager.php 14 KB

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