Completed
Push — master ( 03449d...db6361 )
by Lukas
44s queued 24s
created

OC::initPaths()   F

Complexity

Conditions 23
Paths 804

Size

Total Lines 105
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 23
eloc 65
c 1
b 0
f 0
nc 804
nop 0
dl 0
loc 105
rs 2.2656

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @author Adam Williamson <[email protected]>
4
 * @author Andreas Fischer <[email protected]>
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Bart Visscher <[email protected]>
7
 * @author Bernhard Posselt <[email protected]>
8
 * @author Björn Schießle <[email protected]>
9
 * @author Christoph Wurst <[email protected]>
10
 * @author davidgumberg <[email protected]>
11
 * @author Florin Peter <[email protected]>
12
 * @author Georg Ehrke <[email protected]>
13
 * @author Hugo Gonzalez Labrador <[email protected]>
14
 * @author Individual IT Services <[email protected]>
15
 * @author Jakob Sack <[email protected]>
16
 * @author Joachim Bauch <[email protected]>
17
 * @author Joas Schilling <[email protected]>
18
 * @author Jörn Friedrich Dreyer <[email protected]>
19
 * @author Lukas Reschke <[email protected]>
20
 * @author Michael Gapczynski <[email protected]>
21
 * @author Morris Jobke <[email protected]>
22
 * @author Owen Winkler <[email protected]>
23
 * @author Phil Davis <[email protected]>
24
 * @author Ramiro Aparicio <[email protected]>
25
 * @author Robin Appelman <[email protected]>
26
 * @author Robin McCorkell <[email protected]>
27
 * @author Roeland Jago Douma <[email protected]>
28
 * @author scolebrook <[email protected]>
29
 * @author Stefan Weil <[email protected]>
30
 * @author Thomas Müller <[email protected]>
31
 * @author Thomas Tanghus <[email protected]>
32
 * @author Vincent Petry <[email protected]>
33
 * @author Volkan Gezer <[email protected]>
34
 *
35
 * @copyright Copyright (c) 2016, ownCloud, Inc.
36
 * @license AGPL-3.0
37
 *
38
 * This code is free software: you can redistribute it and/or modify
39
 * it under the terms of the GNU Affero General Public License, version 3,
40
 * as published by the Free Software Foundation.
41
 *
42
 * This program is distributed in the hope that it will be useful,
43
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45
 * GNU Affero General Public License for more details.
46
 *
47
 * You should have received a copy of the GNU Affero General Public License, version 3,
48
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
49
 *
50
 */
51
52
use OCP\IRequest;
53
54
require_once 'public/Constants.php';
55
56
/**
57
 * Class that is a namespace for all global OC variables
58
 * No, we can not put this class in its own file because it is used by
59
 * OC_autoload!
60
 */
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
		} else {
127
			self::$configDir = OC::$SERVERROOT . '/config/';
128
		}
129
		self::$config = new \OC\Config(self::$configDir);
130
131
		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
132
		/**
133
		 * FIXME: The following lines are required because we can't yet instantiiate
134
		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
135
		 */
136
		$params = [
137
			'server' => [
138
				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
139
				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
140
			],
141
		];
142
		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
143
		$scriptName = $fakeRequest->getScriptName();
144
		if (substr($scriptName, -1) == '/') {
145
			$scriptName .= 'index.php';
146
			//make sure suburi follows the same rules as scriptName
147
			if (substr(OC::$SUBURI, -9) != 'index.php') {
148
				if (substr(OC::$SUBURI, -1) != '/') {
149
					OC::$SUBURI = OC::$SUBURI . '/';
150
				}
151
				OC::$SUBURI = OC::$SUBURI . 'index.php';
152
			}
153
		}
154
155
156
		if (OC::$CLI) {
157
			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
158
		} else {
159
			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
160
				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
161
162
				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
163
					OC::$WEBROOT = '/' . OC::$WEBROOT;
164
				}
165
			} else {
166
				// The scriptName is not ending with OC::$SUBURI
167
				// This most likely means that we are calling from CLI.
168
				// However some cron jobs still need to generate
169
				// a web URL, so we use overwritewebroot as a fallback.
170
				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
171
			}
172
173
			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
174
			// slash which is required by URL generation.
175
			if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
176
					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
177
				header('Location: '.\OC::$WEBROOT.'/');
178
				exit();
179
			}
180
		}
