ExtensionManager.php 13 KB

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