ExtensionManager.php 12 KB

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