ExtensionManager.php 13 KB

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