181
182
		// search the apps folder
183
		$config_paths = self::$config->getValue('apps_paths', array());
184
		if (!empty($config_paths)) {
185
			foreach ($config_paths as $paths) {
186
				if (isset($paths['url']) && isset($paths['path'])) {
187
					$paths['url'] = rtrim($paths['url'], '/');
188
					$paths['path'] = rtrim($paths['path'], '/');
189
					OC::$APPSROOTS[] = $paths;
190
				}
191
			}
192
		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
193
			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
194
		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
195
			OC::$APPSROOTS[] = array(
196
				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
197
				'url' => '/apps',
198
				'writable' => true
199
			);
200
		}
201
202
		if (empty(OC::$APPSROOTS)) {
203
			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
204
				. ' or the folder above. You can also configure the location in the config.php file.');
205
		}
206
		$paths = array();
207
		foreach (OC::$APPSROOTS as $path) {
208
			$paths[] = $path['path'];
209
			if (!is_dir($path['path'])) {
210
				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
211
					. ' Nextcloud folder or the folder above. You can also configure the location in the'
212
					. ' config.php file.', $path['path']));
213
			}
214
		}
215
216
		// set the right include path
217
		set_include_path(
218
			OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
219
			OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
220
			OC::$SERVERROOT . '/3rdparty' . PATH_SEPARATOR .
221
			implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
222
			get_include_path() . PATH_SEPARATOR .
223
			OC::$SERVERROOT
224
		);
225
	}
226
227
	public static function checkConfig() {
228
		$l = \OC::$server->getL10N('lib');
229
230
		// Create config if it does not already exist
231
		$configFilePath = self::$configDir .'/config.php';
232
		if(!file_exists($configFilePath)) {
233
			@touch($configFilePath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
234
		}
235
236
		// Check if config is writable
237
		$configFileWritable = is_writable($configFilePath);
238
		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
			|| !$configFileWritable && self::checkUpgrade(false)) {
240
241
			$urlGenerator = \OC::$server->getURLGenerator();
242
243
			if (self::$CLI) {
244
				echo $l->t('Cannot write into "config" directory!')."\n";
245
				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
				echo "\n";
247
				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
				exit;
249
			} else {
250
				OC_Template::printErrorPage(
251
					$l->t('Cannot write into "config" directory!'),
252
					$l->t('This can usually be fixed by '
253
					. '%sgiving the webserver write access to the config directory%s.',
254
					 array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
255
				);
256
			}
257
		}
258
	}
259
260
	public static function checkInstalled() {
261
		if (defined('OC_CONSOLE')) {
262
			return;
263
		}
264
		// Redirect to installer if not installed
265
		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
266
			if (OC::$CLI) {
267
				throw new Exception('Not installed');
268
			} else {
269
				$url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
270
				header('Location: ' . $url);
271
			}
272
			exit();
273
		}
274
	}
275
276
	/**
277
	 * Limit maintenance mode access
278
	 * @param IRequest $request
279
	 */
280
	public static function checkMaintenanceMode(IRequest $request) {
281
		// Check if requested URL matches 'index.php/occ'
282
		$isOccControllerRequested = preg_match('|/index\.php$|', $request->getScriptName()) === 1
283
				&& strpos($request->getPathInfo(), '/occ/') === 0;
284
		// Allow ajax update script to execute without being stopped
285
		if (
286
			\OC::$server->getSystemConfig()->getValue('maintenance', false)
287
			&& OC::$SUBURI != '/core/ajax/update.php'
288
			&& !$isOccControllerRequested
289
		) {
290
			// send http status 503
291
			header('HTTP/1.1 503 Service Temporarily Unavailable');
292
			header('Status: 503 Service Temporarily Unavailable');
293
			header('Retry-After: 120');
294
295
			// render error page
296
			$template = new OC_Template('', 'update.user', 'guest');
297
			OC_Util::addScript('maintenance-check');
298
			$template->printPage();
299
			die();
300
		}
301
	}
302
303
	public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
304
		if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
305
			return;
306
		}
307
		$user = OC_User::getUserSession()->getUser();
308
		if ($user) {
309
			$group = \OC::$server->getGroupManager()->get('admin');
310
			if ($group->inGroup($user)) {
0 ignored issues
show
Compatibility introduced by
$user of type object<OCP\IUser> is not a sub-type of object<OC\User\User>. It seems like you assume a concrete implementation of the interface OCP\IUser to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
311
				return;
312
			}
313
		} else {
314
			if(!$lockIfNoUserLoggedIn) {
315
				return;
316
			}
317
		}
