ExtensionManager.php 11 KB

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