ExtensionManager.php 9.6 KB

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