318
		// send http status 503
319
		header('HTTP/1.1 503 Service Temporarily Unavailable');
320
		header('Status: 503 Service Temporarily Unavailable');
321
		header('Retry-After: 120');
322
323
		// render error page
324
		$template = new OC_Template('', 'singleuser.user', 'guest');
325
		$template->printPage();
326
		die();
327
	}
328
329
	/**
330
	 * Checks if the version requires an update and shows
331
	 * @param bool $showTemplate Whether an update screen should get shown
332
	 * @return bool|void
333
	 */
334
	public static function checkUpgrade($showTemplate = true) {
335
		if (\OCP\Util::needUpgrade()) {
336
			$systemConfig = \OC::$server->getSystemConfig();
337
			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
338
				self::printUpgradePage();
339
				exit();
340
			} else {
341
				return true;
342
			}
343
		}
344
		return false;
345
	}
346
347
	/**
348
	 * Prints the upgrade page
349
	 */
350
	private static function printUpgradePage() {
351
		$systemConfig = \OC::$server->getSystemConfig();
352
353
		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
354
		$tooBig = false;
355
		if (!$disableWebUpdater) {
356
			$apps = \OC::$server->getAppManager();
357
			$tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
358
			if (!$tooBig) {
359
				// count users
360
				$stats = \OC::$server->getUserManager()->countUsers();
361
				$totalUsers = array_sum($stats);
362
				$tooBig = ($totalUsers > 50);
363
			}
364
		}
365
		if ($disableWebUpdater || $tooBig) {
366
			// send http status 503
367
			header('HTTP/1.1 503 Service Temporarily Unavailable');
368
			header('Status: 503 Service Temporarily Unavailable');
369
			header('Retry-After: 120');
370
371
			// render error page
372
			$template = new OC_Template('', 'update.use-cli', 'guest');
373
			$template->assign('productName', 'owncloud'); // for now
374
			$template->assign('version', OC_Util::getVersionString());
375
			$template->assign('tooBig', $tooBig);
376
377
			$template->printPage();
378
			die();
379
		}
380
381
		// check whether this is a core update or apps update
382
		$installedVersion = $systemConfig->getValue('version', '0.0.0');
383
		$currentVersion = implode('.', \OCP\Util::getVersion());
384
385
		// if not a core upgrade, then it's apps upgrade
386
		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
387
388
		$oldTheme = $systemConfig->getValue('theme');
389
		$systemConfig->setValue('theme', '');
390
		\OCP\Util::addScript('config'); // needed for web root
391
		\OCP\Util::addScript('update');
392
		\OCP\Util::addStyle('update');
393
394
		$appManager = \OC::$server->getAppManager();
395
396
		$tmpl = new OC_Template('', 'update.admin', 'guest');
397
		$tmpl->assign('version', OC_Util::getVersionString());
398
		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
399
400
		// get third party apps
401
		$ocVersion = \OCP\Util::getVersion();
402
		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
403
		$tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
404
		$tmpl->assign('productName', 'ownCloud'); // for now
405
		$tmpl->assign('oldTheme', $oldTheme);
406
		$tmpl->printPage();
407
	}
408
409
	public static function initSession() {
410
		// prevents javascript from accessing php session cookies
411
		ini_set('session.cookie_httponly', true);
412
413
		// set the cookie path to the Nextcloud directory
414
		$cookie_path = OC::$WEBROOT ? : '/';
415
		ini_set('session.cookie_path', $cookie_path);
416
417
		// Let the session name be changed in the initSession Hook
418
		$sessionName = OC_Util::getInstanceId();
419
420
		try {
421
			// Allow session apps to create a custom session object
422
			$useCustomSession = false;
423
			$session = self::$server->getSession();
424
			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
425
			if (!$useCustomSession) {
426
				// set the session name to the instance id - which is unique
427
				$session = new \OC\Session\Internal($sessionName);
428
			}
429
430
			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
431
			$session = $cryptoWrapper->wrapSession($session);
432
			self::$server->setSession($session);
433
434
			// if session can't be started break with http 500 error
435
		} catch (Exception $e) {
436
			\OCP\Util::logException('base', $e);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Util::logException() has been deprecated with message: 8.2.0 use logException of \OCP\ILogger

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
437
			//show the user a detailed error page
438
			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
439
			OC_Template::printExceptionErrorPage($e);
440
			die();
441
		}
442
443
		$sessionLifeTime = self::getSessionLifeTime();
444
445
		// session timeout
446
		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
447
			if (isset($_COOKIE[session_name()])) {
448
				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
449
			}
450
			\OC::$server->getUserSession()->logout();
451
		}
