Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like OC 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 OC, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 61 | class OC { |
||
| 62 | /** |
||
| 63 | * Associative array for autoloading. classname => filename |
||
| 64 | */ |
||
| 65 | public static $CLASSPATH = array(); |
||
| 66 | /** |
||
| 67 | * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
||
| 68 | */ |
||
| 69 | public static $SERVERROOT = ''; |
||
| 70 | /** |
||
| 71 | * the current request path relative to the Nextcloud root (e.g. files/index.php) |
||
| 72 | */ |
||
| 73 | private static $SUBURI = ''; |
||
| 74 | /** |
||
| 75 | * the Nextcloud root path for http requests (e.g. nextcloud/) |
||
| 76 | */ |
||
| 77 | public static $WEBROOT = ''; |
||
| 78 | /** |
||
| 79 | * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
||
| 80 | * web path in 'url' |
||
| 81 | */ |
||
| 82 | public static $APPSROOTS = array(); |
||
| 83 | |||
| 84 | /** |
||
| 85 | * @var string |
||
| 86 | */ |
||
| 87 | public static $configDir; |
||
| 88 | |||
| 89 | /** |
||
| 90 | * requested app |
||
| 91 | */ |
||
| 92 | public static $REQUESTEDAPP = ''; |
||
| 93 | |||
| 94 | /** |
||
| 95 | * check if Nextcloud runs in cli mode |
||
| 96 | */ |
||
| 97 | public static $CLI = false; |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @var \OC\Autoloader $loader |
||
| 101 | */ |
||
| 102 | public static $loader = null; |
||
| 103 | |||
| 104 | /** @var \Composer\Autoload\ClassLoader $composerAutoloader */ |
||
| 105 | public static $composerAutoloader = null; |
||
| 106 | |||
| 107 | /** |
||
| 108 | * @var \OC\Server |
||
| 109 | */ |
||
| 110 | public static $server = null; |
||
| 111 | |||
| 112 | /** |
||
| 113 | * @var \OC\Config |
||
| 114 | */ |
||
| 115 | private static $config = null; |
||
| 116 | |||
| 117 | /** |
||
| 118 | * @throws \RuntimeException when the 3rdparty directory is missing or |
||
| 119 | * the app path list is empty or contains an invalid path |
||
| 120 | */ |
||
| 121 | public static function initPaths() { |
||
| 122 | if(defined('PHPUNIT_CONFIG_DIR')) { |
||
| 123 | self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
||
| 124 | } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
||
| 125 | self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
||
| 126 | } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
||
| 127 | self::$configDir = rtrim($dir, '/') . '/'; |
||
| 128 | } else { |
||
| 129 | self::$configDir = OC::$SERVERROOT . '/config/'; |
||
| 130 | } |
||
| 131 | self::$config = new \OC\Config(self::$configDir); |
||
| 132 | |||
| 133 | OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); |
||
| 134 | /** |
||
| 135 | * FIXME: The following lines are required because we can't yet instantiiate |
||
| 136 | * \OC::$server->getRequest() since \OC::$server does not yet exist. |
||
| 137 | */ |
||
| 138 | $params = [ |
||
| 139 | 'server' => [ |
||
| 140 | 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'], |
||
| 141 | 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'], |
||
| 142 | ], |
||
| 143 | ]; |
||
| 144 | $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config))); |
||
| 145 | $scriptName = $fakeRequest->getScriptName(); |
||
| 146 | if (substr($scriptName, -1) == '/') { |
||
| 147 | $scriptName .= 'index.php'; |
||
| 148 | //make sure suburi follows the same rules as scriptName |
||
| 149 | if (substr(OC::$SUBURI, -9) != 'index.php') { |
||
| 150 | if (substr(OC::$SUBURI, -1) != '/') { |
||
| 151 | OC::$SUBURI = OC::$SUBURI . '/'; |
||
| 152 | } |
||
| 153 | OC::$SUBURI = OC::$SUBURI . 'index.php'; |
||
| 154 | } |
||
| 155 | } |
||
| 156 | |||
| 157 | |||
| 158 | if (OC::$CLI) { |
||
| 159 | OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
||
| 160 | } else { |
||
| 161 | if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
||
| 162 | OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
||
| 163 | |||
| 164 | if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
||
| 165 | OC::$WEBROOT = '/' . OC::$WEBROOT; |
||
| 166 | } |
||
| 167 | } else { |
||
| 168 | // The scriptName is not ending with OC::$SUBURI |
||
| 169 | // This most likely means that we are calling from CLI. |
||
| 170 | // However some cron jobs still need to generate |
||
| 171 | // a web URL, so we use overwritewebroot as a fallback. |
||
| 172 | OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
||
| 173 | } |
||
| 174 | |||
| 175 | // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
||
| 176 | // slash which is required by URL generation. |
||
| 177 | if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
||
| 178 | substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
||
| 179 | header('Location: '.\OC::$WEBROOT.'/'); |
||
| 180 | exit(); |
||
| 181 | } |
||
| 182 | } |
||
| 183 | |||
| 184 | // search the apps folder |
||
| 185 | $config_paths = self::$config->getValue('apps_paths', array()); |
||
| 186 | if (!empty($config_paths)) { |
||
| 187 | foreach ($config_paths as $paths) { |
||
| 188 | if (isset($paths['url']) && isset($paths['path'])) { |
||
| 189 | $paths['url'] = rtrim($paths['url'], '/'); |
||
| 190 | $paths['path'] = rtrim($paths['path'], '/'); |
||
| 191 | OC::$APPSROOTS[] = $paths; |
||
| 192 | } |
||
| 193 | } |
||
| 194 | } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
||
| 195 | OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true); |
||
| 196 | } elseif (file_exists(OC::$SERVERROOT . '/../apps')) { |
||
| 197 | OC::$APPSROOTS[] = array( |
||
| 198 | 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps', |
||
| 199 | 'url' => '/apps', |
||
| 200 | 'writable' => true |
||
| 201 | ); |
||
| 202 | } |
||
| 203 | |||
| 204 | if (empty(OC::$APPSROOTS)) { |
||
| 205 | throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
||
| 206 | . ' or the folder above. You can also configure the location in the config.php file.'); |
||
| 207 | } |
||
| 208 | $paths = array(); |
||
| 209 | foreach (OC::$APPSROOTS as $path) { |
||
| 210 | $paths[] = $path['path']; |
||
| 211 | if (!is_dir($path['path'])) { |
||
| 212 | throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
||
| 213 | . ' Nextcloud folder or the folder above. You can also configure the location in the' |
||
| 214 | . ' config.php file.', $path['path'])); |
||
| 215 | } |
||
| 216 | } |
||
| 217 | |||
| 218 | // set the right include path |
||
| 219 | set_include_path( |
||
| 220 | OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR . |
||
| 221 | self::$configDir . PATH_SEPARATOR . |
||
| 222 | OC::$SERVERROOT . '/3rdparty' . PATH_SEPARATOR . |
||
| 223 | implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR . |
||
| 224 | get_include_path() . PATH_SEPARATOR . |
||
| 225 | OC::$SERVERROOT |
||
| 226 | ); |
||
| 227 | } |
||
| 228 | |||
| 229 | public static function checkConfig() { |
||
| 230 | $l = \OC::$server->getL10N('lib'); |
||
| 231 | |||
| 232 | // Create config if it does not already exist |
||
| 233 | $configFilePath = self::$configDir .'/config.php'; |
||
| 234 | if(!file_exists($configFilePath)) { |
||
| 235 | @touch($configFilePath); |
||
|
|
|||
| 236 | } |
||
| 237 | |||
| 238 | // Check if config is writable |
||
| 239 | $configFileWritable = is_writable($configFilePath); |
||
| 240 | if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
||
| 241 | || !$configFileWritable && self::checkUpgrade(false)) { |
||
| 242 | |||
| 243 | $urlGenerator = \OC::$server->getURLGenerator(); |
||
| 244 | |||
| 245 | if (self::$CLI) { |
||
| 246 | echo $l->t('Cannot write into "config" directory!')."\n"; |
||
| 247 | echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n"; |
||
| 248 | echo "\n"; |
||
| 249 | echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n"; |
||
| 250 | exit; |
||
| 251 | } else { |
||
| 252 | OC_Template::printErrorPage( |
||
| 253 | $l->t('Cannot write into "config" directory!'), |
||
| 254 | $l->t('This can usually be fixed by ' |
||
| 255 | . '%sgiving the webserver write access to the config directory%s.', |
||
| 256 | array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>')) |
||
| 257 | ); |
||
| 258 | } |
||
| 259 | } |
||
| 260 | } |
||
| 261 | |||
| 262 | public static function checkInstalled() { |
||
| 263 | if (defined('OC_CONSOLE')) { |
||
| 264 | return; |
||
| 265 | } |
||
| 266 | // Redirect to installer if not installed |
||
| 267 | if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
||
| 268 | if (OC::$CLI) { |
||
| 269 | throw new Exception('Not installed'); |
||
| 270 | } else { |
||
| 271 | $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php'; |
||
| 272 | header('Location: ' . $url); |
||
| 273 | } |
||
| 274 | exit(); |
||
| 275 | } |
||
| 276 | } |
||
| 277 | |||
| 278 | public static function checkMaintenanceMode() { |
||
| 279 | // Allow ajax update script to execute without being stopped |
||
| 280 | if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') { |
||
| 281 | // send http status 503 |
||
| 282 | header('HTTP/1.1 503 Service Temporarily Unavailable'); |
||
| 283 | header('Status: 503 Service Temporarily Unavailable'); |
||
| 284 | header('Retry-After: 120'); |
||
| 285 | |||
| 286 | // render error page |
||
| 287 | $template = new OC_Template('', 'update.user', 'guest'); |
||
| 288 | OC_Util::addScript('maintenance-check'); |
||
| 289 | $template->printPage(); |
||
| 290 | die(); |
||
| 291 | } |
||
| 292 | } |
||
| 293 | |||
| 294 | public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) { |
||
| 295 | if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) { |
||
| 296 | return; |
||
| 297 | } |
||
| 298 | $user = OC_User::getUserSession()->getUser(); |
||
| 299 | if ($user) { |
||
| 300 | $group = \OC::$server->getGroupManager()->get('admin'); |
||
| 301 | if ($group->inGroup($user)) { |
||
| 302 | return; |
||
| 303 | } |
||
| 304 | } else { |
||
| 305 | if(!$lockIfNoUserLoggedIn) { |
||
| 306 | return; |
||
| 307 | } |
||
| 308 | } |
||
| 309 | // send http status 503 |
||
| 310 | header('HTTP/1.1 503 Service Temporarily Unavailable'); |
||
| 311 | header('Status: 503 Service Temporarily Unavailable'); |
||
| 312 | header('Retry-After: 120'); |
||
| 313 | |||
| 314 | // render error page |
||
| 315 | $template = new OC_Template('', 'singleuser.user', 'guest'); |
||
| 316 | $template->printPage(); |
||
| 317 | die(); |
||
| 318 | } |
||
| 319 | |||
| 320 | /** |
||
| 321 | * Checks if the version requires an update and shows |
||
| 322 | * @param bool $showTemplate Whether an update screen should get shown |
||
| 323 | * @return bool|void |
||
| 324 | */ |
||
| 325 | public static function checkUpgrade($showTemplate = true) { |
||
| 326 | if (\OCP\Util::needUpgrade()) { |
||
| 327 | $systemConfig = \OC::$server->getSystemConfig(); |
||
| 328 | if ($showTemplate && !$systemConfig->getValue('maintenance', false)) { |
||
| 329 | self::printUpgradePage(); |
||
| 330 | exit(); |
||
| 331 | } else { |
||
| 332 | return true; |
||
| 333 | } |
||
| 334 | } |
||
| 335 | return false; |
||
| 336 | } |
||
| 337 | |||
| 338 | /** |
||
| 339 | * Prints the upgrade page |
||
| 340 | */ |
||
| 341 | private static function printUpgradePage() { |
||
| 342 | $systemConfig = \OC::$server->getSystemConfig(); |
||
| 343 | |||
| 344 | $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
||
| 345 | $tooBig = false; |
||
| 346 | if (!$disableWebUpdater) { |
||
| 347 | $apps = \OC::$server->getAppManager(); |
||
| 348 | $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth'); |
||
| 349 | if (!$tooBig) { |
||
| 350 | // count users |
||
| 351 | $stats = \OC::$server->getUserManager()->countUsers(); |
||
| 352 | $totalUsers = array_sum($stats); |
||
| 353 | $tooBig = ($totalUsers > 50); |
||
| 354 | } |
||
| 355 | } |
||
| 356 | if ($disableWebUpdater || $tooBig) { |
||
| 357 | // send http status 503 |
||
| 358 | header('HTTP/1.1 503 Service Temporarily Unavailable'); |
||
| 359 | header('Status: 503 Service Temporarily Unavailable'); |
||
| 360 | header('Retry-After: 120'); |
||
| 361 | |||
| 362 | // render error page |
||
| 363 | $template = new OC_Template('', 'update.use-cli', 'guest'); |
||
| 364 | $template->assign('productName', 'owncloud'); // for now |
||
| 365 | $template->assign('version', OC_Util::getVersionString()); |
||
| 366 | $template->assign('tooBig', $tooBig); |
||
| 367 | |||
| 368 | $template->printPage(); |
||
| 369 | die(); |
||
| 370 | } |
||
| 371 | |||
| 372 | // check whether this is a core update or apps update |
||
| 373 | $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
||
| 374 | $currentVersion = implode('.', \OCP\Util::getVersion()); |
||
| 375 | |||
| 376 | // if not a core upgrade, then it's apps upgrade |
||
| 377 | $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '=')); |
||
| 378 | |||
| 379 | $oldTheme = $systemConfig->getValue('theme'); |
||
| 380 | $systemConfig->setValue('theme', ''); |
||
| 381 | \OCP\Util::addScript('config'); // needed for web root |
||
| 382 | \OCP\Util::addScript('update'); |
||
| 383 | \OCP\Util::addStyle('update'); |
||
| 384 | |||
| 385 | $appManager = \OC::$server->getAppManager(); |
||
| 386 | |||
| 387 | $tmpl = new OC_Template('', 'update.admin', 'guest'); |
||
| 388 | $tmpl->assign('version', OC_Util::getVersionString()); |
||
| 389 | $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
||
| 390 | |||
| 391 | // get third party apps |
||
| 392 | $ocVersion = \OCP\Util::getVersion(); |
||
| 393 | $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
||
| 394 | $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion)); |
||
| 395 | $tmpl->assign('productName', 'Nextcloud'); // for now |
||
| 396 | $tmpl->assign('oldTheme', $oldTheme); |
||
| 397 | $tmpl->printPage(); |
||
| 398 | } |
||
| 399 | |||
| 400 | public static function initSession() { |
||
| 401 | // prevents javascript from accessing php session cookies |
||
| 402 | ini_set('session.cookie_httponly', true); |
||
| 403 | |||
| 404 | // set the cookie path to the Nextcloud directory |
||
| 405 | $cookie_path = OC::$WEBROOT ? : '/'; |
||
| 406 | ini_set('session.cookie_path', $cookie_path); |
||
| 407 | |||
| 408 | // Let the session name be changed in the initSession Hook |
||
| 409 | $sessionName = OC_Util::getInstanceId(); |
||
| 410 | |||
| 411 | try { |
||
| 412 | // Allow session apps to create a custom session object |
||
| 413 | $useCustomSession = false; |
||
| 414 | $session = self::$server->getSession(); |
||
| 415 | OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession)); |
||
| 416 | if (!$useCustomSession) { |
||
| 417 | // set the session name to the instance id - which is unique |
||
| 418 | $session = new \OC\Session\Internal($sessionName); |
||
| 419 | } |
||
| 420 | |||
| 421 | $cryptoWrapper = \OC::$server->getSessionCryptoWrapper(); |
||
| 422 | $session = $cryptoWrapper->wrapSession($session); |
||
| 423 | self::$server->setSession($session); |
||
| 424 | |||
| 425 | // if session can't be started break with http 500 error |
||
| 426 | } catch (Exception $e) { |
||
| 427 | \OCP\Util::logException('base', $e); |
||
| 428 | //show the user a detailed error page |
||
| 429 | OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR); |
||
| 430 | OC_Template::printExceptionErrorPage($e); |
||
| 431 | die(); |
||
| 432 | } |
||
| 433 | |||
| 434 | $sessionLifeTime = self::getSessionLifeTime(); |
||
| 435 | |||
| 436 | // session timeout |
||
| 437 | if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
||
| 438 | if (isset($_COOKIE[session_name()])) { |
||
| 439 | setcookie(session_name(), null, -1, self::$WEBROOT ? : '/'); |
||
| 440 | } |
||
| 441 | \OC::$server->getUserSession()->logout(); |
||
| 442 | } |
||
| 443 | |||
| 444 | $session->set('LAST_ACTIVITY', time()); |
||
| 445 | } |
||
| 446 | |||
| 447 | /** |
||
| 448 | * @return string |
||
| 449 | */ |
||
| 450 | private static function getSessionLifeTime() { |
||
| 451 | return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24); |
||
| 452 | } |
||
| 453 | |||
| 454 | public static function loadAppClassPaths() { |
||
| 455 | View Code Duplication | foreach (OC_App::getEnabledApps() as $app) { |
|
| 456 | $appPath = OC_App::getAppPath($app); |
||
| 457 | if ($appPath === false) { |
||
| 458 | continue; |
||
| 459 | } |
||
| 460 | |||
| 461 | $file = $appPath . '/appinfo/classpath.php'; |
||
| 462 | if (file_exists($file)) { |
||
| 463 | require_once $file; |
||
| 464 | } |
||
| 465 | } |
||
| 466 | } |
||
| 467 | |||
| 468 | /** |
||
| 469 | * Try to set some values to the required Nextcloud default |
||
| 470 | */ |
||
| 471 | public static function setRequiredIniValues() { |
||
| 472 | @ini_set('default_charset', 'UTF-8'); |
||
| 473 | @ini_set('gd.jpeg_ignore_warning', 1); |
||
| 474 | } |
||
| 475 | |||
| 476 | /** |
||
| 477 | * Send the same site cookies |
||
| 478 | */ |
||
| 479 | private static function sendSameSiteCookies() { |
||
| 480 | $cookieParams = session_get_cookie_params(); |
||
| 481 | $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
||
| 482 | $policies = [ |
||
| 483 | 'lax', |
||
| 484 | 'strict', |
||
| 485 | ]; |
||
| 486 | foreach($policies as $policy) { |
||
| 487 | header( |
||
| 488 | sprintf( |
||
| 489 | 'Set-Cookie: nc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
||
| 490 | $policy, |
||
| 491 | $cookieParams['path'], |
||
| 492 | $policy |
||
| 493 | ), |
||
| 494 | false |
||
| 495 | ); |
||
| 496 | } |
||
| 497 | } |
||
| 498 | |||
| 499 | /** |
||
| 500 | * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
||
| 501 | * be set in every request if cookies are sent to add a second level of |
||
| 502 | * defense against CSRF. |
||
| 503 | * |
||
| 504 | * If the cookie is not sent this will set the cookie and reload the page. |
||
| 505 | * We use an additional cookie since we want to protect logout CSRF and |
||
| 506 | * also we can't directly interfere with PHP's session mechanism. |
||
| 507 | */ |
||
| 508 | private static function performSameSiteCookieProtection() { |
||
| 509 | $request = \OC::$server->getRequest(); |
||
| 510 | |||
| 511 | // Some user agents are notorious and don't really properly follow HTTP |
||
| 512 | // specifications. For those, have an automated opt-out. Since the protection |
||
| 513 | // for remote.php is applied in base.php as starting point we need to opt out |
||
| 514 | // here. |
||
| 515 | $incompatibleUserAgents = [ |
||
| 516 | // OS X Finder |
||
| 517 | '/^WebDAVFS/', |
||
| 518 | ]; |
||
| 519 | if($request->isUserAgent($incompatibleUserAgents)) { |
||
| 520 | return; |
||
| 521 | } |
||
| 522 | |||
| 523 | |||
| 524 | if(count($_COOKIE) > 0) { |
||
| 525 | $requestUri = $request->getScriptName(); |
||
| 526 | $processingScript = explode('/', $requestUri); |
||
| 527 | $processingScript = $processingScript[count($processingScript)-1]; |
||
| 528 | // FIXME: In a SAML scenario we don't get any strict or lax cookie |
||
| 529 | // send for the ACS endpoint. Since we have some legacy code in Nextcloud |
||
| 530 | // (direct PHP files) the enforcement of lax cookies is performed here |
||
| 531 | // instead of the middleware. |
||
| 532 | // |
||
| 533 | // This means we cannot exclude some routes from the cookie validation, |
||
| 534 | // which normally is not a problem but is a little bit cumbersome for |
||
| 535 | // this use-case. |
||
| 536 | // Once the old legacy PHP endpoints have been removed we can move |
||
| 537 | // the verification into a middleware and also adds some exemptions. |
||
| 538 | // |
||
| 539 | // Questions about this code? Ask Lukas ;-) |
||
| 540 | $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT)); |
||
| 541 | if($currentUrl === '/index.php/apps/user_saml/saml/acs') { |
||
| 542 | return; |
||
| 543 | } |
||
| 544 | // For the "index.php" endpoint only a lax cookie is required. |
||
| 545 | if($processingScript === 'index.php') { |
||
| 546 | if(!$request->passesLaxCookieCheck()) { |
||
| 547 | self::sendSameSiteCookies(); |
||
| 548 | header('Location: '.$_SERVER['REQUEST_URI']); |
||
| 549 | exit(); |
||
| 550 | } |
||
| 551 | } else { |
||
| 552 | // All other endpoints require the lax and the strict cookie |
||
| 553 | if(!$request->passesStrictCookieCheck()) { |
||
| 554 | self::sendSameSiteCookies(); |
||
| 555 | // Debug mode gets access to the resources without strict cookie |
||
| 556 | // due to the fact that the SabreDAV browser also lives there. |
||
| 557 | if(!\OC::$server->getConfig()->getSystemValue('debug', false)) { |
||
| 558 | http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); |
||
| 559 | exit(); |
||
| 560 | } |
||
| 561 | } |
||
| 562 | } |
||
| 563 | } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
||
| 564 | self::sendSameSiteCookies(); |
||
| 565 | } |
||
| 566 | } |
||
| 567 | |||
| 568 | public static function init() { |
||
| 569 | // calculate the root directories |
||
| 570 | OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); |
||
| 571 | |||
| 572 | // register autoloader |
||
| 573 | $loaderStart = microtime(true); |
||
| 574 | require_once __DIR__ . '/autoloader.php'; |
||
| 575 | self::$loader = new \OC\Autoloader([ |
||
| 576 | OC::$SERVERROOT . '/lib/private/legacy', |
||
| 577 | ]); |
||
| 578 | if (defined('PHPUNIT_RUN')) { |
||
| 579 | self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
||
| 580 | } |
||
| 581 | spl_autoload_register(array(self::$loader, 'load')); |
||
| 582 | $loaderEnd = microtime(true); |
||
| 583 | |||
| 584 | self::$CLI = (php_sapi_name() == 'cli'); |
||
| 585 | |||
| 586 | // Add default composer PSR-4 autoloader |
||
| 587 | self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
||
| 588 | |||
| 589 | try { |
||
| 590 | self::initPaths(); |
||
| 591 | // setup 3rdparty autoloader |
||
| 592 | $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; |
||
| 593 | if (!file_exists($vendorAutoLoad)) { |
||
| 594 | throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
||
| 595 | } |
||
| 596 | require_once $vendorAutoLoad; |
||
| 597 | |||
| 598 | } catch (\RuntimeException $e) { |
||
| 599 | if (!self::$CLI) { |
||
| 600 | $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']); |
||
| 601 | $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1'; |
||
| 602 | header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE); |
||
| 603 | } |
||
| 604 | // we can't use the template error page here, because this needs the |
||
| 605 | // DI container which isn't available yet |
||
| 606 | print($e->getMessage()); |
||
| 607 | exit(); |
||
| 608 | } |
||
| 609 | |||
| 610 | // setup the basic server |
||
| 611 | self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
||
| 612 | \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
||
| 613 | \OC::$server->getEventLogger()->start('boot', 'Initialize'); |
||
| 614 | |||
| 615 | // Don't display errors and log them |
||
| 616 | error_reporting(E_ALL | E_STRICT); |
||
| 617 | @ini_set('display_errors', 0); |
||
| 618 | @ini_set('log_errors', 1); |
||
| 619 | |||
| 620 | date_default_timezone_set('UTC'); |
||
| 621 | |||
| 622 | //try to configure php to enable big file uploads. |
||
| 623 | //this doesn´t work always depending on the webserver and php configuration. |
||
| 624 | //Let´s try to overwrite some defaults anyway |
||
| 625 | |||
| 626 | //try to set the maximum execution time to 60min |
||
| 627 | @set_time_limit(3600); |
||
| 628 | @ini_set('max_execution_time', 3600); |
||
| 629 | @ini_set('max_input_time', 3600); |
||
| 630 | |||
| 631 | //try to set the maximum filesize to 10G |
||
| 632 | @ini_set('upload_max_filesize', '10G'); |
||
| 633 | @ini_set('post_max_size', '10G'); |
||
| 634 | @ini_set('file_uploads', '50'); |
||
| 635 | |||
| 636 | self::setRequiredIniValues(); |
||
| 637 | self::handleAuthHeaders(); |
||
| 638 | self::registerAutoloaderCache(); |
||
| 639 | |||
| 640 | // initialize intl fallback is necessary |
||
| 641 | \Patchwork\Utf8\Bootup::initIntl(); |
||
| 642 | OC_Util::isSetLocaleWorking(); |
||
| 643 | |||
| 644 | if (!defined('PHPUNIT_RUN')) { |
||
| 645 | OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger()); |
||
| 646 | $debug = \OC::$server->getConfig()->getSystemValue('debug', false); |
||
| 647 | OC\Log\ErrorHandler::register($debug); |
||
| 648 | } |
||
| 649 | |||
| 650 | // register the stream wrappers |
||
| 651 | stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir'); |
||
| 652 | stream_wrapper_register('static', 'OC\Files\Stream\StaticStream'); |
||
| 653 | stream_wrapper_register('close', 'OC\Files\Stream\Close'); |
||
| 654 | stream_wrapper_register('quota', 'OC\Files\Stream\Quota'); |
||
| 655 | stream_wrapper_register('oc', 'OC\Files\Stream\OC'); |
||
| 656 | |||
| 657 | \OC::$server->getEventLogger()->start('init_session', 'Initialize session'); |
||
| 658 | OC_App::loadApps(array('session')); |
||
| 659 | if (!self::$CLI) { |
||
| 660 | self::initSession(); |
||
| 661 | } |
||
| 662 | \OC::$server->getEventLogger()->end('init_session'); |
||
| 663 | self::checkConfig(); |
||
| 664 | self::checkInstalled(); |
||
| 665 | |||
| 666 | OC_Response::addSecurityHeaders(); |
||
| 667 | if(self::$server->getRequest()->getServerProtocol() === 'https') { |
||
| 668 | ini_set('session.cookie_secure', true); |
||
| 669 | } |
||
| 670 | |||
| 671 | self::performSameSiteCookieProtection(); |
||
| 672 | |||
| 673 | if (!defined('OC_CONSOLE')) { |
||
| 674 | $errors = OC_Util::checkServer(\OC::$server->getConfig()); |
||
| 675 | if (count($errors) > 0) { |
||
| 676 | if (self::$CLI) { |
||
| 677 | // Convert l10n string into regular string for usage in database |
||
| 678 | $staticErrors = []; |
||
| 679 | foreach ($errors as $error) { |
||
| 680 | echo $error['error'] . "\n"; |
||
| 681 | echo $error['hint'] . "\n\n"; |
||
| 682 | $staticErrors[] = [ |
||
| 683 | 'error' => (string)$error['error'], |
||
| 684 | 'hint' => (string)$error['hint'], |
||
| 685 | ]; |
||
| 686 | } |
||
| 687 | |||
| 688 | try { |
||
| 689 | \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
||
| 690 | } catch (\Exception $e) { |
||
| 691 | echo('Writing to database failed'); |
||
| 692 | } |
||
| 693 | exit(1); |
||
| 694 | } else { |
||
| 695 | OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); |
||
| 696 | OC_Template::printGuestPage('', 'error', array('errors' => $errors)); |
||
| 697 | exit; |
||
| 698 | } |
||
| 699 | View Code Duplication | } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) { |
|
| 700 | \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors'); |
||
| 701 | } |
||
| 702 | } |
||
| 703 | //try to set the session lifetime |
||
| 704 | $sessionLifeTime = self::getSessionLifeTime(); |
||
| 705 | @ini_set('gc_maxlifetime', (string)$sessionLifeTime); |
||
| 706 | |||
| 707 | $systemConfig = \OC::$server->getSystemConfig(); |
||
| 708 | |||
| 709 | // User and Groups |
||
| 710 | if (!$systemConfig->getValue("installed", false)) { |
||
| 711 | self::$server->getSession()->set('user_id', ''); |
||
| 712 | } |
||
| 713 | |||
| 714 | OC_User::useBackend(new \OC\User\Database()); |
||
| 715 | OC_Group::useBackend(new \OC\Group\Database()); |
||
| 716 | |||
| 717 | // Subscribe to the hook |
||
| 718 | \OCP\Util::connectHook( |
||
| 719 | '\OCA\Files_Sharing\API\Server2Server', |
||
| 720 | 'preLoginNameUsedAsUserName', |
||
| 721 | '\OC\User\Database', |
||
| 722 | 'preLoginNameUsedAsUserName' |
||
| 723 | ); |
||
| 724 | |||
| 725 | //setup extra user backends |
||
| 726 | if (!self::checkUpgrade(false)) { |
||
| 727 | OC_User::setupBackends(); |
||
| 728 | } else { |
||
| 729 | // Run upgrades in incognito mode |
||
| 730 | OC_User::setIncognitoMode(true); |
||
| 731 | } |
||
| 732 | |||
| 733 | self::registerCacheHooks(); |
||
| 734 | self::registerFilesystemHooks(); |
||
| 735 | if ($systemConfig->getValue('enable_previews', true)) { |
||
| 736 | self::registerPreviewHooks(); |
||
| 737 | } |
||
| 738 | self::registerShareHooks(); |
||
| 739 | self::registerLogRotate(); |
||
| 740 | self::registerEncryptionWrapper(); |
||
| 741 | self::registerEncryptionHooks(); |
||
| 742 | self::registerSettingsHooks(); |
||
| 743 | |||
| 744 | //make sure temporary files are cleaned up |
||
| 745 | $tmpManager = \OC::$server->getTempManager(); |
||
| 746 | register_shutdown_function(array($tmpManager, 'clean')); |
||
| 747 | $lockProvider = \OC::$server->getLockingProvider(); |
||
| 748 | register_shutdown_function(array($lockProvider, 'releaseAll')); |
||
| 749 | |||
| 750 | // Check whether the sample configuration has been copied |
||
| 751 | if($systemConfig->getValue('copied_sample_config', false)) { |
||
| 752 | $l = \OC::$server->getL10N('lib'); |
||
| 753 | header('HTTP/1.1 503 Service Temporarily Unavailable'); |
||
| 754 | header('Status: 503 Service Temporarily Unavailable'); |
||
| 755 | OC_Template::printErrorPage( |
||
| 756 | $l->t('Sample configuration detected'), |
||
| 757 | $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php') |
||
| 758 | ); |
||
| 759 | return; |
||
| 760 | } |
||
| 761 | |||
| 762 | $request = \OC::$server->getRequest(); |
||
| 763 | $host = $request->getInsecureServerHost(); |
||
| 764 | /** |
||
| 765 | * if the host passed in headers isn't trusted |
||
| 766 | * FIXME: Should not be in here at all :see_no_evil: |
||
| 767 | */ |
||
| 768 | if (!OC::$CLI |
||
| 769 | // overwritehost is always trusted, workaround to not have to make |
||
| 770 | // \OC\AppFramework\Http\Request::getOverwriteHost public |
||
| 771 | && self::$server->getConfig()->getSystemValue('overwritehost') === '' |
||
| 772 | && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host) |
||
| 773 | && self::$server->getConfig()->getSystemValue('installed', false) |
||
| 774 | ) { |
||
| 775 | header('HTTP/1.1 400 Bad Request'); |
||
| 776 | header('Status: 400 Bad Request'); |
||
| 777 | |||
| 778 | \OC::$server->getLogger()->warning( |
||
| 779 | 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
||
| 780 | [ |
||
| 781 | 'app' => 'core', |
||
| 782 | 'remoteAddress' => $request->getRemoteAddress(), |
||
| 783 | 'host' => $host, |
||
| 784 | ] |
||
| 785 | ); |
||
| 786 | |||
| 787 | $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); |
||
| 788 | $tmpl->assign('domain', $host); |
||
| 789 | $tmpl->printPage(); |
||
| 790 | |||
| 791 | exit(); |
||
| 792 | } |
||
| 793 | \OC::$server->getEventLogger()->end('boot'); |
||
| 794 | } |
||
| 795 | |||
| 796 | /** |
||
| 797 | * register hooks for the cache |
||
| 798 | */ |
||
| 799 | public static function registerCacheHooks() { |
||
| 820 | |||
| 821 | public static function registerSettingsHooks() { |
||
| 822 | $dispatcher = \OC::$server->getEventDispatcher(); |
||
| 823 | $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) { |
||
| 824 | /** @var \OCP\App\ManagerEvent $event */ |
||
| 825 | \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID()); |
||
| 826 | }); |
||
| 827 | $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) { |
||
| 828 | /** @var \OCP\App\ManagerEvent $event */ |
||
| 829 | $jobList = \OC::$server->getJobList(); |
||
| 830 | $job = 'OC\\Settings\\RemoveOrphaned'; |
||
| 831 | if(!($jobList->has($job, null))) { |
||
| 832 | $jobList->add($job); |
||
| 833 | } |
||
| 834 | }); |
||
| 836 | |||
| 837 | private static function registerEncryptionWrapper() { |
||
| 841 | |||
| 842 | private static function registerEncryptionHooks() { |
||
| 851 | |||
| 852 | /** |
||
| 853 | * register hooks for the cache |
||
| 854 | */ |
||
| 855 | public static function registerLogRotate() { |
||
| 863 | |||
| 864 | /** |
||
| 865 | * register hooks for the filesystem |
||
| 866 | */ |
||
| 867 | public static function registerFilesystemHooks() { |
||
| 872 | |||
| 873 | /** |
||
| 874 | * register hooks for previews |
||
| 875 | */ |
||
| 876 | public static function registerPreviewHooks() { |
||
| 886 | |||
| 887 | /** |
||
| 888 | * register hooks for sharing |
||
| 889 | */ |
||
| 890 | public static function registerShareHooks() { |
||
| 897 | |||
| 898 | protected static function registerAutoloaderCache() { |
||
| 914 | |||
| 915 | /** |
||
| 916 | * Handle the request |
||
| 917 | */ |
||
| 918 | public static function handleRequest() { |
||
| 1016 | |||
| 1017 | /** |
||
| 1018 | * Check login: apache auth, auth token, basic auth |
||
| 1019 | * |
||
| 1020 | * @param OCP\IRequest $request |
||
| 1021 | * @return boolean |
||
| 1022 | */ |
||
| 1023 | static function handleLogin(OCP\IRequest $request) { |
||
| 1036 | |||
| 1037 | protected static function handleAuthHeaders() { |
||
| 1057 | } |
||
| 1058 | |||
| 1060 |
If you suppress an error, we recommend checking for the error condition explicitly: