ExtensionManager.php 8.7 KB

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