452
453
		$session->set('LAST_ACTIVITY', time());
454
	}
455
456
	/**
457
	 * @return string
458
	 */
459
	private static function getSessionLifeTime() {
460
		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
461
	}
462
463
	public static function loadAppClassPaths() {
464 View Code Duplication
		foreach (OC_App::getEnabledApps() as $app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
465
			$appPath = OC_App::getAppPath($app);
466
			if ($appPath === false) {
467
				continue;
468
			}
469
470
			$file = $appPath . '/appinfo/classpath.php';
471
			if (file_exists($file)) {
472
				require_once $file;
473
			}
474
		}
475
	}
476
477
	/**
478
	 * Try to set some values to the required Nextcloud default
479
	 */
480
	public static function setRequiredIniValues() {
481
		@ini_set('default_charset', 'UTF-8');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
482
		@ini_set('gd.jpeg_ignore_warning', 1);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
483
	}
484
485
	public static function init() {
486
		// calculate the root directories
487
		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
488
489
		// register autoloader
490
		$loaderStart = microtime(true);
491
		require_once __DIR__ . '/autoloader.php';
492
		self::$loader = new \OC\Autoloader([
493
			OC::$SERVERROOT . '/lib/private/legacy',
494
		]);
495
		if (defined('PHPUNIT_RUN')) {
496
			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
497
		}
498
		spl_autoload_register(array(self::$loader, 'load'));
499
		$loaderEnd = microtime(true);
500
501
		self::$CLI = (php_sapi_name() == 'cli');
502
503
		// Add default composer PSR-4 autoloader
504
		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
505
506
		try {
507
			self::initPaths();
508
			// setup 3rdparty autoloader
509
			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
510
			if (!file_exists($vendorAutoLoad)) {
511
				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".');
512
			}
513
			require_once $vendorAutoLoad;
514
515
		} catch (\RuntimeException $e) {
516
			if (!self::$CLI) {
517
				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
518
				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
519
				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
520
			}
521
			// we can't use the template error page here, because this needs the
522
			// DI container which isn't available yet
523
			print($e->getMessage());
524
			exit();
525
		}
526
527
		// setup the basic server
528
		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
529
		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
530
		\OC::$server->getEventLogger()->start('boot', 'Initialize');
531
532
		// Don't display errors and log them
533
		error_reporting(E_ALL | E_STRICT);
534
		@ini_set('display_errors', 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
535
		@ini_set('log_errors', 1);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
536
537
		date_default_timezone_set('UTC');
538
539
		//try to configure php to enable big file uploads.
540
		//this doesn´t work always depending on the webserver and php configuration.
541
		//Let´s try to overwrite some defaults anyway
542
543
		//try to set the maximum execution time to 60min
544
		@set_time_limit(3600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
545
		@ini_set('max_execution_time', 3600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
546
		@ini_set('max_input_time', 3600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
547
548
		//try to set the maximum filesize to 10G
549
		@ini_set('upload_max_filesize', '10G');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
550
		@ini_set('post_max_size', '10G');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
551
		@ini_set('file_uploads', '50');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
552
553
		self::setRequiredIniValues();
554
		self::handleAuthHeaders();
555
		self::registerAutoloaderCache();
556
557
		// initialize intl fallback is necessary
558
		\Patchwork\Utf8\Bootup::initIntl();
559
		OC_Util::isSetLocaleWorking();
560
561
		if (!defined('PHPUNIT_RUN')) {
562
			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
563
			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
564
			OC\Log\ErrorHandler::register($debug);
565
		}
566
567
		// register the stream wrappers
568
		stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
569
		stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
570
		stream_wrapper_register('close', 'OC\Files\Stream\Close');
571
		stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
572
		stream_wrapper_register('oc', 'OC\Files\Stream\OC');
573
574
		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
575
		OC_App::loadApps(array('session'));
576
		if (!self::$CLI) {
577
			self::initSession();
578
		}
579
		\OC::$server->getEventLogger()->end('init_session');
580
		self::checkConfig();
581
		self::checkInstalled();
582
583
		OC_Response::addSecurityHeaders();
584
		if(self::$server->getRequest()->getServerProtocol() === 'https') {
585
			ini_set('session.cookie_secure', true);
586
		}
587
588
		if (!defined('OC_CONSOLE')) {
589
			$errors = OC_Util::checkServer(\OC::$server->getConfig());
590
			if (count($errors) > 0) {
591
				if (self::$CLI) {
592
					// Convert l10n string into regular string for usage in database
593
					$staticErrors = [];
594
					foreach ($errors as $error) {
595
						echo $error['error'] . "\n";
596
						echo $error['hint'] . "\n\n";
597
						$staticErrors[] = [
598
							'error' => (string)$error['error'],
599
							'hint' => (string)$error['hint'],
600
						];
601
					}
602
603
					try {
604
						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
605
					} catch (\Exception $e) {
606
						echo('Writing to database failed');
607
					}
608
					exit(1);
609
				} else {
610
					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
611
					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
612
					exit;
613
				}
614 View Code Duplication
			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
615
				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
616
			}
617
		}
618
		//try to set the session lifetime
619
		$sessionLifeTime = self::getSessionLifeTime();
620
		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
621
622
		$systemConfig = \OC::$server->getSystemConfig();
623
624
		// User and Groups
625
		if (!$systemConfig->getValue("installed", false)) {
626
			self::$server->getSession()->set('user_id', '');
627
		}
628
629
		OC_User::useBackend(new \OC\User\Database());
630
		OC_Group::useBackend(new \OC\Group\Database());
631
632
		// Subscribe to the hook
633
		\OCP\Util::connectHook(
634
			'\OCA\Files_Sharing\API\Server2Server',
635
			'preLoginNameUsedAsUserName',
636
			'\OC\User\Database',
637
			'preLoginNameUsedAsUserName'
638
		);
639
640
		//setup extra user backends
641
		if (!self::checkUpgrade(false)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkUpgrade(false) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
642
			OC_User::setupBackends();
643
		} else {
644
			// Run upgrades in incognito mode
645
			OC_User::setIncognitoMode(true);
646
		}
647
648
		self::registerCacheHooks();
649
		self::registerFilesystemHooks();
650
		if ($systemConfig->getValue('enable_previews', true)) {
651
			self::registerPreviewHooks();
652
		}
653
		self::registerShareHooks();
654
		self::registerLogRotate();
655
		self::registerEncryptionWrapper();
656
		self::registerEncryptionHooks();
657
658
		//make sure temporary files are cleaned up
659
		$tmpManager = \OC::$server->getTempManager();
660
		register_shutdown_function(array($tmpManager, 'clean'));
661
		$lockProvider = \OC::$server->getLockingProvider();
662
		register_shutdown_function(array($lockProvider, 'releaseAll'));
663
664
		// Check whether the sample configuration has been copied
665
		if($systemConfig->getValue('copied_sample_config', false)) {
666
			$l = \OC::$server->getL10N('lib');
667
			header('HTTP/1.1 503 Service Temporarily Unavailable');
668
			header('Status: 503 Service Temporarily Unavailable');
669
			OC_Template::printErrorPage(
670
				$l->t('Sample configuration detected'),
671
				$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')
672
			);
673
			return;
674
		}
675
676
		$request = \OC::$server->getRequest();
677
		$host = $request->getInsecureServerHost();
678
		/**
679
		 * if the host passed in headers isn't trusted
680
		 * FIXME: Should not be in here at all :see_no_evil:
681
		 */
682
		if (!OC::$CLI
683
			// overwritehost is always trusted, workaround to not have to make
684
			// \OC\AppFramework\Http\Request::getOverwriteHost public
685
			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
686
			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
687
			&& self::$server->getConfig()->getSystemValue('installed', false)
688
		) {
689
			header('HTTP/1.1 400 Bad Request');
690
			header('Status: 400 Bad Request');
691
692
			\OC::$server->getLogger()->warning(
693
					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
694
					[
695
						'app' => 'core',
696
						'remoteAddress' => $request->getRemoteAddress(),
697
						'host' => $host,
698
					]
699
			);
700
701
			$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
702
			$tmpl->assign('domain', $host);
703
			$tmpl->printPage();
704
705
			exit();
706
		}
707
		\OC::$server->getEventLogger()->end('boot');
708
	}
709
710
	/**
711
	 * register hooks for the cache
712
	 */
713
	public static function registerCacheHooks() {
714
		//don't try to do this before we are properly setup
715
		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkUpgrade(false) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
716
717
			// NOTE: This will be replaced to use OCP
718
			$userSession = self::$server->getUserSession();
719
			$userSession->listen('\OC\User', 'postLogin', function () {
720
				try {
721
					$cache = new \OC\Cache\File();
722
					$cache->gc();
723
				} catch (\OC\ServerNotAvailableException $e) {
724
					// not a GC exception, pass it on
725
					throw $e;
726
				} catch (\Exception $e) {
727
					// a GC exception should not prevent users from using OC,
728
					// so log the exception
729
					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
730
				}
731
			});
732
		}
733
	}
734
735
	private static function registerEncryptionWrapper() {
736
		$manager = self::$server->getEncryptionManager();
737
		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
738
	}
739
740
	private static function registerEncryptionHooks() {
741
		$enabled = self::$server->getEncryptionManager()->isEnabled();
742
		if ($enabled) {
743
			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
744
			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
745
			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
746
			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
747
		}
748
	}
749
750
	/**
751
	 * register hooks for the cache
752
	 */
753
	public static function registerLogRotate() {
754
		$systemConfig = \OC::$server->getSystemConfig();
755
		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkUpgrade(false) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
756
			//don't try to do this before we are properly setup
757
			//use custom logfile path if defined, otherwise use default of owncloud.log in data directory
758
			\OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
0 ignored issues
show
Deprecated Code introduced by
The method OCP\BackgroundJob::registerJob() has been deprecated with message: 8.1.0 Use \OC::$server->getJobList()->add() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
759
		}
760
	}
761
762
	/**
763
	 * register hooks for the filesystem
764
	 */
765
	public static function registerFilesystemHooks() {
766
		// Check for blacklisted files
767
		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
768
		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
769
	}
770
771
	/**
772
	 * register hooks for previews
773
	 */
774
	public static function registerPreviewHooks() {
775
		OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
776
		OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
777
		OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
778
		OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
779
		OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
780
		OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
781
		OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
782
		OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
783
	}
784
785
	/**
786
	 * register hooks for sharing
787
	 */
788
	public static function registerShareHooks() {
789
		if (\OC::$server->getSystemConfig()->getValue('installed')) {
790
			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
791
			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
792
			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
793
		}
794
	}
795
796
	protected static function registerAutoloaderCache() {
797
		// The class loader takes an optional low-latency cache, which MUST be
798
		// namespaced. The instanceid is used for namespacing, but might be
799
		// unavailable at this point. Furthermore, it might not be possible to
800
		// generate an instanceid via \OC_Util::getInstanceId() because the
801
		// config file may not be writable. As such, we only register a class
802
		// loader cache if instanceid is available without trying to create one.
803
		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
804
		if ($instanceId) {
805
			try {
806
				$memcacheFactory = \OC::$server->getMemCacheFactory();
807
				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
0 ignored issues
show
Bug introduced by
The method createLocal() does not exist on OCP\ICacheFactory. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
808
			} catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
809
			}
810
		}
811
	}
812
813
	/**
814
	 * Handle the request
815
	 */
816
	public static function handleRequest() {
817
818
		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
819
		$systemConfig = \OC::$server->getSystemConfig();
820
		// load all the classpaths from the enabled apps so they are available
821
		// in the routing files of each app
822
		OC::loadAppClassPaths();
823
824
		// Check if Nextcloud is installed or in maintenance (update) mode
825
		if (!$systemConfig->getValue('installed', false)) {
826
			\OC::$server->getSession()->clear();
827
			$setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
828
				\OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
829
				\OC::$server->getSecureRandom());
830
			$controller = new OC\Core\Controller\SetupController($setupHelper);
831
			$controller->run($_POST);
832
			exit();
833
		}
834
835
		$request = \OC::$server->getRequest();
836
		$requestPath = $request->getRawPathInfo();
837
		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
838
			self::checkMaintenanceMode($request);
839
			self::checkUpgrade();
840
		}
