3 namespace Shaarli\Plugin
;
5 use Shaarli\Config\ConfigManager
;
6 use Shaarli\Plugin\Exception\PluginFileNotFoundException
;
7 use Shaarli\Plugin\Exception\PluginInvalidRouteException
;
12 * Use to manage, load and execute plugins.
17 * List of authorized plugins from configuration file.
19 * @var array $authorizedPlugins
21 private $authorizedPlugins = [];
24 * List of loaded plugins.
26 * @var array $loadedPlugins
28 private $loadedPlugins = [];
30 /** @var array List of registered routes. Contains keys:
31 * - `method`: HTTP method, GET/POST/PUT/PATCH/DELETE
32 * - `route` (path): without prefix, e.g. `/up/{variable}`
33 * It will be later prefixed by `/plugin/<plugin name>/`.
34 * - `callable` string, function name or FQN class's method, e.g. `demo_plugin_custom_controller`.
36 protected $registeredRoutes = [];
39 * @var ConfigManager Configuration Manager instance.
44 * @var array List of plugin errors.
49 * Plugins subdirectory.
51 * @var string $PLUGINS_PATH
53 public static $PLUGINS_PATH = 'plugins';
56 * Plugins meta files extension.
58 * @var string $META_EXT
60 public static $META_EXT = 'meta';
65 * @param ConfigManager $conf Configuration Manager instance.
67 public function __construct(&$conf)
74 * Load plugins listed in $authorizedPlugins.
76 * @param array $authorizedPlugins Names of plugin authorized to be loaded.
80 public function load($authorizedPlugins)
82 $this->authorizedPlugins
= $authorizedPlugins;
84 $dirs = glob(self
::$PLUGINS_PATH . '/*', GLOB_ONLYDIR
);
85 $dirnames = array_map('basename', $dirs);
86 foreach ($this->authorizedPlugins
as $plugin) {
87 $index = array_search($plugin, $dirnames);
89 // plugin authorized, but its folder isn't listed
90 if ($index === false) {
95 $this->loadPlugin($dirs[$index], $plugin);
96 } catch (PluginFileNotFoundException
$e) {
97 error_log($e->getMessage());
98 } catch (\Throwable
$e) {
99 $error = $plugin . t(' [plugin incompatibility]: ') . $e->getMessage();
100 $this->errors
= array_unique(array_merge($this->errors
, [$error]));
106 * Execute all plugins registered hook.
108 * @param string $hook name of the hook to trigger.
109 * @param array $data list of data to manipulate passed by reference.
110 * @param array $params additional parameters such as page target.
114 public function executeHooks($hook, &$data, $params = [])
116 $metadataParameters = [
117 'target' => '_PAGE_',
118 'loggedin' => '_LOGGEDIN_',
119 'basePath' => '_BASE_PATH_',
120 'rootPath' => '_ROOT_PATH_',
121 'bookmarkService' => '_BOOKMARK_SERVICE_',
124 foreach ($metadataParameters as $parameter => $metaKey) {
125 if (array_key_exists($parameter, $params)) {
126 $data[$metaKey] = $params[$parameter];
130 foreach ($this->loadedPlugins
as $plugin) {
131 $hookFunction = $this->buildHookName($hook, $plugin);
133 if (function_exists($hookFunction)) {
135 $data = call_user_func($hookFunction, $data, $this->conf
);
136 } catch (\Throwable
$e) {
137 $error = $plugin . t(' [plugin incompatibility]: ') . $e->getMessage();
138 $this->errors
= array_unique(array_merge($this->errors
, [$error]));
143 foreach ($metadataParameters as $metaKey) {
144 unset($data[$metaKey]);
149 * Load a single plugin from its files.
150 * Call the init function if it exists, and collect errors.
151 * Add them in $loadedPlugins if successful.
153 * @param string $dir plugin's directory.
154 * @param string $pluginName plugin's name.
157 * @throws \Shaarli\Plugin\Exception\PluginFileNotFoundException - plugin files not found.
159 private function loadPlugin($dir, $pluginName)
162 throw new PluginFileNotFoundException($pluginName);
165 $pluginFilePath = $dir . '/' . $pluginName . '.php';
166 if (!is_file($pluginFilePath)) {
167 throw new PluginFileNotFoundException($pluginName);
171 include_once $pluginFilePath;
173 $initFunction = $pluginName . '_init';
174 if (function_exists($initFunction)) {
175 $errors = call_user_func($initFunction, $this->conf
);
176 if (!empty($errors)) {
177 $this->errors
= array_merge($this->errors
, $errors);
181 $registerRouteFunction = $pluginName . '_register_routes';
183 if (function_exists($registerRouteFunction)) {
184 $routes = call_user_func($registerRouteFunction);
187 if ($routes !== null) {
188 foreach ($routes as $route) {
189 if (static::validateRouteRegistration($route)) {
190 $this->registeredRoutes
[$pluginName][] = $route;
192 throw new PluginInvalidRouteException($pluginName);
197 $this->loadedPlugins
[] = $pluginName;
201 * Construct normalize hook name for a specific plugin.
204 * hook_<plugin_name>_<hook_name>
206 * @param string $hook hook name.
207 * @param string $pluginName plugin name.
209 * @return string - plugin's hook name.
211 public function buildHookName($hook, $pluginName)
213 return 'hook_' . $pluginName . '_' . $hook;
217 * Retrieve plugins metadata from *.meta (INI) files into an array.
219 * - plugin description [description]
220 * - parameters split with ';' [parameters]
222 * Respects plugins order from settings.
224 * @return array plugins metadata.
226 public function getPluginsMeta()
229 $dirs = glob(self
::$PLUGINS_PATH . '/*', GLOB_ONLYDIR
| GLOB_MARK
);
231 // Browse all plugin directories.
232 foreach ($dirs as $pluginDir) {
233 $plugin = basename($pluginDir);
234 $metaFile = $pluginDir . $plugin . '.' . self
::$META_EXT;
235 if (!is_file($metaFile) || !is_readable($metaFile)) {
239 $metaData[$plugin] = parse_ini_file($metaFile);
240 $metaData[$plugin]['order'] = array_search($plugin, $this->authorizedPlugins
);
242 if (isset($metaData[$plugin]['description'])) {
243 $metaData[$plugin]['description'] = t($metaData[$plugin]['description']);
245 // Read parameters and format them into an array.
246 if (isset($metaData[$plugin]['parameters'])) {
247 $params = explode(';', $metaData[$plugin]['parameters']);
251 $metaData[$plugin]['parameters'] = [];
252 foreach ($params as $param) {
257 $metaData[$plugin]['parameters'][$param]['value'] = '';
258 // Optional parameter description in parameter.PARAM_NAME=
259 if (isset($metaData[$plugin]['parameter.' . $param])) {
260 $metaData[$plugin]['parameters'][$param]['desc'] = t($metaData[$plugin]['parameter.' . $param]);
269 * @return array List of registered custom routes by plugins.
271 public function getRegisteredRoutes(): array
273 return $this->registeredRoutes
;
277 * Return the list of encountered errors.
279 * @return array List of errors (empty array if none exists).
281 public function getErrors()
283 return $this->errors
;
287 * Checks whether provided input is valid to register a new route.
288 * It must contain keys `method`, `route`, `callable` (all strings).
290 * @param string[] $input
294 protected static function validateRouteRegistration(array $input): bool
297 !array_key_exists('method', $input)
298 || !in_array(strtoupper($input['method']), ['GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
303 if (!array_key_exists('route', $input) || !preg_match('#^[a-z\d/\.\-_]+$#', $input['route'])) {
307 if (!array_key_exists('callable', $input)) {