ExtensionManager.php 8.6 KB

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