ExtensionManager.php 16 KB

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