841
842
		// emergency app disabling
843
		if ($requestPath === '/disableapp'
844
			&& $request->getMethod() === 'POST'
845
			&& ((string)$request->getParam('appid')) !== ''
846
		) {
847
			\OCP\JSON::callCheck();
0 ignored issues
show
Deprecated Code introduced by
The method OCP\JSON::callCheck() has been deprecated with message: 8.1.0 Use annotation based CSRF checks from the AppFramework instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
848
			\OCP\JSON::checkAdminUser();
0 ignored issues
show
Deprecated Code introduced by
The method OCP\JSON::checkAdminUser() has been deprecated with message: 8.1.0 Use annotation based ACLs from the AppFramework instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
849
			$appId = (string)$request->getParam('appid');
850
			$appId = \OC_App::cleanAppId($appId);
851
852
			\OC_App::disable($appId);
853
			\OC_JSON::success();
0 ignored issues
show
Deprecated Code introduced by
The method OC_JSON::success() has been deprecated with message: Use a AppFramework JSONResponse instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
854
			exit();
855
		}
856
857
		// Always load authentication apps
858
		OC_App::loadApps(['authentication']);
859
860
		// Load minimum set of apps
861
		if (!self::checkUpgrade(false)
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkUpgrade(false) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
862
			&& !$systemConfig->getValue('maintenance', false)) {
863
			// For logged-in users: Load everything
864
			if(OC_User::isLoggedIn()) {
0 ignored issues
show
Deprecated Code introduced by
The method OC_User::isLoggedIn() has been deprecated with message: use \OC::$server->getUserSession()->isLoggedIn()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
865
				OC_App::loadApps();
866
			} else {
867
				// For guests: Load only filesystem and logging
868
				OC_App::loadApps(array('filesystem', 'logging'));
869
				self::handleLogin($request);
870
			}
871
		}
