diff options
| author | 2023-04-04 10:23:26 +0200 | |
|---|---|---|
| committer | 2023-04-04 10:23:26 +0200 | |
| commit | 36aa0122e15b6c5a4bf923467b63a577cac5a539 (patch) | |
| tree | 3dc7d2c5143157165f0248fab7470f86f76b0898 | |
| parent | 2340f7a1bac38647f0267c1d7143c0cf04d68fcc (diff) | |
Fix extensions in actualize_script (#5243)
* Fix extension freshrss_user_maintenance in actualize_script
Follow-up of https://github.com/FreshRSS/FreshRSS/pull/3440
The hook was called before registering all the extensions for the current user
* PHPStan Level 6 for extensions
And remove 5-year old legacy format of enabled extensions < FreshRSS 1.11.1
* Fix multiple bugs in extensions
* Minor typing
* Don't change signature of methods supposed to be overridden
* PHPStan Level 9 and compatibility Intelliphense
* Set as final the methods not supposed to be overriden
| -rw-r--r-- | app/Controllers/extensionController.php | 88 | ||||
| -rw-r--r-- | app/Controllers/feedController.php | 2 | ||||
| -rw-r--r-- | app/Controllers/updateController.php | 2 | ||||
| -rw-r--r-- | app/FreshRSS.php | 2 | ||||
| -rw-r--r-- | app/Models/View.php | 5 | ||||
| -rwxr-xr-x | app/actualize_script.php | 18 | ||||
| -rw-r--r-- | cli/_cli.php | 2 | ||||
| -rw-r--r-- | lib/Minz/ActionController.php | 6 | ||||
| -rw-r--r-- | lib/Minz/Configuration.php | 20 | ||||
| -rw-r--r-- | lib/Minz/Extension.php | 135 | ||||
| -rw-r--r-- | lib/Minz/ExtensionManager.php | 97 | ||||
| -rw-r--r-- | lib/Minz/Request.php | 28 | ||||
| -rw-r--r-- | lib/core-extensions/Google-Groups/extension.php | 3 | ||||
| -rw-r--r-- | lib/core-extensions/Tumblr-GDPR/extension.php | 3 | ||||
| -rw-r--r-- | p/api/greader.php | 2 | ||||
| -rw-r--r-- | p/api/pshb.php | 2 | ||||
| -rw-r--r-- | tests/phpstan-next.txt | 5 |
17 files changed, 252 insertions, 168 deletions
diff --git a/app/Controllers/extensionController.php b/app/Controllers/extensionController.php index d1ea889aa..b482b1a35 100644 --- a/app/Controllers/extensionController.php +++ b/app/Controllers/extensionController.php @@ -9,7 +9,7 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { * the common boiler plate for every action. It is triggered by the * underlying framework. */ - public function firstAction() { + public function firstAction(): void { if (!FreshRSS_Auth::hasAccess()) { Minz_Error::error(403); } @@ -18,7 +18,7 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { /** * This action lists all the extensions available to the current user. */ - public function indexAction() { + public function indexAction(): void { FreshRSS_View::prependTitle(_t('admin.extensions.title') . ' · '); $this->view->extension_list = array( 'system' => array(), @@ -33,14 +33,14 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { $this->view->extensions_installed[$ext->getEntrypoint()] = $ext->getVersion(); } - $availableExtensions = $this->getAvailableExtensionList(); - $this->view->available_extensions = $availableExtensions; + $this->view->available_extensions = $this->getAvailableExtensionList(); } /** * fetch extension list from GitHub + * @return array<string,array{'name':string,'author':string,'description':string,'version':string,'entrypoint':string,'type':'system'|'user','url':string,'method':string,'directory':string}> */ - protected function getAvailableExtensionList() { + protected function getAvailableExtensionList(): array { $extensionListUrl = 'https://raw.githubusercontent.com/FreshRSS/Extensions/master/extensions.json'; $json = @file_get_contents($extensionListUrl); @@ -51,18 +51,17 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { } // fetch the list as an array + /** @var array<string,mixed> */ $list = json_decode($json, true); if (empty($list)) { Minz_Log::warning('Failed to convert extension file list'); return array(); } - // we could use that for comparing and caching later - $version = $list['version']; - // By now, all the needed data is kept in the main extension file. // In the future we could fetch detail information from the extensions metadata.json, but I tend to stick with // the current implementation for now, unless it becomes too much effort maintain the extension list manually + /** @var array<string,array{'name':string,'author':string,'description':string,'version':string,'entrypoint':string,'type':'system'|'user','url':string,'method':string,'directory':string}> */ $extensions = $list['extensions']; return $extensions; @@ -78,22 +77,24 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { * - additional parameters which should be handle by the extension * handleConfigureAction() method (POST request). */ - public function configureAction() { - if (Minz_Request::param('ajax')) { + public function configureAction(): void { + if (Minz_Request::paramBoolean('ajax')) { $this->view->_layout(false); } else { $this->indexAction(); $this->view->_path('extension/index.phtml'); } - $ext_name = urldecode(Minz_Request::param('e')); + $ext_name = urldecode(Minz_Request::paramString('e')); $ext = Minz_ExtensionManager::findExtension($ext_name); - if (is_null($ext)) { + if ($ext === null) { Minz_Error::error(404); + return; } if ($ext->getType() === 'system' && !FreshRSS_Auth::hasAccess('admin')) { Minz_Error::error(403); + return; } $this->view->extension = $ext; @@ -109,41 +110,52 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { * Parameter is: * - e: the extension name (urlencoded). */ - public function enableAction() { + public function enableAction(): void { $url_redirect = array('c' => 'extension', 'a' => 'index'); if (Minz_Request::isPost()) { - $ext_name = urldecode(Minz_Request::param('e')); + $ext_name = urldecode(Minz_Request::paramString('e')); $ext = Minz_ExtensionManager::findExtension($ext_name); if (is_null($ext)) { Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect); + return; } if ($ext->isEnabled()) { Minz_Request::bad(_t('feedback.extensions.already_enabled', $ext_name), $url_redirect); } + $type = $ext->getType(); + if ($type !== 'user' && !FreshRSS_Auth::hasAccess('admin')) { + Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect); + return; + } + $conf = null; - if ($ext->getType() === 'system' && FreshRSS_Auth::hasAccess('admin')) { + if ($type === 'system') { $conf = FreshRSS_Context::$system_conf; - } elseif ($ext->getType() === 'user') { + } elseif ($type === 'user') { $conf = FreshRSS_Context::$user_conf; - } else { - Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect); } $res = $ext->install(); - if ($res === true) { + if ($conf !== null && $res === true) { $ext_list = $conf->extensions_enabled; + $ext_list = array_filter($ext_list, function($key) use($type) { + // Remove from list the extensions that have disappeared or changed type + $extension = Minz_ExtensionManager::findExtension($key); + return $extension !== null && $extension->getType() === $type; + }, ARRAY_FILTER_USE_KEY); + $ext_list[$ext_name] = true; $conf->extensions_enabled = $ext_list; $conf->save(); Minz_Request::good(_t('feedback.extensions.enable.ok', $ext_name), $url_redirect); } else { - Minz_Log::warning('Can not enable extension ' . $ext_name . ': ' . $res); + Minz_Log::warning('Cannot enable extension ' . $ext_name . ': ' . $res); Minz_Request::bad(_t('feedback.extensions.enable.ko', $ext_name, _url('index', 'logs')), $url_redirect); } } @@ -160,45 +172,52 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { * Parameter is: * - e: the extension name (urlencoded). */ - public function disableAction() { + public function disableAction(): void { $url_redirect = array('c' => 'extension', 'a' => 'index'); if (Minz_Request::isPost()) { - $ext_name = urldecode(Minz_Request::param('e')); + $ext_name = urldecode(Minz_Request::paramString('e')); $ext = Minz_ExtensionManager::findExtension($ext_name); if (is_null($ext)) { Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect); + return; } if (!$ext->isEnabled()) { Minz_Request::bad(_t('feedback.extensions.not_enabled', $ext_name), $url_redirect); } + $type = $ext->getType(); + if ($type !== 'user' && !FreshRSS_Auth::hasAccess('admin')) { + Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect); + return; + } + $conf = null; - if ($ext->getType() === 'system' && FreshRSS_Auth::hasAccess('admin')) { + if ($type === 'system') { $conf = FreshRSS_Context::$system_conf; - } elseif ($ext->getType() === 'user') { + } elseif ($type === 'user') { $conf = FreshRSS_Context::$user_conf; - } else { - Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect); } $res = $ext->uninstall(); - if ($res === true) { + if ($conf !== null && $res === true) { $ext_list = $conf->extensions_enabled; - $legacyKey = array_search($ext_name, $ext_list, true); - if ($legacyKey !== false) { //Legacy format FreshRSS < 1.11.1 - unset($ext_list[$legacyKey]); - } + $ext_list = array_filter($ext_list, function($key) use($type) { + // Remove from list the extensions that have disappeared or changed type + $extension = Minz_ExtensionManager::findExtension($key); + return $extension !== null && $extension->getType() === $type; + }, ARRAY_FILTER_USE_KEY); + $ext_list[$ext_name] = false; $conf->extensions_enabled = $ext_list; $conf->save(); Minz_Request::good(_t('feedback.extensions.disable.ok', $ext_name), $url_redirect); } else { - Minz_Log::warning('Can not unable extension ' . $ext_name . ': ' . $res); + Minz_Log::warning('Cannot disable extension ' . $ext_name . ': ' . $res); Minz_Request::bad(_t('feedback.extensions.disable.ko', $ext_name, _url('index', 'logs')), $url_redirect); } } @@ -215,7 +234,7 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { * Parameter is: * -e: extension name (urlencoded) */ - public function removeAction() { + public function removeAction(): void { if (!FreshRSS_Auth::hasAccess('admin')) { Minz_Error::error(403); } @@ -223,11 +242,12 @@ class FreshRSS_extension_Controller extends FreshRSS_ActionController { $url_redirect = array('c' => 'extension', 'a' => 'index'); if (Minz_Request::isPost()) { - $ext_name = urldecode(Minz_Request::param('e')); + $ext_name = urldecode(Minz_Request::paramString('e')); $ext = Minz_ExtensionManager::findExtension($ext_name); if (is_null($ext)) { Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect); + return; } $res = recursive_unlink($ext->getPath()); diff --git a/app/Controllers/feedController.php b/app/Controllers/feedController.php index ade465c55..13fc3fd85 100644 --- a/app/Controllers/feedController.php +++ b/app/Controllers/feedController.php @@ -9,7 +9,7 @@ class FreshRSS_feed_Controller extends FreshRSS_ActionController { * the common boiler plate for every action. It is triggered by the * underlying framework. */ - public function firstAction() { + public function firstAction(): void { if (!FreshRSS_Auth::hasAccess()) { // Token is useful in the case that anonymous refresh is forbidden // and CRON task cannot be used with php command so the user can diff --git a/app/Controllers/updateController.php b/app/Controllers/updateController.php index f638ce96c..82ccd20c9 100644 --- a/app/Controllers/updateController.php +++ b/app/Controllers/updateController.php @@ -92,7 +92,7 @@ class FreshRSS_update_Controller extends FreshRSS_ActionController { return $return == 0 ? true : 'Git error: ' . $line; } - public function firstAction() { + public function firstAction(): void { if (!FreshRSS_Auth::hasAccess('admin')) { Minz_Error::error(403); } diff --git a/app/FreshRSS.php b/app/FreshRSS.php index dd16fad6c..2213c34ca 100644 --- a/app/FreshRSS.php +++ b/app/FreshRSS.php @@ -61,7 +61,7 @@ class FreshRSS extends Minz_FrontController { // Enable extensions for the current (logged) user. if (FreshRSS_Auth::hasAccess() || FreshRSS_Context::$system_conf->allow_anonymous) { $ext_list = FreshRSS_Context::$user_conf->extensions_enabled; - Minz_ExtensionManager::enableByList($ext_list); + Minz_ExtensionManager::enableByList($ext_list, 'user'); } if (FreshRSS_Context::$system_conf->force_email_validation && !FreshRSS_Auth::hasAccess('admin')) { diff --git a/app/Models/View.php b/app/Models/View.php index 309773c93..7e7afd124 100644 --- a/app/Models/View.php +++ b/app/Models/View.php @@ -114,10 +114,15 @@ class FreshRSS_View extends Minz_View { public $selectorSuccess; // Extensions + /** @var array<string,array{'name':string,'author':string,'description':string,'version':string,'entrypoint':string,'type':'system'|'user','url':string,'method':string,'directory':string}> */ public $available_extensions; + /** @var ?Minz_Extension */ public $ext_details; + /** @var array{'system':array<Minz_Extension>,'user':array<Minz_Extension>} */ public $extension_list; + /** @var ?Minz_Extension */ public $extension; + /** @var array<string,string> */ public $extensions_installed; // Errors diff --git a/app/actualize_script.php b/app/actualize_script.php index b4d57c4e3..4a38c13f7 100755 --- a/app/actualize_script.php +++ b/app/actualize_script.php @@ -18,6 +18,9 @@ $_SERVER['HTTP_HOST'] = ''; $app = new FreshRSS(); FreshRSS_Context::initSystem(); +if (FreshRSS_Context::$system_conf === null) { + throw new FreshRSS_Context_Exception('System configuration not initialised!'); +} FreshRSS_Context::$system_conf->auth_type = 'none'; // avoid necessity to be logged in (not saved!) define('SIMPLEPIE_SYSLOG_ENABLED', FreshRSS_Context::$system_conf->simplepie_syslog_enabled); @@ -54,11 +57,6 @@ fclose($handle); register_shutdown_function(function () use ($mutexFile) { unlink($mutexFile); }); - -Minz_ExtensionManager::addHook('feed_before_actualize', function ($feed) use ($mutexFile) { - touch($mutexFile); - return $feed; -}); // </Mutex> notice('FreshRSS starting feeds actualization at ' . $begin_date->format('c')); @@ -99,11 +97,17 @@ foreach ($users as $user) { FreshRSS_Auth::giveAccess(); - Minz_ExtensionManager::callHook('freshrss_user_maintenance'); - + // NB: Extensions and hooks are reinitialised there $app->init(); + + Minz_ExtensionManager::addHook('feed_before_actualize', function ($feed) use ($mutexFile) { + touch($mutexFile); + return $feed; + }); + notice('FreshRSS actualize ' . $user . '…'); echo $user, ' '; //Buffered + Minz_ExtensionManager::callHook('freshrss_user_maintenance'); $app->run(); if (!invalidateHttpCache()) { diff --git a/cli/_cli.php b/cli/_cli.php index 0d2c8695f..13f4c62a2 100644 --- a/cli/_cli.php +++ b/cli/_cli.php @@ -37,7 +37,7 @@ function cliInitUser($username) { } $ext_list = FreshRSS_Context::$user_conf->extensions_enabled; - Minz_ExtensionManager::enableByList($ext_list); + Minz_ExtensionManager::enableByList($ext_list, 'user'); return $username; } diff --git a/lib/Minz/ActionController.php b/lib/Minz/ActionController.php index 08ef2a051..c29ae8ad8 100644 --- a/lib/Minz/ActionController.php +++ b/lib/Minz/ActionController.php @@ -90,7 +90,7 @@ class Minz_ActionController { * firstAction est la première méthode exécutée par le Dispatcher * lastAction est la dernière */ - public function init () { } - public function firstAction () { } - public function lastAction () { } + public function init(): void { } + public function firstAction(): void { } + public function lastAction(): void { } } diff --git a/lib/Minz/Configuration.php b/lib/Minz/Configuration.php index a9a4ae03a..f286138e2 100644 --- a/lib/Minz/Configuration.php +++ b/lib/Minz/Configuration.php @@ -6,7 +6,7 @@ * @property array<string|array<int,string>> $db * @property-read string $disable_update * @property-read string $environment - * @property-read array<string> $extensions_enabled + * @property array<string,bool> $extensions_enabled * @property-read string $mailer * @property-read array<string|int|bool> $smtp * @property string $title @@ -92,24 +92,6 @@ class Minz_Configuration { private $configuration_setter = null; /** - * List of enabled extensions. - */ - private $extensions_enabled = []; - - public function removeExtension($ext_name) { - unset($this->extensions_enabled[$ext_name]); - $legacyKey = array_search($ext_name, $this->extensions_enabled, true); - if ($legacyKey !== false) { //Legacy format FreshRSS < 1.11.1 - unset($this->extensions_enabled[$legacyKey]); - } - } - public function addExtension($ext_name) { - if (!isset($this->extensions_enabled[$ext_name])) { - $this->extensions_enabled[$ext_name] = true; - } - } - - /** * Create a new Minz_Configuration object. * * @param string $namespace the name of the current configuration. diff --git a/lib/Minz/Extension.php b/lib/Minz/Extension.php index d1dabe8d5..e95fe7160 100644 --- a/lib/Minz/Extension.php +++ b/lib/Minz/Extension.php @@ -4,22 +4,34 @@ * The extension base class. */ abstract class Minz_Extension { + /** @var string */ private $name; + /** @var string */ private $entrypoint; + /** @var string */ private $path; + /** @var string */ private $author; + /** @var string */ private $description; + /** @var string */ private $version; + /** @var 'system'|'user' */ private $type; + /** @var string */ private $config_key = 'extensions'; + /** @var array<string,mixed>|null */ private $user_configuration; + /** @var array<string,mixed>|null */ private $system_configuration; + /** @var array{0:'system',1:'user'} */ public static $authorized_types = array( 'system', 'user', ); + /** @var bool */ private $is_enabled; /** @@ -34,9 +46,10 @@ abstract class Minz_Extension { * - version: a version for the current extension. * - type: "system" or "user" (default). * - * @param array<string> $meta_info contains information about the extension. + * @param array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'} $meta_info + * contains information about the extension. */ - final public function __construct($meta_info) { + final public function __construct(array $meta_info) { $this->name = $meta_info['name']; $this->entrypoint = $meta_info['entrypoint']; $this->path = $meta_info['path']; @@ -70,22 +83,23 @@ abstract class Minz_Extension { /** * Call at the initialization of the extension (i.e. when the extension is * enabled by the extension manager). + * @return void */ abstract public function init(); /** * Set the current extension to enable. */ - public function enable() { + public final function enable(): void { $this->is_enabled = true; } /** * Return if the extension is currently enabled. * - * @return string|true true if extension is enabled, false otherwise. + * @return bool true if extension is enabled, false otherwise. */ - public function isEnabled() { + public final function isEnabled(): bool { return $this->is_enabled; } @@ -94,7 +108,7 @@ abstract class Minz_Extension { * * @return string|false html content from ext_dir/configure.phtml, false if it does not exist. */ - public function getConfigureView() { + public final function getConfigureView() { $filename = $this->path . '/configure.phtml'; if (!file_exists($filename)) { return false; @@ -107,35 +121,39 @@ abstract class Minz_Extension { /** * Handle the configure action. + * @return void */ public function handleConfigureAction() {} /** * Getters and setters. */ - public function getName() { + public final function getName(): string { return $this->name; } - public function getEntrypoint() { + public final function getEntrypoint(): string { return $this->entrypoint; } - public function getPath() { + public final function getPath(): string { return $this->path; } - public function getAuthor() { + public final function getAuthor(): string { return $this->author; } - public function getDescription() { + public final function getDescription(): string { return $this->description; } - public function getVersion() { + public final function getVersion(): string { return $this->version; } - public function getType() { + /** @return 'system'|'user' */ + public final function getType() { return $this->type; } - private function setType($type) { - if (!in_array($type, self::$authorized_types)) { + + /** @param 'user'|'system' $type */ + private function setType(string $type): void { + if (!in_array($type, ['user', 'system'])) { throw new Minz_ExtensionException('invalid `type` info', $this->name); } $this->type = $type; @@ -145,11 +163,11 @@ abstract class Minz_Extension { * Return the url for a given file. * * @param string $filename name of the file to serve. - * @param string $type the type (js or css) of the file to serve. + * @param 'css'|'js' $type the type (js or css) of the file to serve. * @param bool $isStatic indicates if the file is a static file or a user file. Default is static. * @return string url corresponding to the file. */ - public function getFileUrl($filename, $type, $isStatic = true) { + public final function getFileUrl(string $filename, string $type, bool $isStatic = true): string { if ($isStatic) { $dir = basename($this->path); $file_name_url = urlencode("{$dir}/static/{$filename}"); @@ -169,21 +187,21 @@ abstract class Minz_Extension { * * @param string $base_name the base name of the controller. Final name will be FreshExtension_<base_name>_Controller. */ - public function registerController($base_name) { + public final function registerController(string $base_name): void { Minz_Dispatcher::registerController($base_name, $this->path); } /** * Register the views in order to be accessible by the application. */ - public function registerViews() { + public final function registerViews(): void { Minz_View::addBasePathname($this->path); } /** * Register i18n files from ext_dir/i18n/ */ - public function registerTranslates() { + public final function registerTranslates(): void { $i18n_dir = $this->path . '/i18n'; Minz_Translate::registerPath($i18n_dir); } @@ -192,46 +210,48 @@ abstract class Minz_Extension { * Register a new hook. * * @param string $hook_name the hook name (must exist). - * @param callable-string|array<string> $hook_function the function name to call (must be callable). + * @param callable $hook_function the function name to call (must be callable). */ - public function registerHook($hook_name, $hook_function) { + public final function registerHook(string $hook_name, $hook_function): void { Minz_ExtensionManager::addHook($hook_name, $hook_function); } - /** - * @return bool - */ - private function isConfigurationEnabled(string $type) { + /** @param 'system'|'user' $type */ + private function isConfigurationEnabled($type): bool { if (!class_exists('FreshRSS_Context', false)) { return false; } - $conf = "{$type}_conf"; - if (null === FreshRSS_Context::$$conf) { - return false; + switch ($type) { + case 'system': return FreshRSS_Context::$system_conf !== null; + case 'user': return FreshRSS_Context::$user_conf !== null; } - - return true; } - /** - * @return bool - */ - private function isExtensionConfigured(string $type) { - $conf = "{$type}_conf"; + /** @param 'system'|'user' $type */ + private function isExtensionConfigured($type): bool { + switch ($type) { + case 'system': + $conf = FreshRSS_Context::$user_conf; + break; + case 'user': + $conf = FreshRSS_Context::$system_conf; + break; + } - if (!FreshRSS_Context::$$conf->hasParam($this->config_key)) { + if ($conf === null || !$conf->hasParam($this->config_key)) { return false; } - $extensions = FreshRSS_Context::$$conf->{$this->config_key}; + $extensions = $conf->{$this->config_key}; return array_key_exists($this->getName(), $extensions); } /** - * @return array + * @param 'system'|'user' $type + * @return array<string,mixed> */ - private function getConfiguration(string $type) { + private function getConfiguration(string $type): array { if (!$this->isConfigurationEnabled($type)) { return []; } @@ -245,16 +265,16 @@ abstract class Minz_Extension { } /** - * @return array + * @return array<string,mixed> */ - public function getSystemConfiguration() { + public final function getSystemConfiguration(): array { return $this->getConfiguration('system'); } /** - * @return array + * @return array<string,mixed> */ - public function getUserConfiguration() { + public final function getUserConfiguration(): array { return $this->getConfiguration('user'); } @@ -262,7 +282,7 @@ abstract class Minz_Extension { * @param mixed $default * @return mixed */ - public function getSystemConfigurationValue(string $key, $default = null) { + public final function getSystemConfigurationValue(string $key, $default = null) { if (!is_array($this->system_configuration)) { $this->system_configuration = $this->getSystemConfiguration(); } @@ -277,7 +297,7 @@ abstract class Minz_Extension { * @param mixed $default * @return mixed */ - public function getUserConfigurationValue(string $key, $default = null) { + public final function getUserConfigurationValue(string $key, $default = null) { if (!is_array($this->user_configuration)) { $this->user_configuration = $this->getUserConfiguration(); } @@ -288,7 +308,11 @@ abstract class Minz_Extension { return $default; } - private function setConfiguration(string $type, array $configuration) { + /** + * @param 'system'|'user' $type + * @param array<string,mixed> $configuration + */ + private function setConfiguration(string $type, array $configuration): void { $conf = "{$type}_conf"; if (FreshRSS_Context::$$conf->hasParam($this->config_key)) { @@ -302,17 +326,20 @@ abstract class Minz_Extension { FreshRSS_Context::$$conf->save(); } - public function setSystemConfiguration(array $configuration) { + /** @param array<string,mixed> $configuration */ + public final function setSystemConfiguration(array $configuration): void { $this->setConfiguration('system', $configuration); $this->system_configuration = $configuration; } - public function setUserConfiguration(array $configuration) { + /** @param array<string,mixed> $configuration */ + public final function setUserConfiguration(array $configuration): void { $this->setConfiguration('user', $configuration); $this->user_configuration = $configuration; } - private function removeConfiguration(string $type) { + /** @param 'system'|'user' $type */ + private function removeConfiguration(string $type): void { if (!$this->isConfigurationEnabled($type)) { return; } @@ -332,17 +359,17 @@ abstract class Minz_Extension { FreshRSS_Context::$$conf->save(); } - public function removeSystemConfiguration() { + public final function removeSystemConfiguration(): void { $this->removeConfiguration('system'); $this->system_configuration = null; } - public function removeUserConfiguration() { + public final function removeUserConfiguration(): void { $this->removeConfiguration('user'); $this->user_configuration = null; } - public function saveFile(string $filename, string $content) { + public final function saveFile(string $filename, string $content): void { $username = Minz_User::name(); $path = USERS_PATH . "/{$username}/{$this->config_key}/{$this->getName()}"; @@ -353,7 +380,7 @@ abstract class Minz_Extension { file_put_contents("{$path}/{$filename}", $content); } - public function removeFile(string $filename) { + public final function removeFile(string $filename): void { $username = Minz_User::name(); $path = USERS_PATH . "/{$username}/{$this->config_key}/{$this->getName()}/{$filename}"; diff --git a/lib/Minz/ExtensionManager.php b/lib/Minz/ExtensionManager.php index 8625217ec..9c0eaf001 100644 --- a/lib/Minz/ExtensionManager.php +++ b/lib/Minz/ExtensionManager.php @@ -5,15 +5,22 @@ * * @todo see coding style for methods!! */ -class Minz_ExtensionManager { +final class Minz_ExtensionManager { + /** @var string */ private static $ext_metaname = 'metadata.json'; + /** @var string */ private static $ext_entry_point = 'extension.php'; + /** @var array<string,Minz_Extension> */ private static $ext_list = array(); + /** @var array<string,Minz_Extension> */ private static $ext_list_enabled = array(); - + /** @var array<string,bool> */ private static $ext_auto_enabled = array(); - // List of available hooks. Please keep this list sorted. + /** + * List of available hooks. Please keep this list sorted. + * @var array<string,array{'list':array<callable>,'signature':'NoneToNone'|'NoneToString'|'OneToOne'|'PassArguments'}> + */ private static $hook_list = array( 'check_url_before_add' => array( // function($url) -> Url | null 'list' => array(), @@ -77,6 +84,22 @@ class Minz_ExtensionManager { ), ); + /** Remove extensions and hooks from a previous initialisation */ + private static function reset(): void { + $hadAny = !empty(self::$ext_list_enabled); + self::$ext_list = []; + self::$ext_list_enabled = []; + self::$ext_auto_enabled = []; + foreach (self::$hook_list as $hook_type => $hook_data) { + $hadAny |= !empty($hook_data['list']); + $hook_data['list'] = []; + self::$hook_list[$hook_type] = $hook_data; + } + if ($hadAny) { + gc_collect_cycles(); + } + } + /** * Initialize the extension manager by loading extensions in EXTENSIONS_PATH. * @@ -88,12 +111,15 @@ class Minz_ExtensionManager { * <name> must match with the entry point in metadata.json. This class must * inherit from Minz_Extension class. */ - public static function init() { - $list_core_extensions = array_diff(scandir(CORE_EXTENSIONS_PATH), [ '..', '.' ]); - $list_thirdparty_extensions = array_diff(scandir(THIRDPARTY_EXTENSIONS_PATH), [ '..', '.' ], $list_core_extensions); + public static function init(): void { + self::reset(); + + $list_core_extensions = array_diff(scandir(CORE_EXTENSIONS_PATH) ?: [], [ '..', '.' ]); + $list_thirdparty_extensions = array_diff(scandir(THIRDPARTY_EXTENSIONS_PATH) ?: [], [ '..', '.' ], $list_core_extensions); array_walk($list_core_extensions, function (&$s) { $s = CORE_EXTENSIONS_PATH . '/' . $s; }); array_walk($list_thirdparty_extensions, function (&$s) { $s = THIRDPARTY_EXTENSIONS_PATH . '/' . $s; }); + /** @var array<string> */ $list_potential_extensions = array_merge($list_core_extensions, $list_thirdparty_extensions); $system_conf = Minz_Configuration::get('system'); @@ -110,7 +136,8 @@ class Minz_ExtensionManager { // No metadata file? Invalid! continue; } - $meta_raw_content = file_get_contents($metadata_filename); + $meta_raw_content = file_get_contents($metadata_filename) ?: ''; + /** @var array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'}|null */ $meta_json = json_decode($meta_raw_content, true); if (!$meta_json || !self::isValidMetadata($meta_json)) { // metadata.json is not a json file? Invalid! @@ -138,10 +165,11 @@ class Minz_ExtensionManager { * If the extension class name is `TestExtension`, entry point will be `Test`. * `entry_point` must be composed of alphanumeric characters. * - * @param array<string> $meta is an array of values. + * @param array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'} $meta + * is an array of values. * @return bool true if the array is valid, false else. */ - public static function isValidMetadata($meta): bool { + private static function isValidMetadata(array $meta): bool { $valid_chars = array('_'); return !(empty($meta['name']) || empty($meta['entrypoint']) || !ctype_alnum(str_replace($valid_chars, '', $meta['entrypoint']))); } @@ -149,10 +177,11 @@ class Minz_ExtensionManager { /** * Load the extension source code based on info metadata. * - * @param array $info an array containing information about extension. + * @param array{'name':string,'entrypoint':string,'path':string,'author'?:string,'description'?:string,'version'?:string,'type'?:'system'|'user'} $info + * an array containing information about extension. * @return Minz_Extension|null an extension inheriting from Minz_Extension. */ - public static function load($info) { + private static function load(array $info): ?Minz_Extension { $entry_point_filename = $info['path'] . '/' . self::$ext_entry_point; $ext_class_name = $info['entrypoint'] . 'Extension'; @@ -191,14 +220,12 @@ class Minz_ExtensionManager { * * @param Minz_Extension $ext a valid extension. */ - public static function register($ext) { + private static function register(Minz_Extension $ext): void { $name = $ext->getName(); self::$ext_list[$name] = $ext; - if ($ext->getType() === 'system' && - (!empty(self::$ext_auto_enabled[$name]) || - in_array($name, self::$ext_auto_enabled, true))) { //Legacy format < FreshRSS 1.11.1 - self::enable($ext->getName()); + if ($ext->getType() === 'system' && !empty(self::$ext_auto_enabled[$name])) { + self::enable($ext->getName(), 'system'); } } @@ -208,10 +235,17 @@ class Minz_ExtensionManager { * The extension init() method will be called. * * @param string $ext_name is the name of a valid extension present in $ext_list. + * @param 'system'|'user'|null $onlyOfType only enable if the extension matches that type. Set to null to load all. */ - public static function enable($ext_name) { + private static function enable(string $ext_name, ?string $onlyOfType = null): void { if (isset(self::$ext_list[$ext_name])) { $ext = self::$ext_list[$ext_name]; + + if ($onlyOfType !== null && $ext->getType() !== $onlyOfType) { + // Do not enable an extension of the wrong type + return; + } + self::$ext_list_enabled[$ext_name] = $ext; if (method_exists($ext, 'autoload')) { @@ -225,17 +259,16 @@ class Minz_ExtensionManager { /** * Enable a list of extensions. * - * @param string[] $ext_list the names of extensions we want to load. + * @param array<string,bool> $ext_list the names of extensions we want to load. + * @param 'system'|'user'|null $onlyOfType limit the extensions to load to those of those type. Set to null string to load all. */ - public static function enableByList($ext_list) { - if (!is_array($ext_list)) { + public static function enableByList(?array $ext_list, ?string $onlyOfType = null): void { + if (empty($ext_list)) { return; } foreach ($ext_list as $ext_name => $ext_status) { - if (is_int($ext_name)) { //Legacy format int=>name - self::enable($ext_status); - } elseif ($ext_status) { //New format name=>Boolean - self::enable($ext_name); + if ($ext_status) { + self::enable($ext_name, $onlyOfType); } } } @@ -246,7 +279,7 @@ class Minz_ExtensionManager { * @param bool $only_enabled if true returns only the enabled extensions (false by default). * @return Minz_Extension[] an array of extensions. */ - public static function listExtensions($only_enabled = false) { + public static function listExtensions(bool $only_enabled = false): array { if ($only_enabled) { return self::$ext_list_enabled; } else { @@ -260,7 +293,7 @@ class Minz_ExtensionManager { * @param string $ext_name the name of the extension. * @return Minz_Extension|null the corresponding extension or null if it doesn't exist. */ - public static function findExtension($ext_name) { + public static function findExtension(string $ext_name): ?Minz_Extension { if (!isset(self::$ext_list[$ext_name])) { return null; } @@ -277,7 +310,7 @@ class Minz_ExtensionManager { * @param string $hook_name the hook name (must exist). * @param callable $hook_function the function name to call (must be callable). */ - public static function addHook($hook_name, $hook_function) { + public static function addHook(string $hook_name, $hook_function): void { if (isset(self::$hook_list[$hook_name]) && is_callable($hook_function)) { self::$hook_list[$hook_name]['list'][] = $hook_function; } @@ -293,7 +326,7 @@ class Minz_ExtensionManager { * @param mixed ...$args additional parameters (for signature, please see self::$hook_list). * @return mixed|null final result of the called hook. */ - public static function callHook($hook_name, ...$args) { + public static function callHook(string $hook_name, ...$args) { if (!isset(self::$hook_list[$hook_name])) { return; } @@ -308,7 +341,7 @@ class Minz_ExtensionManager { } elseif ($signature === 'NoneToString') { return self::callNoneToString($hook_name); } elseif ($signature === 'NoneToNone') { - return self::callNoneToNone($hook_name); + self::callNoneToNone($hook_name); } } @@ -326,7 +359,7 @@ class Minz_ExtensionManager { * @return mixed|null final chained result of the hooks. If nothing is changed, * the initial argument is returned. */ - private static function callOneToOne($hook_name, $arg) { + private static function callOneToOne(string $hook_name, $arg) { $result = $arg; foreach (self::$hook_list[$hook_name]['list'] as $function) { $result = call_user_func($function, $arg); @@ -349,7 +382,7 @@ class Minz_ExtensionManager { * @param string $hook_name is the hook to call. * @return string concatenated result of the call to all the hooks. */ - private static function callNoneToString($hook_name) { + private static function callNoneToString(string $hook_name): string { $result = ''; foreach (self::$hook_list[$hook_name]['list'] as $function) { $result = $result . call_user_func($function); @@ -365,7 +398,7 @@ class Minz_ExtensionManager { * * @param string $hook_name is the hook to call. */ - private static function callNoneToNone($hook_name) { + private static function callNoneToNone(string $hook_name): void { foreach (self::$hook_list[$hook_name]['list'] as $function) { call_user_func($function); } diff --git a/lib/Minz/Request.php b/lib/Minz/Request.php index bcd914612..a296f3b39 100644 --- a/lib/Minz/Request.php +++ b/lib/Minz/Request.php @@ -36,7 +36,7 @@ class Minz_Request { * @param bool $specialchars special characters * @return mixed value of the parameter */ - public static function param($key, $default = false, $specialchars = false) { + public static function param(string $key, $default = false, bool $specialchars = false) { if (isset(self::$params[$key])) { $p = self::$params[$key]; if (is_object($p) || $specialchars) { @@ -48,12 +48,13 @@ class Minz_Request { return $default; } } - public static function paramTernary($key) { + + /** @return bool|null */ + public static function paramTernary(string $key) { if (isset(self::$params[$key])) { $p = self::$params[$key]; - $tp = trim($p); - // @phpstan-ignore-next-line - if ($p === null || $tp === '' || $tp === 'null') { + $tp = is_string($p) ? trim($p) : true; + if ($tp === '' || $tp === 'null') { return null; } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') { return false; @@ -62,12 +63,27 @@ class Minz_Request { } return null; } - public static function paramBoolean($key) { + + public static function paramBoolean(string $key): bool { if (null === $value = self::paramTernary($key)) { return false; } return $value; } + + public static function paramString(string $key): string { + if (isset(self::$params[$key])) { + $s = self::$params[$key]; + if (is_string($s)) { + return trim($s); + } + if (is_int($s) || is_bool($s)) { + return (string)$s; + } + } + return ''; + } + /** * Extract text lines to array. * diff --git a/lib/core-extensions/Google-Groups/extension.php b/lib/core-extensions/Google-Groups/extension.php index 656bf9b8f..cdd605cd9 100644 --- a/lib/core-extensions/Google-Groups/extension.php +++ b/lib/core-extensions/Google-Groups/extension.php @@ -1,10 +1,11 @@ <?php class GoogleGroupsExtension extends Minz_Extension { + /** @return void */ public function init() { $this->registerHook('check_url_before_add', array('GoogleGroupsExtension', 'findFeed')); } - public static function findFeed($url) { + public static function findFeed(string $url): string { return preg_replace('%^(https?://groups.google.com/forum)/#!forum/(.+)$%i', '$1/feed/$2/msgs/rss.xml', $url); } } diff --git a/lib/core-extensions/Tumblr-GDPR/extension.php b/lib/core-extensions/Tumblr-GDPR/extension.php index 83bdf2189..825bb97df 100644 --- a/lib/core-extensions/Tumblr-GDPR/extension.php +++ b/lib/core-extensions/Tumblr-GDPR/extension.php @@ -1,11 +1,12 @@ <?php class TumblrGdprExtension extends Minz_Extension { + /** @return void */ public function init() { $this->registerHook('simplepie_before_init', array('TumblrGdprExtension', 'curlHook')); } - public static function curlHook($simplePie, $feed) { + public static function curlHook(SimplePie $simplePie, FreshRSS_Feed $feed): void { if (preg_match('#^https?://[a-zA-Z_0-9-]+.tumblr.com/#i', $feed->url())) { $simplePie->set_useragent(FRESHRSS_USERAGENT . ' like Baiduspider'); } diff --git a/p/api/greader.php b/p/api/greader.php index 69a50eea3..9256c770b 100644 --- a/p/api/greader.php +++ b/p/api/greader.php @@ -1013,7 +1013,7 @@ final class GReaderAPI { if (FreshRSS_Context::$user_conf != null) { Minz_Translate::init(FreshRSS_Context::$user_conf->language); Minz_ExtensionManager::init(); - Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); + Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled, 'user'); } else { Minz_Translate::init(); } diff --git a/p/api/pshb.php b/p/api/pshb.php index b3e3f400f..9c9323da5 100644 --- a/p/api/pshb.php +++ b/p/api/pshb.php @@ -128,7 +128,7 @@ foreach ($users as $userFilename) { Minz_Log::warning('FreshRSS skip disabled user ' . $username); continue; } - Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); + Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled, 'user'); Minz_Translate::reset(FreshRSS_Context::$user_conf->language); list($updated_feeds, $feed, $nb_new_articles) = FreshRSS_feed_Controller::actualizeFeed(0, $self, false, $simplePie); diff --git a/tests/phpstan-next.txt b/tests/phpstan-next.txt index 52b3b823c..325f16793 100644 --- a/tests/phpstan-next.txt +++ b/tests/phpstan-next.txt @@ -4,7 +4,6 @@ # Can be regenerated with something like: # find . -type d -name 'vendor' -prune -o -name '*.php' -exec sh -c 'vendor/bin/phpstan analyse --level 6 --memory-limit 512M {} >/dev/null 2>/dev/null || echo {}' \; -./app/Controllers/extensionController.php ./app/Controllers/feedController.php ./app/Controllers/updateController.php ./app/Controllers/userController.php @@ -32,14 +31,10 @@ ./cli/i18n/I18nFile.php ./cli/i18n/I18nValue.php ./cli/manipulate.translation.php -./lib/core-extensions/Google-Groups/extension.php -./lib/core-extensions/Tumblr-GDPR/extension.php ./lib/http-conditional.php ./lib/Minz/ActionController.php ./lib/Minz/Configuration.php ./lib/Minz/Dispatcher.php -./lib/Minz/Extension.php -./lib/Minz/ExtensionManager.php ./lib/Minz/FrontController.php ./lib/Minz/Log.php ./lib/Minz/Migrator.php |
