ExtensionManager.php 14 KB

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