ExtensionManager.php 15 KB

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