ExtensionManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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<callable>,'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 the hook name (must exist).
  230. * @param callable $hook_function the function name to call (must be callable).
  231. */
  232. public static function addHook(string|Minz_HookType $hook, $hook_function): void {
  233. if (null === $hook = self::extractHook($hook)) {
  234. return;
  235. }
  236. $hook_name = $hook->value;
  237. if (is_callable($hook_function)) {
  238. self::$hook_list[$hook_name]['list'][] = $hook_function;
  239. }
  240. }
  241. /**
  242. * @param string|Minz_HookType $hook the hook or its name
  243. * @return Minz_HookType|null
  244. */
  245. private static function extractHook(string|Minz_HookType $hook) {
  246. if ($hook instanceof Minz_HookType) {
  247. return $hook;
  248. }
  249. return Minz_HookType::tryFrom($hook);
  250. }
  251. /**
  252. * Call functions related to a given hook.
  253. *
  254. * The hook name must be a valid one. For the valid list, see Minz_HookType enum.
  255. *
  256. * @param string|Minz_HookType $hook the hook to call.
  257. * @param mixed ...$args additional parameters (for signature, please see Minz_HookType enum).
  258. * @return mixed|void|null final result of the called hook.
  259. */
  260. public static function callHook(string|Minz_HookType $hook, ...$args) {
  261. if (null === $hook = self::extractHook($hook)) {
  262. return;
  263. }
  264. $hook_name = $hook->value;
  265. $signature = self::$hook_list[$hook_name]['signature'];
  266. if ($signature === Minz_HookSignature::OneToOne) {
  267. return self::callOneToOne($hook_name, $args[0] ?? null);
  268. } elseif ($signature === Minz_HookSignature::PassArguments) {
  269. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  270. $result = call_user_func($function, ...$args);
  271. if ($result !== null) {
  272. return $result;
  273. }
  274. }
  275. } elseif ($signature === Minz_HookSignature::NoneToString) {
  276. return self::callHookString($hook_name);
  277. } elseif ($signature === Minz_HookSignature::NoneToNone) {
  278. self::callHookVoid($hook_name);
  279. }
  280. return;
  281. }
  282. /**
  283. * Call a hook which takes one argument and return a result.
  284. *
  285. * The result is chained between the extension, for instance, first extension
  286. * hook will receive the initial argument and return a result which will be
  287. * passed as an argument to the next extension hook and so on.
  288. *
  289. * If a hook return a null value, the method is stopped and return null.
  290. *
  291. * @param string|Minz_HookType $hook is the hook to call.
  292. * @param mixed $arg is the argument to pass to the first extension hook.
  293. * @return mixed|null final chained result of the hooks. If nothing is changed,
  294. * the initial argument is returned.
  295. */
  296. private static function callOneToOne(string|Minz_HookType $hook, mixed $arg): mixed {
  297. if (null === $hook = self::extractHook($hook)) {
  298. return $arg;
  299. }
  300. $hook_name = $hook->value;
  301. $result = $arg;
  302. foreach (self::$hook_list[$hook_name]['list'] as $function) {
  303. $result = call_user_func($function, $arg);
  304. if ($result === null) {
  305. break;
  306. }
  307. $arg = $result;
  308. }
  309. return $result;
  310. }
  311. /**
  312. * Call a hook which takes no argument and returns a string.
  313. *
  314. * The result is concatenated between each hook and the final string is
  315. * returned.
  316. *
  317. * @param string|Minz_HookType $hook is the hook to call.
  318. * @return string concatenated result of the call to all the hooks.
  319. */
  320. public static function callHookString(string|Minz_HookType $hook): string {
  321. if (null === $hook = self::extractHook($hook)) {
  322. return '';
  323. }
  324. $hook_name = $hook->value;
  325. $result = '';
  326. foreach (self::$hook_list[$hook_name]['list'] ?? [] as $function) {
  327. $return = call_user_func($function);
  328. if (is_scalar($return)) {
  329. $result .= $return;
  330. }
  331. }
  332. return $result;
  333. }
  334. /**
  335. * Call a hook which takes no argument and returns nothing.
  336. *
  337. * This case is simpler than callOneToOne because hooks are called one by
  338. * one, without any consideration of argument nor result.
  339. *
  340. * @param string|Minz_HookType $hook is the hook to call.
  341. */
  342. public static function callHookVoid(string|Minz_HookType $hook): void {
  343. if (null === $hook = self::extractHook($hook)) {
  344. return;
  345. }
  346. $hook_name = $hook->value;
  347. foreach (self::$hook_list[$hook_name]['list'] ?? [] as $function) {
  348. call_user_func($function);
  349. }
  350. }
  351. /**
  352. * Call a hook which takes no argument and returns nothing.
  353. * Same as callHookVoid but only calls the first extension.
  354. *
  355. * @param string|Minz_HookType $hook is the hook to call.
  356. */
  357. public static function callHookUnique(string|Minz_HookType $hook): bool {
  358. if (null === $hook = self::extractHook($hook)) {
  359. throw new \RuntimeException("The “{$hook}” does not exist!");
  360. }
  361. $hook_name = $hook->value;
  362. foreach (self::$hook_list[$hook_name]['list'] ?? [] as $function) {
  363. call_user_func($function);
  364. return true;
  365. }
  366. return false;
  367. }
  368. /**
  369. * Check if a extension is enabled
  370. *
  371. * @param string $ext_name is the extension's name as provided in metadata.json
  372. */
  373. public static function isExtensionEnabled(string $ext_name): bool {
  374. return isset(self::$ext_list_enabled[$ext_name]);
  375. }
  376. }