872
873
		if (!self::$CLI) {
874
			try {
875
				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkUpgrade(false) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
876
					OC_App::loadApps(array('filesystem', 'logging'));
877
					OC_App::loadApps();
878
				}
879
				self::checkSingleUserMode();
880
				OC_Util::setupFS();
881
				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Route\IRouter::match() has been deprecated with message: 9.0.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
882
				return;
883
			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Routin...sourceNotFoundException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
884
				//header('HTTP/1.0 404 Not Found');
885
			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Routin...thodNotAllowedException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
886
				OC_Response::setStatus(405);
887
				return;
888
			}
889
		}
890
891
		// Handle WebDAV
892
		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
893
			// not allowed any more to prevent people
894
			// mounting this root directly.
895
			// Users need to mount remote.php/webdav instead.
896
			header('HTTP/1.1 405 Method Not Allowed');
897
			header('Status: 405 Method Not Allowed');
898
			return;
899
		}
900
901
		// Someone is logged in
902
		if (OC_User::isLoggedIn()) {
0 ignored issues
show
Deprecated Code introduced by
The method OC_User::isLoggedIn() has been deprecated with message: use \OC::$server->getUserSession()->isLoggedIn()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
903
			OC_App::loadApps();
904
			OC_User::setupBackends();
905
			OC_Util::setupFS();
906
			// FIXME
907
			// Redirect to default application
908
			OC_Util::redirectToDefaultPage();
909
		} else {
910
			// Not handled and not logged in
911
			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
912
		}
913
	}
914
915
	/**
916
	 * Check login: apache auth, auth token, basic auth
917
	 *
918
	 * @param OCP\IRequest $request
919
	 * @return boolean
920
	 */
921
	private static function handleLogin(OCP\IRequest $request) {
922
		$userSession = self::$server->getUserSession();
923
		if (OC_User::handleApacheAuth()) {
924
			return true;
925
		}
926
		if ($userSession->tryTokenLogin($request)) {
927
			return true;
928
		}
929
		if ($userSession->tryBasicAuthLogin($request)) {
930
			return true;
931
		}
932
		return false;
933
	}
934
935
	protected static function handleAuthHeaders() {
936
		//copy http auth headers for apache+php-fcgid work around
937
		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
938
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
939
		}
940
941
		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
942
		$vars = array(
943
			'HTTP_AUTHORIZATION', // apache+php-cgi work around
944
			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
945
		);
946
		foreach ($vars as $var) {
947
			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
948
				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
949
				$_SERVER['PHP_AUTH_USER'] = $name;
950
				$_SERVER['PHP_AUTH_PW'] = $password;
951
				break;
952
			}
953
		}
954
	}
955
}
956
957
OC::init();
958