ExtensionManager.php 15 KB

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