| Total Complexity | 44 |
| Total Lines | 410 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like Bootstrap often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Bootstrap, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 61 | final class Bootstrap |
||
| 62 | { |
||
| 63 | /** |
||
| 64 | * @var string The current request path relative to the sysPass root (e.g. files/index.php) |
||
| 65 | */ |
||
| 66 | public static $WEBROOT = ''; |
||
| 67 | /** |
||
| 68 | * @var string The full URL to reach sysPass (e.g. https://sub.example.com/syspass/) |
||
| 69 | */ |
||
| 70 | public static $WEBURI = ''; |
||
| 71 | /** |
||
| 72 | * @var string |
||
| 73 | */ |
||
| 74 | public static $SUBURI = ''; |
||
| 75 | /** |
||
| 76 | * @var mixed |
||
| 77 | */ |
||
| 78 | public static $LOCK; |
||
| 79 | /** |
||
| 80 | * @var bool Indica si la versión de PHP es correcta |
||
| 81 | */ |
||
| 82 | public static $checkPhpVersion; |
||
| 83 | /** |
||
| 84 | * @var ContainerInterface |
||
| 85 | */ |
||
| 86 | private static $container; |
||
| 87 | /** |
||
| 88 | * @var Klein |
||
| 89 | */ |
||
| 90 | private $router; |
||
| 91 | /** |
||
| 92 | * @var Language |
||
| 93 | */ |
||
| 94 | private $language; |
||
| 95 | /** |
||
| 96 | * @var Request |
||
| 97 | */ |
||
| 98 | private $request; |
||
| 99 | /** |
||
| 100 | * @var Config |
||
| 101 | */ |
||
| 102 | private $config; |
||
| 103 | /** |
||
| 104 | * @var ConfigData |
||
| 105 | */ |
||
| 106 | private $configData; |
||
| 107 | |||
| 108 | /** |
||
| 109 | * Bootstrap constructor. |
||
| 110 | * |
||
| 111 | * @param Container $container |
||
| 112 | * |
||
| 113 | * @throws \DI\DependencyException |
||
| 114 | * @throws \DI\NotFoundException |
||
| 115 | */ |
||
| 116 | private final function __construct(Container $container) |
||
| 117 | { |
||
| 118 | self::$container = $container; |
||
| 119 | |||
| 120 | // Set the default language |
||
| 121 | Language::setLocales('en_US'); |
||
| 122 | |||
| 123 | $this->config = $container->get(Config::class); |
||
| 124 | $this->configData = $this->config->getConfigData(); |
||
| 125 | $this->router = $container->get(Klein::class); |
||
| 126 | $this->request = $container->get(Request::class); |
||
| 127 | $this->language = $container->get(Language::class); |
||
| 128 | |||
| 129 | $this->initRouter(); |
||
| 130 | } |
||
| 131 | |||
| 132 | /** |
||
| 133 | * Inicializar router |
||
| 134 | */ |
||
| 135 | protected function initRouter() |
||
| 136 | { |
||
| 137 | $oops = "Oops, it looks like this content does not exist..."; |
||
| 138 | |||
| 139 | $this->router->onError(function ($router, $err_msg, $type, $err) { |
||
| 140 | logger('Routing error: ' . $err_msg); |
||
| 141 | |||
| 142 | /** @var Exception|\Throwable $err */ |
||
| 143 | logger('Routing error: ' . $err->getTraceAsString()); |
||
| 144 | |||
| 145 | /** @var Klein $router */ |
||
| 146 | $router->response()->body(__($err_msg)); |
||
| 147 | }); |
||
| 148 | |||
| 149 | // Manage requests for api module |
||
| 150 | $this->router->respond(['POST'], |
||
| 151 | '@/api\.php', |
||
| 152 | function ($request, $response, $service) use ($oops) { |
||
| 153 | try { |
||
| 154 | logger('API route'); |
||
| 155 | |||
| 156 | $apiRequest = self::$container->get(ApiRequest::class); |
||
| 157 | |||
| 158 | list($controller, $action) = explode('/', $apiRequest->getMethod()); |
||
| 159 | |||
| 160 | $controllerClass = 'SP\\Modules\\' . ucfirst(APP_MODULE) . '\\Controllers\\' . ucfirst($controller) . 'Controller'; |
||
| 161 | $method = $action . 'Action'; |
||
| 162 | |||
| 163 | if (!method_exists($controllerClass, $method)) { |
||
| 164 | logger($controllerClass . '::' . $method); |
||
| 165 | |||
| 166 | /** @var Response $response */ |
||
| 167 | $response->headers()->set('Content-type', 'application/json; charset=utf-8'); |
||
| 168 | return $response->body(JsonRpcResponse::getResponseError($oops, JsonRpcResponse::METHOD_NOT_FOUND, $apiRequest->getId())); |
||
| 169 | } |
||
| 170 | |||
| 171 | $this->initializeCommon(); |
||
| 172 | |||
| 173 | self::$container->get(InitApi::class) |
||
| 174 | ->initialize($controller); |
||
| 175 | |||
| 176 | logger('Routing call: ' . $controllerClass . '::' . $method); |
||
| 177 | |||
| 178 | return call_user_func([new $controllerClass(self::$container, $method, $apiRequest), $method]); |
||
| 179 | } catch (\Exception $e) { |
||
| 180 | processException($e); |
||
| 181 | |||
| 182 | /** @var Response $response */ |
||
| 183 | $response->headers()->set('Content-type', 'application/json; charset=utf-8'); |
||
| 184 | return $response->body(JsonRpcResponse::getResponseException($e, 0)); |
||
| 185 | |||
| 186 | } finally { |
||
| 187 | $this->router->skipRemaining(); |
||
| 188 | } |
||
| 189 | } |
||
| 190 | ); |
||
| 191 | |||
| 192 | // Manage requests for web module |
||
| 193 | $this->router->respond(['GET', 'POST'], |
||
| 194 | '@(?!/api\.php)', |
||
| 195 | function ($request, $response, $service) use ($oops) { |
||
| 196 | try { |
||
| 197 | logger('WEB route'); |
||
| 198 | |||
| 199 | /** @var \Klein\Request $request */ |
||
| 200 | $route = Filter::getString($request->param('r', 'index/index')); |
||
| 201 | |||
| 202 | if (!preg_match_all('#(?P<controller>[a-zA-Z]+)(?:/(?P<action>[a-zA-Z]+))?(?P<params>(/[a-zA-Z\d\.]+)+)?#', $route, $matches)) { |
||
| 203 | throw new RuntimeException($oops); |
||
| 204 | } |
||
| 205 | |||
| 206 | // $app = $matches['app'][0] ?: 'web'; |
||
| 207 | $controllerName = $matches['controller'][0]; |
||
| 208 | $methodName = !empty($matches['action'][0]) ? $matches['action'][0] . 'Action' : 'indexAction'; |
||
| 209 | $methodParams = !empty($matches['params'][0]) ? Filter::getArray(explode('/', trim($matches['params'][0], '/'))) : []; |
||
| 210 | |||
| 211 | $controllerClass = 'SP\\Modules\\' . ucfirst(APP_MODULE) . '\\Controllers\\' . ucfirst($controllerName) . 'Controller'; |
||
| 212 | |||
| 213 | $this->initializePluginClasses(); |
||
| 214 | |||
| 215 | if (!method_exists($controllerClass, $methodName)) { |
||
| 216 | logger($controllerClass . '::' . $methodName); |
||
| 217 | |||
| 218 | /** @var Response $response */ |
||
| 219 | $response->code(404); |
||
| 220 | |||
| 221 | throw new RuntimeException($oops); |
||
| 222 | } |
||
| 223 | |||
| 224 | $this->initializeCommon(); |
||
| 225 | |||
| 226 | switch (APP_MODULE) { |
||
| 227 | case 'web': |
||
| 228 | self::$container->get(InitWeb::class) |
||
| 229 | ->initialize($controllerName); |
||
| 230 | break; |
||
| 231 | } |
||
| 232 | |||
| 233 | logger('Routing call: ' . $controllerClass . '::' . $methodName . '::' . print_r($methodParams, true)); |
||
| 234 | |||
| 235 | $controller = new $controllerClass(self::$container, $methodName); |
||
| 236 | |||
| 237 | return call_user_func_array([$controller, $methodName], $methodParams); |
||
| 238 | } catch (SessionTimeout $sessionTimeout) { |
||
| 239 | logger('Session timeout', 'DEBUG'); |
||
| 240 | } catch (\Exception $e) { |
||
| 241 | processException($e); |
||
| 242 | |||
| 243 | /** @var Response $response */ |
||
| 244 | if ($response->status()->getCode() !== 404) { |
||
| 245 | $response->code(503); |
||
| 246 | } |
||
| 247 | |||
| 248 | return __($e->getMessage()); |
||
| 249 | } |
||
| 250 | } |
||
| 251 | ); |
||
| 252 | |||
| 253 | // Manejar URLs que no empiecen por '/admin' |
||
| 254 | // $this->Router->respond('GET', '!@^/(admin|public|service)', |
||
| 255 | // function ($request, $response) { |
||
| 256 | // /** @var Response $response */ |
||
| 257 | // $response->redirect('index.php'); |
||
| 258 | // } |
||
| 259 | // ); |
||
| 260 | } |
||
| 261 | |||
| 262 | /** |
||
| 263 | * @throws ConfigException |
||
| 264 | * @throws Core\Exceptions\CheckException |
||
| 265 | * @throws InitializationException |
||
| 266 | * @throws Services\Upgrade\UpgradeException |
||
| 267 | * @throws \DI\DependencyException |
||
| 268 | * @throws \DI\NotFoundException |
||
| 269 | * @throws Storage\File\FileException |
||
| 270 | */ |
||
| 271 | protected function initializeCommon() |
||
| 272 | { |
||
| 273 | logger(__FUNCTION__); |
||
| 274 | |||
| 275 | self::$checkPhpVersion = Checks::checkPhpVersion(); |
||
| 276 | |||
| 277 | // Initialize authentication variables |
||
| 278 | $this->initAuthVariables(); |
||
| 279 | |||
| 280 | // Initialize logging |
||
| 281 | $this->initPHPVars(); |
||
| 282 | |||
| 283 | // Set application paths |
||
| 284 | $this->initPaths(); |
||
| 285 | |||
| 286 | self::$container->get(PhpExtensionChecker::class)->checkMandatory(); |
||
| 287 | |||
| 288 | if (!self::$checkPhpVersion) { |
||
| 289 | throw new InitializationException( |
||
| 290 | sprintf(__('Required PHP version >= %s <= %s'), '7.0', '7.2'), |
||
| 291 | InitializationException::ERROR, |
||
| 292 | __u('Please update the PHP version to run sysPass') |
||
| 293 | ); |
||
| 294 | } |
||
| 295 | |||
| 296 | // Check and intitialize configuration |
||
| 297 | $this->initConfig(); |
||
| 298 | } |
||
| 299 | |||
| 300 | /** |
||
| 301 | * Establecer variables de autentificación |
||
| 302 | */ |
||
| 303 | private function initAuthVariables() |
||
| 304 | { |
||
| 305 | $server = $this->router->request()->server(); |
||
| 306 | |||
| 307 | // Copiar la cabecera http de autentificación para apache+php-fcgid |
||
| 308 | if ($server->get('HTTP_XAUTHORIZATION') !== null |
||
| 309 | && $server->get('HTTP_AUTHORIZATION') === null) { |
||
| 310 | $server->set('HTTP_AUTHORIZATION', $server->get('HTTP_XAUTHORIZATION')); |
||
| 311 | } |
||
| 312 | |||
| 313 | // Establecer las cabeceras de autentificación para apache+php-cgi |
||
| 314 | // Establecer las cabeceras de autentificación para que apache+php-cgi funcione si la variable es renombrada por apache |
||
| 315 | if (($server->get('HTTP_AUTHORIZATION') !== null |
||
| 316 | && preg_match('/Basic\s+(.*)$/i', $server->get('HTTP_AUTHORIZATION'), $matches)) |
||
| 317 | || ($server->get('REDIRECT_HTTP_AUTHORIZATION') !== null |
||
| 318 | && preg_match('/Basic\s+(.*)$/i', $server->get('REDIRECT_HTTP_AUTHORIZATION'), $matches)) |
||
| 319 | ) { |
||
| 320 | list($name, $password) = explode(':', base64_decode($matches[1]), 2); |
||
| 321 | $server->set('PHP_AUTH_USER', strip_tags($name)); |
||
| 322 | $server->set('PHP_AUTH_PW', strip_tags($password)); |
||
| 323 | } |
||
| 324 | } |
||
| 325 | |||
| 326 | /** |
||
| 327 | * Establecer el nivel de logging |
||
| 328 | */ |
||
| 329 | public function initPHPVars() |
||
| 330 | { |
||
| 331 | if (defined('DEBUG') && DEBUG) { |
||
| 332 | Debug::enable(); |
||
| 333 | } else { |
||
| 334 | // Set debug mode if an Xdebug session is active |
||
| 335 | if (($this->router->request()->cookies()->get('XDEBUG_SESSION') |
||
| 336 | || $this->configData->isDebug()) |
||
| 337 | && !defined('DEBUG') |
||
| 338 | ) { |
||
| 339 | define('DEBUG', true); |
||
| 340 | Debug::enable(); |
||
| 341 | } else { |
||
| 342 | error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE)); |
||
| 343 | ini_set('display_errors', 0); |
||
| 344 | } |
||
| 345 | } |
||
| 346 | |||
| 347 | if (!file_exists(LOG_FILE) |
||
| 348 | && touch(LOG_FILE) |
||
| 349 | && chmod(LOG_FILE, 0600) |
||
| 350 | ) { |
||
| 351 | logger('Setup log file: ' . LOG_FILE); |
||
| 352 | } |
||
| 353 | |||
| 354 | if (date_default_timezone_get() === 'UTC') { |
||
| 355 | date_default_timezone_set('UTC'); |
||
| 356 | } |
||
| 357 | |||
| 358 | // Avoid PHP session cookies from JavaScript |
||
| 359 | ini_set('session.cookie_httponly', '1'); |
||
| 360 | ini_set('session.save_handler', 'files'); |
||
| 361 | } |
||
| 362 | |||
| 363 | /** |
||
| 364 | * Establecer las rutas de la aplicación. |
||
| 365 | * Esta función establece las rutas del sistema de archivos y web de la aplicación. |
||
| 366 | * La variables de clase definidas son $SERVERROOT, $WEBROOT y $SUBURI |
||
| 367 | */ |
||
| 368 | private function initPaths() |
||
| 369 | { |
||
| 370 | self::$SUBURI = '/' . basename($this->request->getServer('SCRIPT_FILENAME')); |
||
| 371 | |||
| 372 | $uri = $this->request->getServer('REQUEST_URI'); |
||
| 373 | |||
| 374 | $pos = strpos($uri, self::$SUBURI); |
||
| 375 | |||
| 376 | if ($pos > 0) { |
||
| 377 | self::$WEBROOT = substr($uri, 0, $pos); |
||
| 378 | } |
||
| 379 | |||
| 380 | self::$WEBURI = $this->request->getHttpHost() . self::$WEBROOT; |
||
| 381 | } |
||
| 382 | |||
| 383 | /** |
||
| 384 | * Cargar la configuración |
||
| 385 | * |
||
| 386 | * @throws ConfigException |
||
| 387 | * @throws Services\Upgrade\UpgradeException |
||
| 388 | * @throws Storage\File\FileException |
||
| 389 | * @throws \DI\DependencyException |
||
| 390 | * @throws \DI\NotFoundException |
||
| 391 | */ |
||
| 392 | private function initConfig() |
||
| 393 | { |
||
| 394 | $this->checkConfigVersion(); |
||
| 395 | |||
| 396 | ConfigUtil::checkConfigDir(); |
||
| 397 | } |
||
| 398 | |||
| 399 | /** |
||
| 400 | * Comprobar la versión de configuración y actualizarla |
||
| 401 | * |
||
| 402 | * @throws Services\Upgrade\UpgradeException |
||
| 403 | * @throws Storage\File\FileException |
||
| 404 | * @throws \DI\DependencyException |
||
| 405 | * @throws \DI\NotFoundException |
||
| 406 | */ |
||
| 407 | private function checkConfigVersion() |
||
| 408 | { |
||
| 409 | if (file_exists(OLD_CONFIG_FILE)) { |
||
| 410 | $upgradeConfigService = self::$container->get(UpgradeConfigService::class); |
||
| 411 | $upgradeConfigService->upgradeOldConfigFile(VersionUtil::getVersionStringNormalized()); |
||
| 412 | } |
||
| 413 | |||
| 414 | $configVersion = UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion()); |
||
| 415 | |||
| 416 | if ($this->configData->isInstalled() |
||
| 417 | && UpgradeConfigService::needsUpgrade($configVersion) |
||
| 418 | ) { |
||
| 419 | $upgradeConfigService = self::$container->get(UpgradeConfigService::class); |
||
| 420 | $upgradeConfigService->upgrade($configVersion, $this->configData); |
||
| 421 | } |
||
| 422 | } |
||
| 423 | |||
| 424 | /** |
||
| 425 | * initializePluginClasses |
||
| 426 | */ |
||
| 427 | protected function initializePluginClasses() |
||
| 428 | { |
||
| 429 | $loader = require APP_ROOT . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; |
||
| 430 | |||
| 431 | foreach (PluginManager::getPlugins() as $name => $base) { |
||
| 432 | $loader->addPsr4($base['namespace'], $base['dir']); |
||
| 433 | } |
||
| 434 | } |
||
| 435 | |||
| 436 | /** |
||
| 437 | * @return ContainerInterface |
||
| 438 | */ |
||
| 439 | public static function getContainer() |
||
| 440 | { |
||
| 441 | return self::$container; |
||
| 442 | } |
||
| 443 | |||
| 444 | /** |
||
| 445 | * @param Container $container |
||
| 446 | * @param string $module |
||
| 447 | * |
||
| 448 | * @throws InitializationException |
||
| 449 | * @throws \DI\DependencyException |
||
| 450 | * @throws \DI\NotFoundException |
||
| 451 | */ |
||
| 452 | public static function run(Container $container, $module = APP_MODULE) |
||
| 471 | } |
||
| 472 | } |
||
| 473 | } |