ExtensionManager.php 9.0 KB

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