diff --git a/app/modules/api/Init.php b/app/modules/api/Init.php index 2ef66337..21a649db 100644 --- a/app/modules/api/Init.php +++ b/app/modules/api/Init.php @@ -25,11 +25,13 @@ namespace SP\Modules\Api; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use Psr\Container\ContainerInterface; -use SP\Core\Context\StatelessContext; +use Klein\Klein; +use SP\Core\Application; use SP\Core\Exceptions\InitializationException; +use SP\Core\HttpModuleBase; use SP\Core\Language; -use SP\Core\ModuleBase; +use SP\Core\ProvidersHelper; +use SP\Http\Request; use SP\Services\Upgrade\UpgradeAppService; use SP\Services\Upgrade\UpgradeDatabaseService; use SP\Services\Upgrade\UpgradeUtil; @@ -40,20 +42,28 @@ use SP\Util\HttpUtil; /** * Class Init */ -final class Init extends ModuleBase +final class Init extends HttpModuleBase { - protected StatelessContext $context; - protected Language $language; + private Language $language; + private DatabaseUtil $databaseUtil; - /** - * Module constructor. - */ - public function __construct(ContainerInterface $container) - { - parent::__construct($container); + public function __construct( + Application $application, + ProvidersHelper $providersHelper, + Request $request, + Klein $router, + Language $language, + DatabaseUtil $databaseUtil + ) { + parent::__construct( + $application, + $providersHelper, + $request, + $router + ); - $this->context = $container->get(StatelessContext::class); - $this->language = $container->get(Language::class); + $this->language = $language; + $this->databaseUtil = $databaseUtil; } /** @@ -83,21 +93,19 @@ final class Init extends ModuleBase $this->checkInstalled(); // Checks if maintenance mode is turned on - if ($this->checkMaintenanceMode($this->context)) { + if ($this->checkMaintenanceMode()) { throw new InitializationException('Maintenance mode'); } // Checks if upgrade is needed $this->checkUpgrade(); - $databaseUtil = $this->container->get(DatabaseUtil::class); - // Checks if the database is set up - if (!$databaseUtil->checkDatabaseConnection()) { + if (!$this->databaseUtil->checkDatabaseConnection()) { throw new InitializationException('Database connection error'); } - if (!$databaseUtil->checkDatabaseTables($this->configData->getDbName())) { + if (!$this->databaseUtil->checkDatabaseTables($this->configData->getDbName())) { throw new InitializationException('Database checking error'); } @@ -134,8 +142,8 @@ final class Init extends ModuleBase UpgradeUtil::fixAppUpgrade($this->configData, $this->config); if ($this->configData->getUpgradeKey() - || (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) || - UpgradeAppService::needsUpgrade($this->configData->getAppVersion())) + || (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) + || UpgradeAppService::needsUpgrade($this->configData->getAppVersion())) ) { $this->config->generateUpgradeKey(); diff --git a/app/modules/cli/CliCommandHelper.php b/app/modules/cli/CliCommandHelper.php new file mode 100644 index 00000000..0c56b9ed --- /dev/null +++ b/app/modules/cli/CliCommandHelper.php @@ -0,0 +1,62 @@ +. + */ + +namespace SP\Modules\Cli; + + +use SP\Modules\Cli\Commands\BackupCommand; +use SP\Modules\Cli\Commands\CommandBase; +use SP\Modules\Cli\Commands\Crypt\UpdateMasterPasswordCommand; +use SP\Modules\Cli\Commands\InstallCommand; + +/** + * A helper to instantiate CLI commands + */ +final class CliCommandHelper +{ + /** + * @var CommandBase[] + */ + private array $commands; + + public function __construct( + InstallCommand $installCommand, + BackupCommand $backupCommand, + UpdateMasterPasswordCommand $updateMasterPasswordCommand + ) { + $this->commands = [ + $installCommand, + $backupCommand, + $updateMasterPasswordCommand, + ]; + } + + /** + * @return CommandBase[] + */ + public function getCommands(): array + { + return $this->commands; + } +} \ No newline at end of file diff --git a/app/modules/cli/Init.php b/app/modules/cli/Init.php index 39bf4903..b9c939c8 100644 --- a/app/modules/cli/Init.php +++ b/app/modules/cli/Init.php @@ -24,15 +24,12 @@ namespace SP\Modules\Cli; -use Psr\Container\ContainerInterface; -use SP\Core\Context\StatelessContext; +use SP\Core\Application; use SP\Core\Language; use SP\Core\ModuleBase; -use SP\Modules\Cli\Commands\BackupCommand; -use SP\Modules\Cli\Commands\Crypt\UpdateMasterPasswordCommand; -use SP\Modules\Cli\Commands\InstallCommand; +use SP\Core\ProvidersHelper; use SP\Util\VersionUtil; -use Symfony\Component\Console\Application; +use Symfony\Component\Console\Application as ConsoleApplication; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -43,25 +40,32 @@ use Symfony\Component\Console\Output\OutputInterface; */ final class Init extends ModuleBase { - private const CLI_COMMANDS = [ - InstallCommand::class, - BackupCommand::class, - UpdateMasterPasswordCommand::class - ]; - protected StatelessContext $context; - protected Language $language; - protected Application $application; + private Language $language; + private InputInterface $input; + private OutputInterface $output; + private ConsoleApplication $consoleApplication; + private CliCommandHelper $cliCommandHelper; - /** - * Module constructor. - */ - public function __construct(ContainerInterface $container) - { - parent::__construct($container); + public function __construct( + Application $application, + ProvidersHelper $providersHelper, + Language $language, + ConsoleApplication $consoleApplication, + InputInterface $input, + OutputInterface $output, + CliCommandHelper $cliCommandHelper + ) { + $this->language = $language; + $this->consoleApplication = $consoleApplication; + $this->input = $input; + $this->output = $output; + $this->cliCommandHelper = $cliCommandHelper; + + parent::__construct( + $application, + $providersHelper + ); - $this->context = $container->get(StatelessContext::class); - $this->language = $container->get(Language::class); - $this->application = $container->get(Application::class); } /** @@ -89,16 +93,13 @@ final class Init extends ModuleBase */ private function initCli(): void { - $this->application->setName('sysPass CLI'); - $this->application->setVersion(implode('.', VersionUtil::getVersionArray())); + $this->consoleApplication->setName('sysPass CLI'); + $this->consoleApplication->setVersion(implode('.', VersionUtil::getVersionArray())); + $this->consoleApplication->addCommands($this->cliCommandHelper->getCommands()); - foreach (self::CLI_COMMANDS as $command) { - $this->application->add($this->container->get($command)); - } - - $this->application->run( - $this->container->get(InputInterface::class), - $this->container->get(OutputInterface::class) + $this->consoleApplication->run( + $this->input, + $this->output ); } } \ No newline at end of file diff --git a/app/modules/web/Init.php b/app/modules/web/Init.php index e681ef42..8498b4c1 100644 --- a/app/modules/web/Init.php +++ b/app/modules/web/Init.php @@ -26,10 +26,10 @@ namespace SP\Modules\Web; use Defuse\Crypto\Exception\CryptoException; use Exception; -use Psr\Container\ContainerInterface; +use Klein\Klein; use SP\Bootstrap; +use SP\Core\Application; use SP\Core\Context\ContextBase; -use SP\Core\Context\ContextInterface; use SP\Core\Context\SessionContext; use SP\Core\Crypt\CryptSessionHandler; use SP\Core\Crypt\CSRF; @@ -40,11 +40,13 @@ use SP\Core\Exceptions\InitializationException; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; +use SP\Core\HttpModuleBase; use SP\Core\Language; -use SP\Core\ModuleBase; +use SP\Core\ProvidersHelper; use SP\Core\UI\ThemeInterface; use SP\DataModel\ItemPreset\SessionTimeout; use SP\Http\Address; +use SP\Http\Request; use SP\Plugin\PluginManager; use SP\Services\Crypt\SecureSessionService; use SP\Services\ItemPreset\ItemPresetInterface; @@ -60,7 +62,7 @@ use SP\Util\HttpUtil; /** * Class Init */ -final class Init extends ModuleBase +final class Init extends HttpModuleBase { /** * List of controllers that don't need to perform fully initialization @@ -73,46 +75,60 @@ final class Init extends ModuleBase 'status', 'upgrade', 'error', - 'task' + 'task', ]; /** * List of controllers that don't need to update the user's session activity */ private const NO_SESSION_ACTIVITY = ['items', 'login']; - private CSRF $csrf; - private SessionContext $context; - private ThemeInterface $theme; - private Language $language; + private CSRF $csrf; + private ThemeInterface $theme; + private Language $language; private SecureSessionService $secureSessionService; - private PluginManager $pluginManager; - private ItemPresetService $itemPresetService; - private bool $isIndex = false; + private PluginManager $pluginManager; + private ItemPresetService $itemPresetService; + private DatabaseUtil $databaseUtil; + private UserProfileService $userProfileService; + private bool $isIndex = false; - /** - * Init constructor. - */ - public function __construct(ContainerInterface $container) - { - parent::__construct($container); + public function __construct( + Application $application, + ProvidersHelper $providersHelper, + Request $request, + Klein $router, + CSRF $csrf, + ThemeInterface $theme, + Language $language, + SecureSessionService $secureSessionService, + PluginManager $pluginManager, + ItemPresetService $itemPresetService, + DatabaseUtil $databaseUtil, + UserProfileService $userProfileService + ) { + parent::__construct( + $application, + $providersHelper, + $request, + $router + ); - $this->context = $container->get(ContextInterface::class); - $this->theme = $container->get(ThemeInterface::class); - $this->language = $container->get(Language::class); - $this->secureSessionService = $container->get(SecureSessionService::class); - $this->pluginManager = $container->get(PluginManager::class); - $this->itemPresetService = $container->get(ItemPresetService::class); - $this->csrf = $container->get(CSRF::class); + $this->csrf = $csrf; + $this->theme = $theme; + $this->language = $language; + $this->secureSessionService = $secureSessionService; + $this->pluginManager = $pluginManager; + $this->itemPresetService = $itemPresetService; + $this->databaseUtil = $databaseUtil; + $this->userProfileService = $userProfileService; } /** * Initialize Web App * - * @param string $controller + * @param string $controller * * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException * @throws \JsonException - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\InitializationException * @throws \SP\Core\Exceptions\QueryException @@ -152,8 +168,6 @@ final class Init extends ModuleBase HttpUtil::checkHttps($this->configData, $this->request); if (in_array($controller, self::PARTIAL_INIT, true) === false) { - $databaseUtil = $this->container->get(DatabaseUtil::class); - // Checks if sysPass is installed if (!$this->checkInstalled()) { logger('Not installed', 'ERROR'); @@ -166,7 +180,7 @@ final class Init extends ModuleBase } // Checks if the database is set up - if (!$databaseUtil->checkDatabaseConnection()) { + if (!$this->databaseUtil->checkDatabaseConnection()) { logger('Database connection error', 'ERROR'); $this->router->response() @@ -177,7 +191,7 @@ final class Init extends ModuleBase } // Checks if maintenance mode is turned on - if ($this->checkMaintenanceMode($this->context)) { + if ($this->checkMaintenanceMode()) { logger('Maintenance mode', 'INFO'); $this->router->response() @@ -201,7 +215,7 @@ final class Init extends ModuleBase } // Checks if the database is set up - if (!$databaseUtil->checkDatabaseTables($this->configData->getDbName())) { + if (!$this->databaseUtil->checkDatabaseTables($this->configData->getDbName())) { logger('Database checking error', 'ERROR'); $this->router->response() @@ -229,9 +243,10 @@ final class Init extends ModuleBase // Recargar los permisos del perfil de usuario $this->context->setUserProfile( - $this->container->get(UserProfileService::class) - ->getById($this->context->getUserData() - ->getUserProfileId())->getProfile()); + $this->userProfileService + ->getById($this->context->getUserData()->getUserProfileId()) + ->getProfile() + ); } if (!$this->csrf->check()) { @@ -280,7 +295,7 @@ final class Init extends ModuleBase private function checkInstalled(): bool { return $this->configData->isInstalled() - && $this->router->request()->param('r') !== 'install/index'; + && $this->router->request()->param('r') !== 'install/index'; } /** @@ -293,8 +308,8 @@ final class Init extends ModuleBase UpgradeUtil::fixAppUpgrade($this->configData, $this->config); return $this->configData->getUpgradeKey() - || (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) || - UpgradeAppService::needsUpgrade($this->configData->getAppVersion())); + || (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) + || UpgradeAppService::needsUpgrade($this->configData->getAppVersion())); } /** @@ -325,17 +340,20 @@ final class Init extends ModuleBase if ($sidStartTime === 0) { // Try to set PHP's session lifetime @ini_set('session.gc_maxlifetime', $this->getSessionLifeTime()); - } else if (!$inMaintenance - && time() > ($sidStartTime + SessionContext::MAX_SID_TIME) - && $this->context->isLoggedIn() - ) { - try { - CryptSession::reKey($this->context); - } catch (CryptoException $e) { - logger($e->getMessage()); + } else { + if (!$inMaintenance + && time() > ($sidStartTime + SessionContext::MAX_SID_TIME) + && $this->context->isLoggedIn() + ) { + try { + CryptSession::reKey($this->context); + } catch (CryptoException $e) { + logger($e->getMessage()); - SessionContext::restart(); - return; + SessionContext::restart(); + + return; + } } } @@ -357,7 +375,7 @@ final class Init extends ModuleBase $userTimeout = $this->getSessionTimeoutForUser($timeout) ?: $this->configData->getSessionTimeout(); - logger('Session timeout: ' . $userTimeout); + logger('Session timeout: '.$userTimeout); return $this->context->setSessionTimeout($userTimeout); } @@ -382,7 +400,11 @@ final class Init extends ModuleBase if ($itemPreset !== null) { $sessionTimeout = $itemPreset->hydrate(SessionTimeout::class); - if (Address::check($this->request->getClientAddress(), $sessionTimeout->getAddress(), $sessionTimeout->getMask())) { + if (Address::check( + $this->request->getClientAddress(), + $sessionTimeout->getAddress(), + $sessionTimeout->getMask() + )) { return $sessionTimeout->getTimeout(); } } diff --git a/lib/Definitions.php b/lib/Definitions.php index 5d39039d..0476415c 100644 --- a/lib/Definitions.php +++ b/lib/Definitions.php @@ -96,6 +96,5 @@ return [ AccountAclService::class => autowire(AccountAclService::class), \GuzzleHttp\Client::class => create(GuzzleHttp\Client::class) ->constructor(factory([Client::class, 'getOptions'])), - CSRF::class => autowire(CSRF::class), - AuthProvider::class => autowire(AuthProvider::class)->lazy(), + CSRF::class => autowire(CSRF::class) ]; \ No newline at end of file diff --git a/lib/SP/Bootstrap.php b/lib/SP/Bootstrap.php index 49e3d68a..8bed51e1 100644 --- a/lib/SP/Bootstrap.php +++ b/lib/SP/Bootstrap.php @@ -69,17 +69,11 @@ final class Bootstrap * @var string The full URL to reach sysPass (e.g. https://sub.example.com/syspass/) */ public static string $WEBURI = ''; - /** - * @var string - */ public static string $SUBURI = ''; /** * @var mixed */ public static $LOCK; - /** - * @var bool Indica si la versión de PHP es correcta - */ public static bool $checkPhpVersion = false; private static ContainerInterface $container; private Klein $router; @@ -367,23 +361,21 @@ final class Bootstrap public function initPHPVars(): void { if (defined('DEBUG') && DEBUG) { + /** @noinspection ForgottenDebugOutputInspection */ + Debug::enable(); + } elseif (!defined('DEBUG') + && ($this->router->request()->cookies()->get('XDEBUG_SESSION') + || $this->configData->isDebug()) + ) { + define('DEBUG', true); + /** @noinspection ForgottenDebugOutputInspection */ Debug::enable(); } else { - if (!defined('DEBUG') - && ($this->router->request()->cookies()->get('XDEBUG_SESSION') - || $this->configData->isDebug()) - ) { - define('DEBUG', true); + error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE)); - /** @noinspection ForgottenDebugOutputInspection */ - Debug::enable(); - } else { - error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE)); - - if (!headers_sent()) { - ini_set('display_errors', 0); - } + if (!headers_sent()) { + ini_set('display_errors', 0); } } diff --git a/lib/SP/Core/Application.php b/lib/SP/Core/Application.php new file mode 100644 index 00000000..17ce413e --- /dev/null +++ b/lib/SP/Core/Application.php @@ -0,0 +1,81 @@ +. + */ + +namespace SP\Core; + + +use SP\Config\Config; +use SP\Core\Context\ContextInterface; +use SP\Core\Events\EventDispatcher; + +/** + * The Application helper class. It holds all the needed dependencies for the application + */ +final class Application +{ + private Config $config; + private EventDispatcher $eventDispatcher; + private ContextInterface $context; + + /** + * Module constructor. + * + * @param \SP\Config\Config $config + * @param \SP\Core\Events\EventDispatcher $eventDispatcher + * @param \SP\Core\Context\ContextInterface $context + */ + public function __construct( + Config $config, + EventDispatcher $eventDispatcher, + ContextInterface $context + ) { + $this->config = $config; + $this->eventDispatcher = $eventDispatcher; + $this->context = $context; + } + + /** + * @return \SP\Config\Config + */ + public function getConfig(): Config + { + return $this->config; + } + + /** + * @return \SP\Core\Events\EventDispatcher + */ + public function getEventDispatcher(): EventDispatcher + { + return $this->eventDispatcher; + } + + /** + * @return \SP\Core\Context\ContextInterface + */ + public function getContext(): ContextInterface + { + return $this->context; + } +} \ No newline at end of file diff --git a/lib/SP/Core/Context/ContextFactory.php b/lib/SP/Core/Context/ContextFactory.php index 224b3467..290dfcb0 100644 --- a/lib/SP/Core/Context/ContextFactory.php +++ b/lib/SP/Core/Context/ContextFactory.php @@ -25,7 +25,7 @@ namespace SP\Core\Context; /** - * + * ContextFactory */ final class ContextFactory { diff --git a/lib/SP/Core/HttpModuleBase.php b/lib/SP/Core/HttpModuleBase.php new file mode 100644 index 00000000..f215a297 --- /dev/null +++ b/lib/SP/Core/HttpModuleBase.php @@ -0,0 +1,72 @@ +. + */ + +namespace SP\Core; + +use Klein\Klein; +use SP\Bootstrap; +use SP\Http\Request; +use SP\Util\Util; + +/** + * Base module for HTTP based modules + */ +abstract class HttpModuleBase extends ModuleBase +{ + protected Request $request; + protected Klein $router; + + public function __construct( + Application $application, + ProvidersHelper $providersHelper, + Request $request, + Klein $router + ) { + $this->request = $request; + $this->router = $router; + + parent::__construct($application, $providersHelper); + } + + /** + * Comprobar si el modo mantenimiento está activado + * Esta función comprueba si el modo mantenimiento está activado. + * + * @throws \JsonException + */ + protected function checkMaintenanceMode(): bool + { + if ($this->configData->isMaintenance()) { + Bootstrap::$LOCK = Util::getAppLock(); + + return !$this->request->isAjax() + || !(Bootstrap::$LOCK !== false + && Bootstrap::$LOCK->userId > 0 + && $this->context->isLoggedIn() + && Bootstrap::$LOCK->userId === $this->context->getUserData()->getId()); + } + + return false; + } +} \ No newline at end of file diff --git a/lib/SP/Core/ModuleBase.php b/lib/SP/Core/ModuleBase.php index 408913c3..584036ff 100644 --- a/lib/SP/Core/ModuleBase.php +++ b/lib/SP/Core/ModuleBase.php @@ -24,22 +24,10 @@ namespace SP\Core; -use Klein\Klein; -use Psr\Container\ContainerInterface; -use SP\Bootstrap; use SP\Config\Config; use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; -use SP\Http\Request; -use SP\Providers\Acl\AclHandler; -use SP\Providers\Log\DatabaseLogHandler; -use SP\Providers\Log\FileLogHandler; -use SP\Providers\Log\RemoteSyslogHandler; -use SP\Providers\Log\SyslogHandler; -use SP\Providers\Mail\MailHandler; -use SP\Providers\Notification\NotificationHandler; -use SP\Util\Util; /** * Class ModuleBase @@ -48,50 +36,27 @@ use SP\Util\Util; */ abstract class ModuleBase { + protected Config $config; protected ConfigDataInterface $configData; - protected Config $config; - protected Klein $router; - protected ContainerInterface $container; - protected Request $request; + protected ContextInterface $context; + private EventDispatcher $eventDispatcher; + private ProvidersHelper $providersHelper; /** * Module constructor. * - * @param ContainerInterface $container - * - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface + * @param \SP\Core\Application $application + * @param \SP\Core\ProvidersHelper $providersHelper */ - public function __construct(ContainerInterface $container) - { - $this->container = $container; - $this->config = $container->get(Config::class); + public function __construct( + Application $application, + ProvidersHelper $providersHelper + ) { + $this->config = $application->getConfig(); $this->configData = $this->config->getConfigData(); - $this->router = $container->get(Klein::class); - $this->request = $container->get(Request::class); - } - - abstract public function initialize(string $controller); - - /** - * Comprobar si el modo mantenimiento está activado - * Esta función comprueba si el modo mantenimiento está activado. - * - * @throws \JsonException - */ - public function checkMaintenanceMode(ContextInterface $context): bool - { - if ($this->configData->isMaintenance()) { - Bootstrap::$LOCK = Util::getAppLock(); - - return !$this->request->isAjax() - || !(Bootstrap::$LOCK !== false - && Bootstrap::$LOCK->userId > 0 - && $context->isLoggedIn() - && Bootstrap::$LOCK->userId === $context->getUserData()->getId()); - } - - return false; + $this->context = $application->getContext(); + $this->eventDispatcher = $application->getEventDispatcher(); + $this->providersHelper = $providersHelper; } /** @@ -99,29 +64,51 @@ abstract class ModuleBase */ protected function initEventHandlers(): void { - $eventDispatcher = $this->container->get(EventDispatcher::class); - if (DEBUG || $this->configData->isDebug()) { - $eventDispatcher->attach($this->container->get(FileLogHandler::class)); + $handler = $this->providersHelper->getFileLogHandler(); + $handler->initialize(); + + $this->eventDispatcher->attach($handler); } if ($this->configData->isLogEnabled()) { - $eventDispatcher->attach($this->container->get(DatabaseLogHandler::class)); + $handler = $this->providersHelper->getDatabaseLogHandler(); + $handler->initialize(); + + $this->eventDispatcher->attach($handler); } if ($this->configData->isMailEnabled()) { - $eventDispatcher->attach($this->container->get(MailHandler::class)); + $handler = $this->providersHelper->getMailHandler(); + $handler->initialize(); + + $this->eventDispatcher->attach($handler); } if ($this->configData->isSyslogEnabled()) { - $eventDispatcher->attach($this->container->get(SyslogHandler::class)); + $handler = $this->providersHelper->getSyslogHandler(); + $handler->initialize(); + + $this->eventDispatcher->attach($handler); } if ($this->configData->isSyslogRemoteEnabled()) { - $eventDispatcher->attach($this->container->get(RemoteSyslogHandler::class)); + $handler = $this->providersHelper->getRemoteSyslogHandler(); + $handler->initialize(); + + $this->eventDispatcher->attach($handler); } - $eventDispatcher->attach($this->container->get(AclHandler::class)); - $eventDispatcher->attach($this->container->get(NotificationHandler::class)); + $aclHandler = $this->providersHelper->getAclHandler(); + $aclHandler->initialize(); + + $this->eventDispatcher->attach($aclHandler); + + $notificationHandler = $this->providersHelper->getNotificationHandler(); + $notificationHandler->initialize(); + + $this->eventDispatcher->attach($notificationHandler); } + + abstract public function initialize(string $controller); } \ No newline at end of file diff --git a/lib/SP/Core/ProvidersHelper.php b/lib/SP/Core/ProvidersHelper.php new file mode 100644 index 00000000..647451a8 --- /dev/null +++ b/lib/SP/Core/ProvidersHelper.php @@ -0,0 +1,133 @@ +. + */ + +namespace SP\Core; + + +use SP\Providers\Acl\AclHandler; +use SP\Providers\Log\DatabaseLogHandler; +use SP\Providers\Log\FileLogHandler; +use SP\Providers\Log\RemoteSyslogHandler; +use SP\Providers\Log\SyslogHandler; +use SP\Providers\Mail\MailHandler; +use SP\Providers\Notification\NotificationHandler; + +/** + * The Provider helper class will have oll the providers availabe in the application + */ +final class ProvidersHelper +{ + private FileLogHandler $fileLogHandler; + private DatabaseLogHandler $databaseLogHandler; + private MailHandler $mailHandler; + private SyslogHandler $syslogHandler; + private RemoteSyslogHandler $remoteSyslogHandler; + private AclHandler $aclHandler; + private NotificationHandler $notificationHandler; + + /** + * Module constructor. + * + * @param \SP\Providers\Log\FileLogHandler $fileLogHandler + * @param \SP\Providers\Log\DatabaseLogHandler $databaseLogHandler + * @param \SP\Providers\Mail\MailHandler $mailHandler + * @param \SP\Providers\Log\SyslogHandler $syslogHandler + * @param \SP\Providers\Log\RemoteSyslogHandler $remoteSyslogHandler + * @param \SP\Providers\Acl\AclHandler $aclHandler + * @param \SP\Providers\Notification\NotificationHandler $notificationHandler + */ + public function __construct( + FileLogHandler $fileLogHandler, + DatabaseLogHandler $databaseLogHandler, + MailHandler $mailHandler, + SyslogHandler $syslogHandler, + RemoteSyslogHandler $remoteSyslogHandler, + AclHandler $aclHandler, + NotificationHandler $notificationHandler + ) { + $this->fileLogHandler = $fileLogHandler; + $this->databaseLogHandler = $databaseLogHandler; + $this->mailHandler = $mailHandler; + $this->syslogHandler = $syslogHandler; + $this->remoteSyslogHandler = $remoteSyslogHandler; + $this->aclHandler = $aclHandler; + $this->notificationHandler = $notificationHandler; + } + + /** + * @return \SP\Providers\Log\FileLogHandler + */ + public function getFileLogHandler(): FileLogHandler + { + return $this->fileLogHandler; + } + + /** + * @return \SP\Providers\Log\DatabaseLogHandler + */ + public function getDatabaseLogHandler(): DatabaseLogHandler + { + return $this->databaseLogHandler; + } + + /** + * @return \SP\Providers\Mail\MailHandler + */ + public function getMailHandler(): MailHandler + { + return $this->mailHandler; + } + + /** + * @return \SP\Providers\Log\SyslogHandler + */ + public function getSyslogHandler(): SyslogHandler + { + return $this->syslogHandler; + } + + /** + * @return \SP\Providers\Log\RemoteSyslogHandler + */ + public function getRemoteSyslogHandler(): RemoteSyslogHandler + { + return $this->remoteSyslogHandler; + } + + /** + * @return \SP\Providers\Acl\AclHandler + */ + public function getAclHandler(): AclHandler + { + return $this->aclHandler; + } + + /** + * @return \SP\Providers\Notification\NotificationHandler + */ + public function getNotificationHandler(): NotificationHandler + { + return $this->notificationHandler; + } +} \ No newline at end of file diff --git a/lib/SP/Providers/Acl/AclHandler.php b/lib/SP/Providers/Acl/AclHandler.php index f7971ed0..2c299500 100644 --- a/lib/SP/Providers/Acl/AclHandler.php +++ b/lib/SP/Providers/Acl/AclHandler.php @@ -25,8 +25,10 @@ namespace SP\Providers\Acl; use Exception; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\SPException; use SP\Providers\EventsTrait; @@ -50,17 +52,26 @@ final class AclHandler extends Provider implements EventReceiver 'edit.user', 'edit.userGroup', 'delete.user', - 'delete.user.selection' + 'delete.user.selection', ]; - /** - * @var string - */ - private string $events; - /** - * @var ContainerInterface - */ - private ContainerInterface $dic; + private string $events; + private UserProfileService $userProfileService; + private UserGroupService $userGroupService; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + UserProfileService $userProfileService, + UserGroupService $userGroupService + ) { + $this->userProfileService = $userProfileService; + $this->userGroupService = $userGroupService; + + parent::__construct($config, $context, $eventDispatcher); + } + /** * Devuelve los eventos que implementa el observador @@ -87,7 +98,7 @@ final class AclHandler extends Provider implements EventReceiver * * @link https://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject
+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -103,8 +114,8 @@ final class AclHandler extends Provider implements EventReceiver /** * Evento de actualización * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento * * @throws \SP\Core\Exceptions\SPException */ @@ -125,9 +136,6 @@ final class AclHandler extends Provider implements EventReceiver } } - /** - * @param Event $event - */ private function processUserProfile(Event $event): void { try { @@ -140,9 +148,7 @@ final class AclHandler extends Provider implements EventReceiver $extra = $eventMessage->getExtra(); if (isset($extra['userProfileId'])) { - $userProfileService = $this->dic->get(UserProfileService::class); - - foreach ($userProfileService->getUsersForProfile($extra['userProfileId'][0]) as $user) { + foreach ($this->userProfileService->getUsersForProfile($extra['userProfileId'][0]) as $user) { AccountAclService::clearAcl($user->id); } } @@ -152,8 +158,6 @@ final class AclHandler extends Provider implements EventReceiver } /** - * @param Event $event - * * @throws \SP\Core\Exceptions\SPException */ private function processUser(Event $event): void @@ -173,9 +177,6 @@ final class AclHandler extends Provider implements EventReceiver } } - /** - * @param Event $event - */ private function processUserGroup(Event $event): void { try { @@ -188,9 +189,7 @@ final class AclHandler extends Provider implements EventReceiver $extra = $eventMessage->getExtra(); if (isset($extra['userGroupId'])) { - $userGroupService = $this->dic->get(UserGroupService::class); - - foreach ($userGroupService->getUsageByUsers($extra['userGroupId'][0]) as $user) { + foreach ($this->userGroupService->getUsageByUsers($extra['userGroupId'][0]) as $user) { AccountAclService::clearAcl($user->id); } } @@ -199,12 +198,8 @@ final class AclHandler extends Provider implements EventReceiver } } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - $this->dic = $dic; $this->events = $this->parseEventsToRegex(self::EVENTS); } } \ No newline at end of file diff --git a/lib/SP/Providers/Auth/AuthProvider.php b/lib/SP/Providers/Auth/AuthProvider.php index 2cbab444..1c6967ec 100644 --- a/lib/SP/Providers/Auth/AuthProvider.php +++ b/lib/SP/Providers/Auth/AuthProvider.php @@ -24,7 +24,9 @@ namespace SP\Providers\Auth; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; +use SP\Core\Events\EventDispatcher; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\UserLoginData; @@ -50,12 +52,27 @@ class AuthProvider extends Provider /** * @var callable[] */ - protected array $auths = []; + protected array $auths = []; + protected Browser $browser; + protected Database $database; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + Browser $browser, + Database $database + ) { + $this->browser = $browser; + $this->database = $database; + + parent::__construct($config, $context, $eventDispatcher); + } /** * Probar los métodos de autentificación * - * @param UserLoginData $userLoginData + * @param UserLoginData $userLoginData * * @return false|AuthResult[] */ @@ -75,23 +92,21 @@ class AuthProvider extends Provider } /** - * Auth constructor. - * - * @param ContainerInterface $dic + * Auth initializer * * @throws AuthException */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { $configData = $this->config->getConfigData(); if ($configData->isAuthBasicEnabled()) { $this->registerAuth( - function (UserLoginData $userLoginData) use ($dic) { - $dic->get(Browser::class) - ->authenticate($userLoginData); + function (UserLoginData $userLoginData) { + $this->browser->authenticate($userLoginData); }, - 'authBrowser'); + 'authBrowser' + ); } if ($configData->isLdapEnabled()) { @@ -116,11 +131,13 @@ class AuthProvider extends Provider $ldapParams->setFilterUserAttributes($configData->getLdapFilterUserAttributes()); $ldapParams->setFilterGroupAttributes($configData->getLdapFilterGroupAttributes()); + // TODO: Use IoC?? $ldapAuth = new LdapAuth( Ldap::factory( $ldapParams, $this->eventDispatcher, - $configData->isDebug()), + $configData->isDebug() + ), $this->eventDispatcher, $configData ); @@ -140,13 +157,13 @@ class AuthProvider extends Provider return $ldapAuthData; }, - 'authLdap'); + 'authLdap' + ); } $this->registerAuth( - function (UserLoginData $userLoginData) use ($dic) { - return $dic->get(Database::class) - ->authenticate($userLoginData); + function (UserLoginData $userLoginData) { + return $this->database->authenticate($userLoginData); }, 'authDatabase' ); @@ -155,17 +172,19 @@ class AuthProvider extends Provider /** * Registrar un método de autentificación primarios * - * @param callable $auth Función de autentificación - * @param string $name + * @param callable $auth Función de autentificación + * @param string $name * * @throws AuthException */ private function registerAuth(callable $auth, string $name): void { if (array_key_exists($name, $this->auths)) { - throw new AuthException(__u('Authentication already initialized'), + throw new AuthException( + __u('Authentication already initialized'), SPException::ERROR, - __FUNCTION__); + __FUNCTION__ + ); } $this->auths[$name] = $auth; diff --git a/lib/SP/Providers/Log/DatabaseLogHandler.php b/lib/SP/Providers/Log/DatabaseLogHandler.php index b4951163..39b73ad8 100644 --- a/lib/SP/Providers/Log/DatabaseLogHandler.php +++ b/lib/SP/Providers/Log/DatabaseLogHandler.php @@ -25,8 +25,10 @@ namespace SP\Providers\Log; use Exception; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\InvalidClassException; use SP\Core\Exceptions\SPException; @@ -46,25 +48,30 @@ final class DatabaseLogHandler extends Provider implements EventReceiver { use EventsTrait; - /** - * @var EventlogService - */ private EventlogService $eventlogService; - /** - * @var string - */ - private string $events; - /** - * @var Language - */ - private Language $language; + private Language $language; + private string $events; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + EventlogService $eventlogService, + Language $language + ) { + $this->eventlogService = $eventlogService; + $this->language = $language; + + parent::__construct($config, $context, $eventDispatcher); + } + /** * Receive update from subject * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -80,8 +87,8 @@ final class DatabaseLogHandler extends Provider implements EventReceiver /** * Evento de actualización * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento * * @throws InvalidClassException */ @@ -105,7 +112,7 @@ final class DatabaseLogHandler extends Provider implements EventReceiver $hint = $source->getHint(); if ($hint !== null) { - $eventlogData->setDescription(__($source->getMessage()) . PHP_EOL . $hint); + $eventlogData->setDescription(__($source->getMessage()).PHP_EOL.$hint); } else { $eventlogData->setDescription(__($source->getMessage())); } @@ -145,14 +152,8 @@ final class DatabaseLogHandler extends Provider implements EventReceiver return LogInterface::EVENTS; } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - $this->language = $dic->get(Language::class); - $this->eventlogService = $dic->get(EventlogService::class); - $configEvents = $this->config->getConfigData()->getLogEvents(); if (count($configEvents) === 0) { diff --git a/lib/SP/Providers/Log/FileLogHandler.php b/lib/SP/Providers/Log/FileLogHandler.php index da47cfd7..9426ec16 100644 --- a/lib/SP/Providers/Log/FileLogHandler.php +++ b/lib/SP/Providers/Log/FileLogHandler.php @@ -26,7 +26,6 @@ namespace SP\Providers\Log; use Monolog\Handler\StreamHandler; -use Psr\Container\ContainerInterface; use SP\Core\Events\Event; use SP\Core\Exceptions\InvalidClassException; use SP\Providers\EventsTrait; @@ -66,7 +65,7 @@ final class FileLogHandler extends LoggerBase * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -74,18 +73,15 @@ final class FileLogHandler extends LoggerBase * @throws InvalidClassException * @since 5.1.0 */ - public function update(SplSubject $subject) + public function update(SplSubject $subject): void { $this->updateEvent('update', new Event($subject)); } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - parent::initialize($dic); - $this->logger->pushHandler(new StreamHandler(LOG_FILE)); + + parent::initialize(); } } \ No newline at end of file diff --git a/lib/SP/Providers/Log/LoggerBase.php b/lib/SP/Providers/Log/LoggerBase.php index 91564a46..64174789 100644 --- a/lib/SP/Providers/Log/LoggerBase.php +++ b/lib/SP/Providers/Log/LoggerBase.php @@ -26,8 +26,10 @@ namespace SP\Providers\Log; use Exception; use Monolog\Logger; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\InvalidClassException; use SP\Core\Language; @@ -44,29 +46,44 @@ abstract class LoggerBase extends Provider implements EventReceiver { use EventsTrait; - public const MESSAGE_FORMAT = 'event="%s";address="%s";user="%s";message="%s"'; - /** - * @var Logger - */ - protected Logger $logger; - /** - * @var Request - */ - protected Request $request; - /** - * @var string - */ - protected string $events; - /** - * @var Language - */ + protected Logger $logger; protected Language $language; + protected Request $request; + protected string $events; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + Logger $logger, + Language $language, + Request $request + ) { + $this->logger = $logger; + $this->language = $language; + $this->request = $request; + + parent::__construct($config, $context, $eventDispatcher); + } + + /** + */ + public function initialize(): void + { + $configEvents = $this->config->getConfigData()->getLogEvents(); + + if (count($configEvents) === 0) { + $this->events = $this->parseEventsToRegex(LogInterface::EVENTS_FIXED); + } else { + $this->events = $this->parseEventsToRegex(array_merge($configEvents, LogInterface::EVENTS_FIXED)); + } + } /** * Evento de actualización * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento * * @throws InvalidClassException */ @@ -115,9 +132,9 @@ abstract class LoggerBase extends Provider implements EventReceiver } /** - * @param string $message - * @param string $address - * @param string $user + * @param string $message + * @param string $address + * @param string $user * * @return array */ @@ -125,32 +142,12 @@ abstract class LoggerBase extends Provider implements EventReceiver string $message, string $address, string $user - ): array - { + ): array { return [ 'message' => trim($message), - 'user' => trim($user), + 'user' => trim($user), 'address' => trim($address), - 'caller' => getLastCaller(4) + 'caller' => getLastCaller(4), ]; } - - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void - { - $this->language = $dic->get(Language::class); - $this->request = $dic->get(Request::class); - - $configEvents = $this->config->getConfigData()->getLogEvents(); - - if (count($configEvents) === 0) { - $this->events = $this->parseEventsToRegex(LogInterface::EVENTS_FIXED); - } else { - $this->events = $this->parseEventsToRegex(array_merge($configEvents, LogInterface::EVENTS_FIXED)); - } - - $this->logger = $dic->get(Logger::class); - } } \ No newline at end of file diff --git a/lib/SP/Providers/Log/RemoteSyslogHandler.php b/lib/SP/Providers/Log/RemoteSyslogHandler.php index 51f8959a..ceb81d14 100644 --- a/lib/SP/Providers/Log/RemoteSyslogHandler.php +++ b/lib/SP/Providers/Log/RemoteSyslogHandler.php @@ -26,7 +26,6 @@ namespace SP\Providers\Log; use Monolog\Handler\SyslogUdpHandler; use Monolog\Logger; -use Psr\Container\ContainerInterface; use SP\Core\Events\Event; use SP\Core\Exceptions\InvalidClassException; use SplSubject; @@ -63,7 +62,7 @@ final class RemoteSyslogHandler extends LoggerBase * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -76,13 +75,8 @@ final class RemoteSyslogHandler extends LoggerBase $this->updateEvent('update', new Event($subject)); } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - parent::initialize($dic); - $configData = $this->config->getConfigData(); $this->logger->pushHandler( @@ -95,5 +89,7 @@ final class RemoteSyslogHandler extends LoggerBase 'syspass' ) ); + + parent::initialize(); } } \ No newline at end of file diff --git a/lib/SP/Providers/Log/SyslogHandler.php b/lib/SP/Providers/Log/SyslogHandler.php index b655a393..cdf501e9 100644 --- a/lib/SP/Providers/Log/SyslogHandler.php +++ b/lib/SP/Providers/Log/SyslogHandler.php @@ -25,7 +25,6 @@ namespace SP\Providers\Log; use Monolog\Handler\SyslogHandler as MSyslogHandler; -use Psr\Container\ContainerInterface; use SP\Core\Events\Event; use SP\Core\Exceptions\InvalidClassException; use SplSubject; @@ -62,7 +61,7 @@ final class SyslogHandler extends LoggerBase * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -76,12 +75,11 @@ final class SyslogHandler extends LoggerBase } /** - * @param ContainerInterface $dic */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - parent::initialize($dic); - $this->logger->pushHandler(new MSyslogHandler('syspass')); + + parent::initialize(); } } \ No newline at end of file diff --git a/lib/SP/Providers/Mail/MailHandler.php b/lib/SP/Providers/Mail/MailHandler.php index e75e9226..119974c2 100644 --- a/lib/SP/Providers/Mail/MailHandler.php +++ b/lib/SP/Providers/Mail/MailHandler.php @@ -25,8 +25,10 @@ namespace SP\Providers\Mail; use Exception; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Messages\MailMessage; use SP\Core\Messages\TextFormatter; @@ -52,7 +54,7 @@ final class MailHandler extends Provider implements EventReceiver 'save.', 'import.ldap.end', 'run.backup.end', - 'run.import.end' + 'run.import.end', ]; public const EVENTS_FIXED = [ @@ -63,21 +65,25 @@ final class MailHandler extends Provider implements EventReceiver 'request.account', 'edit.user.password', 'save.config.', - 'create.tempMasterPassword' + 'create.tempMasterPassword', ]; - /** - * @var MailService - */ private MailService $mailService; - /** - * @var string - */ - private string $events; - /** - * @var Request - */ - private Request $request; + private Request $request; + private string $events; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + MailService $mailService, + Request $request + ) { + $this->mailService = $mailService; + $this->request = $request; + + parent::__construct($config, $context, $eventDispatcher); + } /** * Devuelve los eventos que implementa el observador @@ -104,7 +110,7 @@ final class MailHandler extends Provider implements EventReceiver * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -119,8 +125,8 @@ final class MailHandler extends Provider implements EventReceiver /** * Evento de actualización * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento */ public function updateEvent(string $eventType, Event $event): void { @@ -193,14 +199,8 @@ final class MailHandler extends Provider implements EventReceiver } } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - $this->mailService = $dic->get(MailService::class); - $this->request = $dic->get(Request::class); - $configEvents = $this->config->getConfigData()->getMailEvents(); if (count($configEvents) === 0) { diff --git a/lib/SP/Providers/Mail/MailProvider.php b/lib/SP/Providers/Mail/MailProvider.php index 7059cf48..c116bde8 100644 --- a/lib/SP/Providers/Mail/MailProvider.php +++ b/lib/SP/Providers/Mail/MailProvider.php @@ -26,8 +26,10 @@ namespace SP\Providers\Mail; use Exception; use PHPMailer\PHPMailer\PHPMailer; -use Psr\Container\ContainerInterface; +use SP\Config\Config; use SP\Core\AppInfoInterface; +use SP\Core\Context\ContextInterface; +use SP\Core\Events\EventDispatcher; use SP\Core\Exceptions\SPException; use SP\Providers\Provider; @@ -38,19 +40,24 @@ use SP\Providers\Provider; */ final class MailProvider extends Provider { - /** - * @var PHPMailer - */ private PHPMailer $mailer; - /** - * @var bool - */ - private bool $debug = false; + private bool $debug = false; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + PHPMailer $mailer + ) { + $this->mailer = $mailer; + + parent::__construct($config, $context, $eventDispatcher); + } /** * Inicializar la clase PHPMailer. * - * @param MailParams $mailParams + * @param MailParams $mailParams * * @return PHPMailer * @throws MailProviderException @@ -108,18 +115,15 @@ final class MailProvider extends Provider } /** - * @param bool $debug + * @param bool $debug */ public function setDebug(bool $debug) { $this->debug = $debug; } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - $this->mailer = $dic->get(PHPMailer::class); + // TODO: Implement initialize() method. } } \ No newline at end of file diff --git a/lib/SP/Providers/Notification/NotificationHandler.php b/lib/SP/Providers/Notification/NotificationHandler.php index b4bb19d9..d51486b9 100644 --- a/lib/SP/Providers/Notification/NotificationHandler.php +++ b/lib/SP/Providers/Notification/NotificationHandler.php @@ -25,8 +25,10 @@ namespace SP\Providers\Notification; use Exception; -use Psr\Container\ContainerInterface; +use SP\Config\Config; +use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\DataModel\NotificationData; use SP\Providers\EventsTrait; @@ -45,17 +47,22 @@ final class NotificationHandler extends Provider implements EventReceiver public const EVENTS = [ 'request.account', - 'show.account.link' + 'show.account.link', ]; - /** - * @var NotificationService - */ private NotificationService $notificationService; - /** - * @var string - */ - private string $events; + private string $events; + + public function __construct( + Config $config, + ContextInterface $context, + EventDispatcher $eventDispatcher, + NotificationService $notificationService + ) { + $this->notificationService = $notificationService; + + parent::__construct($config, $context, $eventDispatcher); + } /** * Devuelve los eventos que implementa el observador @@ -82,7 +89,7 @@ final class NotificationHandler extends Provider implements EventReceiver * * @link http://php.net/manual/en/splobserver.update.php * - * @param SplSubject $subject+ * @param SplSubject $subject
* The SplSubject notifying the observer of an update. *
* @@ -97,8 +104,8 @@ final class NotificationHandler extends Provider implements EventReceiver /** * Evento de actualización * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento */ public function updateEvent(string $eventType, Event $event): void { @@ -113,7 +120,7 @@ final class NotificationHandler extends Provider implements EventReceiver } /** - * @param Event $event + * @param Event $event */ private function requestAccountNotification(Event $event): void { @@ -132,7 +139,7 @@ final class NotificationHandler extends Provider implements EventReceiver } /** - * @param NotificationData $notificationData + * @param NotificationData $notificationData */ private function notify(NotificationData $notificationData): void { @@ -144,7 +151,7 @@ final class NotificationHandler extends Provider implements EventReceiver } /** - * @param Event $event + * @param Event $event */ private function showAccountLinkNotification(Event $event): void { @@ -162,13 +169,8 @@ final class NotificationHandler extends Provider implements EventReceiver } } - /** - * @param ContainerInterface $dic - */ - protected function initialize(ContainerInterface $dic): void + public function initialize(): void { - $this->notificationService = $dic->get(NotificationService::class); - $this->events = $this->parseEventsToRegex(self::EVENTS); } } \ No newline at end of file diff --git a/lib/SP/Providers/Provider.php b/lib/SP/Providers/Provider.php index eb0e5b9b..53174431 100644 --- a/lib/SP/Providers/Provider.php +++ b/lib/SP/Providers/Provider.php @@ -24,7 +24,6 @@ namespace SP\Providers; -use Psr\Container\ContainerInterface; use SP\Config\Config; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; @@ -34,36 +33,23 @@ use SP\Core\Events\EventDispatcher; * * @package SP\Providers */ -abstract class Provider +abstract class Provider implements ProviderInterface { - public const STATUS_INTERNAL_ERROR = 1000; - - /** - * @var Config - */ - protected $config; - /** - * @var ContextInterface - */ - protected $context; - /** - * @var EventDispatcher - */ - protected $eventDispatcher; + protected Config $config; + protected ContextInterface $context; + protected EventDispatcher $eventDispatcher; /** * Provider constructor. * - * @param ContainerInterface $dic + * @param Config $config + * @param ContextInterface $context + * @param EventDispatcher $eventDispatcher */ - final public function __construct(ContainerInterface $dic) + public function __construct(Config $config, ContextInterface $context, EventDispatcher $eventDispatcher) { - $this->config = $dic->get(Config::class); - $this->context = $dic->get(ContextInterface::class); - $this->eventDispatcher = $dic->get(EventDispatcher::class); - - if (method_exists($this, 'initialize')) { - $this->initialize($dic); - } + $this->config = $config; + $this->context = $context; + $this->eventDispatcher = $eventDispatcher; } } \ No newline at end of file diff --git a/lib/SP/Providers/ProviderInterface.php b/lib/SP/Providers/ProviderInterface.php new file mode 100644 index 00000000..5f824220 --- /dev/null +++ b/lib/SP/Providers/ProviderInterface.php @@ -0,0 +1,34 @@ +. + */ + +namespace SP\Providers; + + +/** + * ProviderInterface + */ +interface ProviderInterface +{ + public function initialize(): void; +} \ No newline at end of file diff --git a/lib/SP/Services/Auth/LoginService.php b/lib/SP/Services/Auth/LoginService.php index ec2512df..bf1e42cb 100644 --- a/lib/SP/Services/Auth/LoginService.php +++ b/lib/SP/Services/Auth/LoginService.php @@ -35,7 +35,6 @@ use SP\Config\ConfigDataInterface; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ConstraintException; -use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\Core\Language; @@ -72,25 +71,25 @@ final class LoginService extends Service /** * Estados */ - private const STATUS_INVALID_LOGIN = 1; - private const STATUS_INVALID_MASTER_PASS = 2; - private const STATUS_USER_DISABLED = 3; - private const STATUS_NEED_OLD_PASS = 5; + private const STATUS_INVALID_LOGIN = 1; + private const STATUS_INVALID_MASTER_PASS = 2; + private const STATUS_USER_DISABLED = 3; + private const STATUS_NEED_OLD_PASS = 5; private const STATUS_MAX_ATTEMPTS_EXCEEDED = 6; - private const STATUS_PASS_RESET = 7; - private const STATUS_PASS = 0; - private const STATUS_NONE = 100; + private const STATUS_PASS_RESET = 7; + private const STATUS_PASS = 0; + private const STATUS_NONE = 100; - private ?AuthProvider $authProvider = null; - private ?UserLoginData $userLoginData = null; - private ?ConfigDataInterface $configData = null; - private ?ThemeInterface $theme = null; - private ?UserService $userService = null; - private ?Language $language = null; - private ?TrackService $trackService = null; - private ?TrackRequest $trackRequest = null; - private ?string $from = null; - private ?Request $request = null; + private ?AuthProvider $authProvider = null; + private ?UserLoginData $userLoginData = null; + private ?ConfigDataInterface $configData = null; + private ?ThemeInterface $theme = null; + private ?UserService $userService = null; + private ?Language $language = null; + private ?TrackService $trackService = null; + private ?TrackRequest $trackRequest = null; + private ?string $from = null; + private ?Request $request = null; /** * Ejecutar las acciones de login @@ -222,9 +221,11 @@ final class LoginService extends Service if ($userLoginResponse->getIsDisabled()) { $this->eventDispatcher->notifyEvent( 'login.checkUser.disabled', - new Event($this, EventMessage::factory() + new Event( + $this, EventMessage::factory() ->addDescription(__u('User disabled')) - ->addDetail(__u('User'), $userLoginResponse->getLogin())) + ->addDetail(__u('User'), $userLoginResponse->getLogin()) + ) ); $this->addTracking(); @@ -241,8 +242,10 @@ final class LoginService extends Service if ($userLoginResponse->getIsChangePass()) { $this->eventDispatcher->notifyEvent( 'login.checkUser.changePass', - new Event($this, EventMessage::factory() - ->addDetail(__u('User'), $userLoginResponse->getLogin())) + new Event( + $this, EventMessage::factory() + ->addDetail(__u('User'), $userLoginResponse->getLogin()) + ) ); $hash = PasswordUtil::generateRandomBytes(16); @@ -251,7 +254,7 @@ final class LoginService extends Service ->add($userLoginResponse->getId(), $hash); $uri = new Uri('index.php'); - $uri->addParam('r', 'userPassReset/reset/' . $hash); + $uri->addParam('r', 'userPassReset/reset/'.$hash); return new LoginResponse( self::STATUS_PASS_RESET, @@ -284,8 +287,10 @@ final class LoginService extends Service if ($temporaryMasterPass->checkTempMasterPass($masterPass)) { $this->eventDispatcher->notifyEvent( 'login.masterPass.temporary', - new Event($this, EventMessage::factory() - ->addDescription(__u('Using temporary password'))) + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Using temporary password')) + ) ); $masterPass = $temporaryMasterPass->getUsingKey($masterPass); @@ -293,12 +298,15 @@ final class LoginService extends Service if ($userPassService->updateMasterPassOnLogin( $masterPass, - $this->userLoginData)->getStatus() !== UserPassService::MPASS_OK + $this->userLoginData + )->getStatus() !== UserPassService::MPASS_OK ) { $this->eventDispatcher->notifyEvent( 'login.masterPass', - new Event($this, EventMessage::factory() - ->addDescription(__u('Wrong master password'))) + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Wrong master password')) + ) ); $this->addTracking(); @@ -313,55 +321,64 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.masterPass', - new Event($this, EventMessage::factory() - ->addDescription(__u('Master password updated'))) - ); - } else if ($oldPass) { - if ($userPassService->updateMasterPassFromOldPass( - $oldPass, - $this->userLoginData)->getStatus() !== UserPassService::MPASS_OK - ) { - $this->eventDispatcher->notifyEvent( - 'login.masterPass', - new Event($this, EventMessage::factory() - ->addDescription(__u('Wrong master password'))) - ); - - $this->addTracking(); - - throw new AuthException( - __u('Wrong master password'), - SPException::INFO, - null, - self::STATUS_INVALID_MASTER_PASS - ); - } - - $this->eventDispatcher->notifyEvent( - 'login.masterPass', - new Event($this, EventMessage::factory() - ->addDescription(__u('Master password updated'))) + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Master password updated')) + ) ); } else { - switch ($userPassService->loadUserMPass($this->userLoginData)->getStatus()) { - case UserPassService::MPASS_CHECKOLD: - throw new AuthException( - __u('Your previous password is needed'), - SPException::INFO, - null, - self::STATUS_NEED_OLD_PASS + if ($oldPass) { + if ($userPassService->updateMasterPassFromOldPass( + $oldPass, + $this->userLoginData + )->getStatus() !== UserPassService::MPASS_OK + ) { + $this->eventDispatcher->notifyEvent( + 'login.masterPass', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Wrong master password')) + ) ); - case UserPassService::MPASS_NOTSET: - case UserPassService::MPASS_CHANGED: - case UserPassService::MPASS_WRONG: + $this->addTracking(); throw new AuthException( - __u('The Master Password either is not saved or is wrong'), + __u('Wrong master password'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS ); + } + + $this->eventDispatcher->notifyEvent( + 'login.masterPass', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Master password updated')) + ) + ); + } else { + switch ($userPassService->loadUserMPass($this->userLoginData)->getStatus()) { + case UserPassService::MPASS_CHECKOLD: + throw new AuthException( + __u('Your previous password is needed'), + SPException::INFO, + null, + self::STATUS_NEED_OLD_PASS + ); + case UserPassService::MPASS_NOTSET: + case UserPassService::MPASS_CHANGED: + case UserPassService::MPASS_WRONG: + $this->addTracking(); + + throw new AuthException( + __u('The Master Password either is not saved or is wrong'), + SPException::INFO, + null, + self::STATUS_INVALID_MASTER_PASS + ); + } } } } catch (CryptoException $e) { @@ -412,8 +429,10 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.session.load', - new Event($this, EventMessage::factory() - ->addDetail(__u('User'), $userLoginResponse->getLogin())) + new Event( + $this, EventMessage::factory() + ->addDetail(__u('User'), $userLoginResponse->getLogin()) + ) ); } @@ -443,7 +462,7 @@ final class LoginService extends Service } /** - * @param string|null $from + * @param string|null $from */ public function setFrom(?string $from): void { @@ -451,9 +470,10 @@ final class LoginService extends Service } /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws InvalidArgumentException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + * @throws \SP\Core\Exceptions\InvalidArgumentException + * @throws \SP\Services\Auth\AuthException */ protected function initialize(): void { @@ -466,12 +486,14 @@ final class LoginService extends Service $this->userLoginData = new UserLoginData(); $this->trackRequest = $this->trackService->getTrackRequest(__CLASS__); $this->authProvider = $this->dic->get(AuthProvider::class); + + $this->authProvider->initialize(); } /** * Autentificación LDAP * - * @param LdapAuthData $authData + * @param LdapAuthData $authData * * @return bool * @throws SPException @@ -565,7 +587,8 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.auth.ldap', - new Event($this, EventMessage::factory() + new Event( + $this, EventMessage::factory() ->addDetail(__u('Type'), __FUNCTION__) ->addDetail(__u('LDAP Server'), $authData->getServer()) ) @@ -610,7 +633,7 @@ final class LoginService extends Service /** * Autentificación en BD * - * @param DatabaseAuthData $authData + * @param DatabaseAuthData $authData * * @return bool * @throws SPException @@ -663,7 +686,7 @@ final class LoginService extends Service /** * Comprobar si el cliente ha enviado las variables de autentificación * - * @param BrowserAuthData $authData + * @param BrowserAuthData $authData * * @return bool * @throws AuthException