3 namespace Shaarli\Plugin
;
5 use Shaarli\Bookmark\Bookmark
;
6 use Shaarli\Config\ConfigManager
;
7 use Shaarli\Plugin\Exception\PluginFileNotFoundException
;
8 use Shaarli\Plugin\Exception\PluginInvalidRouteException
;
13 * Use to manage, load and execute plugins.
18 * List of authorized plugins from configuration file.
20 * @var array $authorizedPlugins
22 private $authorizedPlugins = [];
25 * List of loaded plugins.
27 * @var array $loadedPlugins
29 private $loadedPlugins = [];
31 /** @var array List of registered routes. Contains keys:
32 * - `method`: HTTP method, GET/POST/PUT/PATCH/DELETE
33 * - `route` (path): without prefix, e.g. `/up/{variable}`
34 * It will be later prefixed by `/plugin/<plugin name>/`.
35 * - `callable` string, function name or FQN class's method, e.g. `demo_plugin_custom_controller`.
37 protected $registeredRoutes = [];
40 * @var ConfigManager Configuration Manager instance.
45 * @var array List of plugin errors.
49 /** @var callable[]|null Preloaded list of hook function for filterSearchEntry() */
50 protected $filterSearchEntryHooks = null;
53 * Plugins subdirectory.
55 * @var string $PLUGINS_PATH
57 public static $PLUGINS_PATH = 'plugins';
60 * Plugins meta files extension.
62 * @var string $META_EXT
64 public static $META_EXT = 'meta';
69 * @param ConfigManager $conf Configuration Manager instance.
71 public function __construct(&$conf)
78 * Load plugins listed in $authorizedPlugins.
80 * @param array $authorizedPlugins Names of plugin authorized to be loaded.
84 public function load($authorizedPlugins)
86 $this->authorizedPlugins
= $authorizedPlugins;
88 $dirs = glob(self
::$PLUGINS_PATH . '/*', GLOB_ONLYDIR
);
89 $dirnames = array_map('basename', $dirs);
90 foreach ($this->authorizedPlugins
as $plugin) {
91 $index = array_search($plugin, $dirnames);
93 // plugin authorized, but its folder isn't listed
94 if ($index === false) {
99 $this->loadPlugin($dirs[$index], $plugin);
100 } catch (PluginFileNotFoundException
$e) {
101 error_log($e->getMessage());
102 } catch (\Throwable
$e) {
103 $error = $plugin . t(' [plugin incompatibility]: ') . $e->getMessage();
104 $this->errors
= array_unique(array_merge($this->errors
, [$error]));
110 * Execute all plugins registered hook.
112 * @param string $hook name of the hook to trigger.
113 * @param array $data list of data to manipulate passed by reference.
114 * @param array $params additional parameters such as page target.
118 public function executeHooks($hook, &$data, $params = [])
120 $metadataParameters = [
121 'target' => '_PAGE_',
122 'loggedin' => '_LOGGEDIN_',
123 'basePath' => '_BASE_PATH_',
124 'rootPath' => '_ROOT_PATH_',
125 'bookmarkService' => '_BOOKMARK_SERVICE_',
128 foreach ($metadataParameters as $parameter => $metaKey) {
129 if (array_key_exists($parameter, $params)) {
130 $data[$metaKey] = $params[$parameter];
134 foreach ($this->loadedPlugins
as $plugin) {
135 $hookFunction = $this->buildHookName($hook, $plugin);
137 if (function_exists($hookFunction)) {
139 $data = call_user_func($hookFunction, $data, $this->conf
);
140 } catch (\Throwable
$e) {
141 $error = $plugin . t(' [plugin incompatibility]: ') . $e->getMessage();
142 $this->errors
= array_unique(array_merge($this->errors
, [$error]));
147 foreach ($metadataParameters as $metaKey) {
148 unset($data[$metaKey]);
153 * Load a single plugin from its files.
154 * Call the init function if it exists, and collect errors.
155 * Add them in $loadedPlugins if successful.
157 * @param string $dir plugin's directory.
158 * @param string $pluginName plugin's name.
161 * @throws \Shaarli\Plugin\Exception\PluginFileNotFoundException - plugin files not found.
163 private function loadPlugin($dir, $pluginName)
166 throw new PluginFileNotFoundException($pluginName);
169 $pluginFilePath = $dir . '/' . $pluginName . '.php';
170 if (!is_file($pluginFilePath)) {
171 throw new PluginFileNotFoundException($pluginName);
175 include_once $pluginFilePath;
177 $initFunction = $pluginName . '_init';
178 if (function_exists($initFunction)) {
179 $errors = call_user_func($initFunction, $this->conf
);
180 if (!empty($errors)) {
181 $this->errors
= array_merge($this->errors
, $errors);
185 $registerRouteFunction = $pluginName . '_register_routes';
187 if (function_exists($registerRouteFunction)) {
188 $routes = call_user_func($registerRouteFunction);
191 if ($routes !== null) {
192 foreach ($routes as $route) {
193 if (static::validateRouteRegistration($route)) {
194 $this->registeredRoutes
[$pluginName][] = $route;
196 throw new PluginInvalidRouteException($pluginName);
201 $this->loadedPlugins
[] = $pluginName;
205 * Construct normalize hook name for a specific plugin.
208 * hook_<plugin_name>_<hook_name>
210 * @param string $hook hook name.
211 * @param string $pluginName plugin name.
213 * @return string - plugin's hook name.
215 public function buildHookName($hook, $pluginName)
217 return 'hook_' . $pluginName . '_' . $hook;
221 * Retrieve plugins metadata from *.meta (INI) files into an array.
223 * - plugin description [description]
224 * - parameters split with ';' [parameters]
226 * Respects plugins order from settings.
228 * @return array plugins metadata.
230 public function getPluginsMeta()
233 $dirs = glob(self
::$PLUGINS_PATH . '/*', GLOB_ONLYDIR
| GLOB_MARK
);
235 // Browse all plugin directories.
236 foreach ($dirs as $pluginDir) {
237 $plugin = basename($pluginDir);
238 $metaFile = $pluginDir . $plugin . '.' . self
::$META_EXT;
239 if (!is_file($metaFile) || !is_readable($metaFile)) {
243 $metaData[$plugin] = parse_ini_file($metaFile);
244 $metaData[$plugin]['order'] = array_search($plugin, $this->authorizedPlugins
);
246 if (isset($metaData[$plugin]['description'])) {
247 $metaData[$plugin]['description'] = t($metaData[$plugin]['description']);
249 // Read parameters and format them into an array.
250 if (isset($metaData[$plugin]['parameters'])) {
251 $params = explode(';', $metaData[$plugin]['parameters']);
255 $metaData[$plugin]['parameters'] = [];
256 foreach ($params as $param) {
261 $metaData[$plugin]['parameters'][$param]['value'] = '';
262 // Optional parameter description in parameter.PARAM_NAME=
263 if (isset($metaData[$plugin]['parameter.' . $param])) {
264 $metaData[$plugin]['parameters'][$param]['desc'] = t($metaData[$plugin]['parameter.' . $param]);
273 * @return array List of registered custom routes by plugins.
275 public function getRegisteredRoutes(): array
277 return $this->registeredRoutes
;
281 * @return array List of registered filter_search_entry hooks
283 public function getFilterSearchEntryHooks(): ?array
285 return $this->filterSearchEntryHooks
;
289 * Return the list of encountered errors.
291 * @return array List of errors (empty array if none exists).
293 public function getErrors()
295 return $this->errors
;
299 * Apply additional filter on every search result of BookmarkFilter calling plugins hooks.
301 * @param Bookmark $bookmark To check.
302 * @param array $context Additional info about search context, depends on the search source.
304 * @return bool True if the result must be kept in search results, false otherwise.
306 public function filterSearchEntry(Bookmark
$bookmark, array $context): bool
308 if ($this->filterSearchEntryHooks
=== null) {
309 $this->loadFilterSearchEntryHooks();
312 if ($this->filterSearchEntryHooks
=== []) {
316 foreach ($this->filterSearchEntryHooks
as $filterSearchEntryHook) {
317 if ($filterSearchEntryHook($bookmark, $context) === false) {
326 * filterSearchEntry() method will be called for every search result,
327 * so for performances we preload existing functions to invoke them directly.
329 protected function loadFilterSearchEntryHooks(): void
331 $this->filterSearchEntryHooks
= [];
333 foreach ($this->loadedPlugins
as $plugin) {
334 $hookFunction = $this->buildHookName('filter_search_entry', $plugin);
336 if (function_exists($hookFunction)) {
337 $this->filterSearchEntryHooks
[] = $hookFunction;
343 * Checks whether provided input is valid to register a new route.
344 * It must contain keys `method`, `route`, `callable` (all strings).
346 * @param string[] $input
350 protected static function validateRouteRegistration(array $input): bool
353 !array_key_exists('method', $input)
354 || !in_array(strtoupper($input['method']), ['GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
359 if (!array_key_exists('route', $input) || !preg_match('#^[a-z\d/\.\-_]+$#', $input['route'])) {
363 if (!array_key_exists('callable', $input)) {