ExtensionManager.php 14 KB

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