Completed
Pull Request — stable8.2 (#27092)
by Victor
18:13
created

OC::fixupIncludePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 10
ccs 0
cts 8
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
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 Christopher Schäpers <[email protected]>
10
 * @author davidgumberg <[email protected]>
11
 * @author Florian Scholz <[email protected]>
12
 * @author Florin Peter <[email protected]>
13
 * @author Frank Karlitschek <[email protected]>
14
 * @author Georg Ehrke <[email protected]>
15
 * @author Hugo Gonzalez Labrador <[email protected]>
16
 * @author Individual IT Services <[email protected]>
17
 * @author Jakob Sack <[email protected]>
18
 * @author Joas Schilling <[email protected]>
19
 * @author Jörn Friedrich Dreyer <[email protected]>
20
 * @author Lukas Reschke <[email protected]>
21
 * @author marc0s <[email protected]>
22
 * @author Martin Mattel <[email protected]>
23
 * @author Michael Gapczynski <[email protected]>
24
 * @author Morris Jobke <[email protected]>
25
 * @author Owen Winkler <[email protected]>
26
 * @author Phil Davis <[email protected]>
27
 * @author Ramiro Aparicio <[email protected]>
28
 * @author Robin Appelman <[email protected]>
29
 * @author Robin McCorkell <[email protected]>
30
 * @author scolebrook <[email protected]>
31
 * @author Stefan Herbrechtsmeier <[email protected]>
32
 * @author Thomas Müller <[email protected]>
33
 * @author Thomas Tanghus <[email protected]>
34
 * @author Victor Dubiniuk <[email protected]>
35
 * @author Vincent Petry <[email protected]>
36
 * @author Volkan Gezer <[email protected]>
37
 *
38
 * @copyright Copyright (c) 2015, ownCloud, Inc.
39
 * @license AGPL-3.0
40
 *
41
 * This code is free software: you can redistribute it and/or modify
42
 * it under the terms of the GNU Affero General Public License, version 3,
43
 * as published by the Free Software Foundation.
44
 *
45
 * This program is distributed in the hope that it will be useful,
46
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48
 * GNU Affero General Public License for more details.
49
 *
50
 * You should have received a copy of the GNU Affero General Public License, version 3,
51
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
52
 *
53
 */
54
55
require_once 'public/constants.php';
56
57
/**
58
 * Class that is a namespace for all global OC variables
59
 * No, we can not put this class in its own file because it is used by
60
 * OC_autoload!
61
 */
62
class OC {
63
	/**
64
	 * Associative array for autoloading. classname => filename
65
	 */
66
	public static $CLASSPATH = array();
67
	/**
68
	 * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
69
	 */
70
	public static $SERVERROOT = '';
71
	/**
72
	 * the current request path relative to the owncloud root (e.g. files/index.php)
73
	 */
74
	private static $SUBURI = '';
75
	/**
76
	 * the owncloud root path for http requests (e.g. owncloud/)
77
	 */
78
	public static $WEBROOT = '';
79
	/**
80
	 * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
81
	 */
82
	public static $THIRDPARTYROOT = '';
83
	/**
84
	 * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
85
	 */
86
	public static $THIRDPARTYWEBROOT = '';
87
	/**
88
	 * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
89
	 * web path in 'url'
90
	 */
91
	public static $APPSROOTS = array();
92
93
	public static $configDir;
94
95
	/**
96
	 * requested app
97
	 */
98
	public static $REQUESTEDAPP = '';
99
100
	/**
101
	 * check if ownCloud runs in cli mode
102
	 */
103
	public static $CLI = false;
104
105
	/**
106
	 * @var \OC\Autoloader $loader
107
	 */
108
	public static $loader = null;
109
110
	/**
111
	 * @var \OC\Server
112
	 */
113
	public static $server = null;
114
115
	/**
116
	 * Remove current directory from include path
117
	 * @param string $oldIncludePath
118
	 * @return string
119
	 */
120
	public static function fixupIncludePath($oldIncludePath){
121
		$newIncludePath = $oldIncludePath;
122
		$includePathArray = explode(PATH_SEPARATOR, $oldIncludePath);
123
		$dotIndex = array_search('.', $includePathArray, true);
124
		if ($dotIndex !== false){
125
			unset($includePathArray[$dotIndex]);
126
			$newIncludePath = implode(PATH_SEPARATOR, $includePathArray);
127
		}
128
		return $newIncludePath;
129
	}
130
	
131
	/**
132
	 * @throws \RuntimeException when the 3rdparty directory is missing or
133
	 * the app path list is empty or contains an invalid path
134
	 */
135
	public static function initPaths() {
136
		// fixup: strip current dir from include path
137
		$includePath = self::fixupIncludePath(get_include_path());
138
		// ensure we can find OC_Config
139
		set_include_path(
140
			OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
141
			$includePath
142
		);
143
		
144
145
		if(defined('PHPUNIT_CONFIG_DIR')) {
146
			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
147
		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
148
			self::$configDir = OC::$SERVERROOT . '/tests/config/';
149
		} else {
150
			self::$configDir = OC::$SERVERROOT . '/config/';
151
		}
152
		OC_Config::$object = new \OC\Config(self::$configDir);
153
154
		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
155
		/**
156
		 * FIXME: The following lines are required because we can't yet instantiiate
157
		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
158
		 */
159
		$params = [
160
			'server' => [
161
				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
162
				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
163
			],
164
		];
165
		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig()));
166
		$scriptName = $fakeRequest->getScriptName();
167
		if (substr($scriptName, -1) == '/') {
168
			$scriptName .= 'index.php';
169
			//make sure suburi follows the same rules as scriptName
170
			if (substr(OC::$SUBURI, -9) != 'index.php') {
171
				if (substr(OC::$SUBURI, -1) != '/') {
172
					OC::$SUBURI = OC::$SUBURI . '/';
173
				}
174
				OC::$SUBURI = OC::$SUBURI . 'index.php';
175
			}
176
		}
177
178
179
		if (OC::$CLI) {
180
			OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
181
		} else {
182
			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
183
				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
184
185
				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
186
					OC::$WEBROOT = '/' . OC::$WEBROOT;
187
				}
188
			} else {
189
				// The scriptName is not ending with OC::$SUBURI
190
				// This most likely means that we are calling from CLI.
191
				// However some cron jobs still need to generate
192
				// a web URL, so we use overwritewebroot as a fallback.
193
				OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
194
			}
195
		}
196
197
		// search the 3rdparty folder
198
		OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', null);
199
		OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', null);
200
201
		if (empty(OC::$THIRDPARTYROOT) && empty(OC::$THIRDPARTYWEBROOT)) {
202
			if (file_exists(OC::$SERVERROOT . '/3rdparty')) {
203
				OC::$THIRDPARTYROOT = OC::$SERVERROOT;
204
				OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
205
			} elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
206
				OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
207
				OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
208
			}
209
		}
210
		if (empty(OC::$THIRDPARTYROOT) || !file_exists(OC::$THIRDPARTYROOT)) {
211
			throw new \RuntimeException('3rdparty directory not found! Please put the ownCloud 3rdparty'
212
				. ' folder in the ownCloud folder or the folder above.'
213
				. ' You can also configure the location in the config.php file.');
214
		}
215
216
		// search the apps folder
217
		$config_paths = OC_Config::getValue('apps_paths', array());
218
		if (!empty($config_paths)) {
219
			foreach ($config_paths as $paths) {
220
				if (isset($paths['url']) && isset($paths['path'])) {
221
					$paths['url'] = rtrim($paths['url'], '/');
222
					$paths['path'] = rtrim($paths['path'], '/');
223
					OC::$APPSROOTS[] = $paths;
224
				}
225
			}
226 View Code Duplication
		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
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...
227
			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
228
		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
229
			OC::$APPSROOTS[] = array(
230
				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
231
				'url' => '/apps',
232
				'writable' => true
233
			);
234
		}
235
236
		if (empty(OC::$APPSROOTS)) {
237
			throw new \RuntimeException('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
238
				. ' or the folder above. You can also configure the location in the config.php file.');
239
		}
240
		$paths = array();
241
		foreach (OC::$APPSROOTS as $path) {
242
			$paths[] = $path['path'];
243
			if (!is_dir($path['path'])) {
244
				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the ownCloud apps folder in the'
245
					. ' ownCloud folder or the folder above. You can also configure the location in the'
246
					. ' config.php file.', $path['path']));
247
			}
248
		}
249
250
		// set the right include path
251
		set_include_path(
252
			OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
253
			OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
254
			OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
255
			implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
256
			get_include_path() . PATH_SEPARATOR .
257
			OC::$SERVERROOT
258
		);
259
	}
260
261
	public static function checkConfig() {
262
		$l = \OC::$server->getL10N('lib');
263
264
		// Create config if it does not already exist
265
		$configFilePath = self::$configDir .'/config.php';
266
		if(!file_exists($configFilePath)) {
267
			@touch($configFilePath);
268
		}
269
270
		// Check if config is writable
271
		$configFileWritable = is_writable($configFilePath);
272
		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
273
			|| !$configFileWritable && self::checkUpgrade(false)) {
274
			if (self::$CLI) {
275
				echo $l->t('Cannot write into "config" directory!')."\n";
276
				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
277
				echo "\n";
278
				echo $l->t('See %s', array(\OC_Helper::linkToDocs('admin-dir_permissions')))."\n";
279
				exit;
280
			} else {
281
				OC_Template::printErrorPage(
282
					$l->t('Cannot write into "config" directory!'),
283
					$l->t('This can usually be fixed by '
284
					. '%sgiving the webserver write access to the config directory%s.',
285
					 array('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>'))
286
				);
287
			}
288
		}
289
	}
290
291
	public static function checkInstalled() {
292
		if (defined('OC_CONSOLE')) {
293
			return;
294
		}
295
		// Redirect to installer if not installed
296
		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
297
			if (OC::$CLI) {
298
				throw new Exception('Not installed');
299
			} else {
300
				$url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
301
				header('Location: ' . $url);
302
			}
303
			exit();
304
		}
305
	}
306
307
	public static function checkMaintenanceMode() {
308
		// Allow ajax update script to execute without being stopped
309
		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
310
			// send http status 503
311
			header('HTTP/1.1 503 Service Temporarily Unavailable');
312
			header('Status: 503 Service Temporarily Unavailable');
313
			header('Retry-After: 120');
314
315
			// render error page
316
			$template = new OC_Template('', 'update.user', 'guest');
317
			OC_Util::addscript('maintenance-check');
318
			$template->printPage();
319
			die();
320
		}
321
	}
322
323
	public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
324
		if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
325
			return;
326
		}
327
		$user = OC_User::getUserSession()->getUser();
328
		if ($user) {
329
			$group = \OC::$server->getGroupManager()->get('admin');
330
			if ($group->inGroup($user)) {
331
				return;
332
			}
333
		} else {
334
			if(!$lockIfNoUserLoggedIn) {
335
				return;
336
			}
337
		}
338
		// send http status 503
339
		header('HTTP/1.1 503 Service Temporarily Unavailable');
340
		header('Status: 503 Service Temporarily Unavailable');
341
		header('Retry-After: 120');
342
343
		// render error page
344
		$template = new OC_Template('', 'singleuser.user', 'guest');
345 14
		$template->printPage();
346 14
		die();
347
	}
348
349
	/**
350
	 * check if the instance needs to perform an upgrade
351
	 *
352
	 * @return bool
353
	 * @deprecated use \OCP\Util::needUpgrade() instead
354
	 */
355 14
	public static function needUpgrade() {
356
		return \OCP\Util::needUpgrade();
357
	}
358
359
	/**
360
	 * Checks if the version requires an update and shows
361
	 * @param bool $showTemplate Whether an update screen should get shown
362
	 * @return bool|void
363
	 */
364
	public static function checkUpgrade($showTemplate = true) {
365
		if (\OCP\Util::needUpgrade()) {
366
			$systemConfig = \OC::$server->getSystemConfig();
367
			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
368
				self::printUpgradePage();
369
				exit();
370
			} else {
371
				return true;
372
			}
373
		}
374
		return false;
375
	}
376
377
	/**
378
	 * Prints the upgrade page
379
	 */
380
	private static function printUpgradePage() {
381
		$systemConfig = \OC::$server->getSystemConfig();
382
		$oldTheme = $systemConfig->getValue('theme');
383
		$systemConfig->setValue('theme', '');
384
		\OCP\Util::addScript('config'); // needed for web root
385
		\OCP\Util::addScript('update');
386
387
		// check whether this is a core update or apps update
388
		$installedVersion = $systemConfig->getValue('version', '0.0.0');
389
		$currentVersion = implode('.', OC_Util::getVersion());
390
391
		$appManager = \OC::$server->getAppManager();
392
393
		$tmpl = new OC_Template('', 'update.admin', 'guest');
394
		$tmpl->assign('version', OC_Util::getVersionString());
395
396
		// if not a core upgrade, then it's apps upgrade
397
		if (version_compare($currentVersion, $installedVersion, '=')) {
398
			$tmpl->assign('isAppsOnlyUpgrade', true);
399
		} else {
400
			$tmpl->assign('isAppsOnlyUpgrade', false);
401
		}
402
403
		// get third party apps
404
		$ocVersion = OC_Util::getVersion();
405
		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
406
		$tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
407
		$tmpl->assign('productName', 'ownCloud'); // for now
408
		$tmpl->assign('oldTheme', $oldTheme);
409
		$tmpl->printPage();
410
	}
411
412
	public static function initSession() {
413
		// prevents javascript from accessing php session cookies
414
		ini_set('session.cookie_httponly', true);
415
416
		// set the cookie path to the ownCloud directory
417
		$cookie_path = OC::$WEBROOT ? : '/';
418
		ini_set('session.cookie_path', $cookie_path);
419
420
		// Let the session name be changed in the initSession Hook
421
		$sessionName = OC_Util::getInstanceId();
422
423
		try {
424
			// Allow session apps to create a custom session object
425
			$useCustomSession = false;
426
			$session = self::$server->getSession();
427
			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
428
			if (!$useCustomSession) {
429
				// set the session name to the instance id - which is unique
430
				$session = new \OC\Session\Internal($sessionName);
431
			}
432
433
			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
434
			$session = $cryptoWrapper->wrapSession($session);
435
			self::$server->setSession($session);
436
437
			// if session cant be started break with http 500 error
438
		} catch (Exception $e) {
439
			\OCP\Util::logException('base', $e);
440
			//show the user a detailed error page
441
			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
442
			OC_Template::printExceptionErrorPage($e);
443
		}
444
445
		$sessionLifeTime = self::getSessionLifeTime();
446
		// regenerate session id periodically to avoid session fixation
447
		/**
448
		 * @var \OCP\ISession $session
449
		 */
450
		$session = self::$server->getSession();
451
		if (!$session->exists('SID_CREATED')) {
452
			$session->set('SID_CREATED', time());
453
		} else if (time() - $session->get('SID_CREATED') > $sessionLifeTime / 2) {
454
			session_regenerate_id(true);
455
			$session->set('SID_CREATED', time());
456
		}
457
458
		// session timeout
459
		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
460
			if (isset($_COOKIE[session_name()])) {
461
				setcookie(session_name(), '', time() - 42000, $cookie_path);
462
			}
463
			$session->clear();
464
		}
465
466
		$session->set('LAST_ACTIVITY', time());
467
	}
468
469
	/**
470
	 * @return string
471
	 */
472
	private static function getSessionLifeTime() {
473
		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
474
	}
475
476
	public static function loadAppClassPaths() {
477 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...
478
			$file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
479
			if (file_exists($file)) {
480
				require_once $file;
481
			}
482
		}
483
	}
484
485
	/**
486
	 * Try to set some values to the required ownCloud default
487
	 */
488
	public static function setRequiredIniValues() {
489
		@ini_set('default_charset', 'UTF-8');
490
	}
491
492
	public static function init() {
493
		// calculate the root directories
494
		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
495
496
		// register autoloader
497
		$loaderStart = microtime(true);
498
		require_once __DIR__ . '/autoloader.php';
499
		self::$loader = new \OC\Autoloader([
500
			OC::$SERVERROOT . '/lib',
501
			OC::$SERVERROOT . '/core',
502
			OC::$SERVERROOT . '/settings',
503
			OC::$SERVERROOT . '/ocs',
504
			OC::$SERVERROOT . '/ocs-provider',
505
			OC::$SERVERROOT . '/3rdparty',
506
			OC::$SERVERROOT . '/tests',
507
		]);
508
		spl_autoload_register(array(self::$loader, 'load'));
509
		$loaderEnd = microtime(true);
510
511
		self::$CLI = (php_sapi_name() == 'cli');
512
513
		try {
514
			self::initPaths();
515
			// setup 3rdparty autoloader
516
			$vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
517
			if (!file_exists($vendorAutoLoad)) {
518
				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".');
519
			}
520
			require_once $vendorAutoLoad;
521
522
		} catch (\RuntimeException $e) {
523
			OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
524
			// we can't use the template error page here, because this needs the
525
			// DI container which isn't available yet
526
			print($e->getMessage());
527
			exit();
528
		}
529
530
		// setup the basic server
531
		self::$server = new \OC\Server(\OC::$WEBROOT);
532
		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
533
		\OC::$server->getEventLogger()->start('boot', 'Initialize');
534
535
		// Don't display errors and log them
536
		error_reporting(E_ALL | E_STRICT);
537
		@ini_set('display_errors', 0);
538
		@ini_set('log_errors', 1);
539
540
		date_default_timezone_set('UTC');
541
542
		//try to configure php to enable big file uploads.
543
		//this doesn´t work always depending on the webserver and php configuration.
544
		//Let´s try to overwrite some defaults anyway
545
546
		//try to set the maximum execution time to 60min
547
		@set_time_limit(3600);
548
		@ini_set('max_execution_time', 3600);
549
		@ini_set('max_input_time', 3600);
550
551
		//try to set the maximum filesize to 10G
552
		@ini_set('upload_max_filesize', '10G');
553
		@ini_set('post_max_size', '10G');
554
		@ini_set('file_uploads', '50');
555
556
		self::setRequiredIniValues();
557
		self::handleAuthHeaders();
558
		self::registerAutoloaderCache();
559
560
		// initialize intl fallback is necessary
561
		\Patchwork\Utf8\Bootup::initIntl();
562
		OC_Util::isSetLocaleWorking();
563
564
		if (!defined('PHPUNIT_RUN')) {
565
			$logger = \OC::$server->getLogger();
566
			OC\Log\ErrorHandler::setLogger($logger);
567
			if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
568
				OC\Log\ErrorHandler::register(true);
569
				set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
570
			} else {
571
				OC\Log\ErrorHandler::register();
572
			}
573
		}
574
575
		// register the stream wrappers
576
		stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
577
		stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
578
		stream_wrapper_register('close', 'OC\Files\Stream\Close');
579
		stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
580
		stream_wrapper_register('oc', 'OC\Files\Stream\OC');
581
582
		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
583
		OC_App::loadApps(array('session'));
584
		if (!self::$CLI) {
585
			self::initSession();
586
		}
587
		\OC::$server->getEventLogger()->end('init_session');
588
		self::checkConfig();
589
		self::checkInstalled();
590
591
		OC_Response::addSecurityHeaders();
592
		if(self::$server->getRequest()->getServerProtocol() === 'https') {
593
			ini_set('session.cookie_secure', true);
594
		}
595
596
		if (!defined('OC_CONSOLE')) {
597
			$errors = OC_Util::checkServer(\OC::$server->getConfig());
598
			if (count($errors) > 0) {
599
				if (self::$CLI) {
600
					// Convert l10n string into regular string for usage in database
601
					$staticErrors = [];
602
					foreach ($errors as $error) {
603
						echo $error['error'] . "\n";
604
						echo $error['hint'] . "\n\n";
605
						$staticErrors[] = [
606
							'error' => (string)$error['error'],
607
							'hint' => (string)$error['hint'],
608
						];
609
					}
610
611
					try {
612
						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
613
					} catch (\Exception $e) {
614
						echo('Writing to database failed');
615
					}
616
					exit(1);
617
				} else {
618
					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
619
					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
620
					exit;
621
				}
622 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...
623
				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
624
			}
625
		}
626
		//try to set the session lifetime
627
		$sessionLifeTime = self::getSessionLifeTime();
628
		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
629
630
		$systemConfig = \OC::$server->getSystemConfig();
631
632
		// User and Groups
633
		if (!$systemConfig->getValue("installed", false)) {
634
			self::$server->getSession()->set('user_id', '');
635
		}
636
637
		OC_User::useBackend(new OC_User_Database());
638
		OC_Group::useBackend(new OC_Group_Database());
639
640
		// Subscribe to the hook
641
		\OCP\Util::connectHook(
642
			'\OCA\Files_Sharing\API\Server2Server',
643
			'preLoginNameUsedAsUserName',
644
			'\OC_User_Database',
645
			'preLoginNameUsedAsUserName'
646
		);
647
648
		//setup extra user backends
649
		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...
650
			OC_User::setupBackends();
651
		}
652
653
		self::registerCacheHooks();
654
		self::registerFilesystemHooks();
655
		if ($systemConfig->getValue('enable_previews', true)) {
656
			self::registerPreviewHooks();
657
		}
658
		self::registerShareHooks();
659
		self::registerLogRotate();
660
		self::registerLocalAddressBook();
661
		self::registerEncryptionWrapper();
662
		self::registerEncryptionHooks();
663
664
		//make sure temporary files are cleaned up
665
		$tmpManager = \OC::$server->getTempManager();
666
		register_shutdown_function(array($tmpManager, 'clean'));
667
		$lockProvider = \OC::$server->getLockingProvider();
668
		register_shutdown_function(array($lockProvider, 'releaseAll'));
669
670
		// Check whether the sample configuration has been copied
671
		if($systemConfig->getValue('copied_sample_config', false)) {
672
			$l = \OC::$server->getL10N('lib');
673
			header('HTTP/1.1 503 Service Temporarily Unavailable');
674
			header('Status: 503 Service Temporarily Unavailable');
675
			OC_Template::printErrorPage(
676
				$l->t('Sample configuration detected'),
677
				$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')
678
			);
679
			return;
680
		}
681
682
		$request = \OC::$server->getRequest();
683
		$host = $request->getInsecureServerHost();
684
		/**
685
		 * if the host passed in headers isn't trusted
686
		 * FIXME: Should not be in here at all :see_no_evil:
687
		 */
688
		if (!OC::$CLI
689
			// overwritehost is always trusted, workaround to not have to make
690
			// \OC\AppFramework\Http\Request::getOverwriteHost public
691
			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
692
			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
693
			&& self::$server->getConfig()->getSystemValue('installed', false)
694
		) {
695
			header('HTTP/1.1 400 Bad Request');
696
			header('Status: 400 Bad Request');
697
698
			$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
699 263
			$tmpl->assign('domain', $request->server['SERVER_NAME']);
0 ignored issues
show
Bug introduced by
Accessing server on the interface OCP\IRequest suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
700
			$tmpl->printPage();
701
702
			exit();
703
		}
704
		\OC::$server->getEventLogger()->end('boot');
705 263
	}
706
707 263
	private static function registerLocalAddressBook() {
708 263
		self::$server->getContactsManager()->register(function() {
709 263
			$userManager = \OC::$server->getUserManager();
710
			\OC::$server->getContactsManager()->registerAddressBook(
711
				new \OC\Contacts\LocalAddressBook($userManager));
712
		});
713
	}
714 263
715
	/**
716
	 * register hooks for the cache
717
	 */
718
	public static function registerCacheHooks() {
719
		//don't try to do this before we are properly setup
720
		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...
721
722
			// NOTE: This will be replaced to use OCP
723
			$userSession = self::$server->getUserSession();
724
			$userSession->listen('\OC\User', 'postLogin', function () {
725
				try {
726
					$cache = new \OC\Cache\File();
727
					$cache->gc();
728
				} catch (\OC\ServerNotAvailableException $e) {
729
					// not a GC exception, pass it on
730
					throw $e;
731
				} catch (\Exception $e) {
732
					// a GC exception should not prevent users from using OC,
733
					// so log the exception
734
					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
735
				}
736
			});
737
		}
738
	}
739
740
	private static function registerEncryptionWrapper() {
741
		$manager = self::$server->getEncryptionManager();
742
		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
743
	}
744
745
	private static function registerEncryptionHooks() {
746
		$enabled = self::$server->getEncryptionManager()->isEnabled();
747
		if ($enabled) {
748
			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
749
			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
750
			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
751
			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
752
		}
753
	}
754
755
	/**
756
	 * register hooks for the cache
757
	 */
758
	public static function registerLogRotate() {
759
		$systemConfig = \OC::$server->getSystemConfig();
760
		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...
761
			//don't try to do this before we are properly setup
762
			//use custom logfile path if defined, otherwise use default of owncloud.log in data directory
763
			\OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
764
		}
765
	}
766
767
	/**
768
	 * register hooks for the filesystem
769
	 */
770 78
	public static function registerFilesystemHooks() {
771 78
		// Check for blacklisted files
772 78
		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
773 78
		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
774 78
	}
775 78
776 78
	/**
777 78
	 * register hooks for previews
778 78
	 */
779
	public static function registerPreviewHooks() {
780
		OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
781
		OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
782
		OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
783
		OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
784
		OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
785
		OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
786
		OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
787
		OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
788
	}
789
790
	/**
791
	 * register hooks for sharing
792
	 */
793
	public static function registerShareHooks() {
794
		if (\OC::$server->getSystemConfig()->getValue('installed')) {
795
			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
796
			OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
797
			OC_Hook::connect('OC_Group', 'pre_addToGroup', 'OC\Share\Hooks', 'pre_addToGroup');
798
			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
799
			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
800
		}
801
	}
802
803
	protected static function registerAutoloaderCache() {
804
		// The class loader takes an optional low-latency cache, which MUST be
805
		// namespaced. The instanceid is used for namespacing, but might be
806
		// unavailable at this point. Futhermore, it might not be possible to
807
		// generate an instanceid via \OC_Util::getInstanceId() because the
808
		// config file may not be writable. As such, we only register a class
809
		// loader cache if instanceid is available without trying to create one.
810
		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
811
		if ($instanceId) {
812
			try {
813
				$memcacheFactory = \OC::$server->getMemCacheFactory();
814
				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...
815
			} catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
816
			}
817
		}
818
	}
819
820
	/**
821
	 * Handle the request
822
	 */
823
	public static function handleRequest() {
824
825
		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
826
		$systemConfig = \OC::$server->getSystemConfig();
827
		// load all the classpaths from the enabled apps so they are available
828
		// in the routing files of each app
829
		OC::loadAppClassPaths();
830
831
		// Check if ownCloud is installed or in maintenance (update) mode
832
		if (!$systemConfig->getValue('installed', false)) {
833
			\OC::$server->getSession()->clear();
834
			$setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
835
				\OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
836
				\OC::$server->getSecureRandom());
837
			$controller = new OC\Core\Setup\Controller($setupHelper);
838
			$controller->run($_POST);
839
			exit();
840
		}
841
842
		$request = \OC::$server->getRequest()->getPathInfo();
843
		if (substr($request, -3) !== '.js') { // we need these files during the upgrade
844
			self::checkMaintenanceMode();
845
			self::checkUpgrade();
846
		}
847
848
		// Always load authentication apps
849
		OC_App::loadApps(['authentication']);
850
851
		// Load minimum set of apps
852
		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...
853
			&& !$systemConfig->getValue('maintenance', false)) {
854
			// For logged-in users: Load everything
855
			if(OC_User::isLoggedIn()) {
856
				OC_App::loadApps();
857
			} else {
858
				// For guests: Load only filesystem and logging
859
				OC_App::loadApps(array('filesystem', 'logging'));
860
				\OC_User::tryBasicAuthLogin();
861
			}
862
		}
863
864
		if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
865
			try {
866
				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...
867
					OC_App::loadApps(array('filesystem', 'logging'));
868
					OC_App::loadApps();
869
				}
870
				self::checkSingleUserMode();
871
				OC_Util::setupFS();
872
				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
873
				return;
874
			} 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...
875
				//header('HTTP/1.0 404 Not Found');
876
			} 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...
877
				OC_Response::setStatus(405);
878
				return;
879
			}
880
		}
881
882
		// Handle redirect URL for logged in users
883
		if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
884
			$location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
885
886
			// Deny the redirect if the URL contains a @
887
			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
888
			if (strpos($location, '@') === false) {
889
				header('Location: ' . $location);
890
				return;
891
			}
892
		}
893
		// Handle WebDAV
894
		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
895
			// not allowed any more to prevent people
896
			// mounting this root directly.
897
			// Users need to mount remote.php/webdav instead.
898
			header('HTTP/1.1 405 Method Not Allowed');
899
			header('Status: 405 Method Not Allowed');
900
			return;
901
		}
902
903
		// Redirect to index if the logout link is accessed without valid session
904
		// this is needed to prevent "Token expired" messages while login if a session is expired
905
		// @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
906
		if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
907
			header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
908
			return;
909
		}
910
911
		// Someone is logged in
912
		if (OC_User::isLoggedIn()) {
913
			OC_App::loadApps();
914
			OC_User::setupBackends();
915
			OC_Util::setupFS();
916
			if (isset($_GET["logout"]) and ($_GET["logout"])) {
917
				OC_JSON::callCheck();
918
				if (isset($_COOKIE['oc_token'])) {
919
					\OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
920
				}
921
				OC_User::logout();
922
				// redirect to webroot and add slash if webroot is empty
923
				header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
924
			} else {
925
				// Redirect to default application
926
				OC_Util::redirectToDefaultPage();
927
			}
928
		} else {
929
			// Not handled and not logged in
930
			self::handleLogin();
931
		}
932
	}
933
934
	protected static function handleAuthHeaders() {
935
		//copy http auth headers for apache+php-fcgid work around
936
		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
937
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
938
		}
939
940
		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
941
		$vars = array(
942
			'HTTP_AUTHORIZATION', // apache+php-cgi work around
943
			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
944
		);
945
		foreach ($vars as $var) {
946
			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
947
				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
948
				$_SERVER['PHP_AUTH_USER'] = $name;
949
				$_SERVER['PHP_AUTH_PW'] = $password;
950
				break;
951
			}
952
		}
953
	}
954
955
	protected static function handleLogin() {
956
		OC_App::loadApps(array('prelogin'));
957
		$error = array();
958
		$messages = [];
959
960
		try {
961
			// auth possible via apache module?
962
			if (OC::tryApacheAuth()) {
963
				$error[] = 'apacheauthfailed';
964
			} // remember was checked after last login
965
			elseif (OC::tryRememberLogin()) {
966
				$error[] = 'invalidcookie';
967
			} // logon via web form
968
			elseif (OC::tryFormLogin()) {
969
				$error[] = 'invalidpassword';
970
			}
971
		} catch (\OC\User\LoginException $e) {
972
			$messages[] = $e->getMessage();
973
		} catch (\Exception $ex) {
974
			\OCP\Util::logException('handleLogin', $ex);
975
			// do not disclose information. show generic error
976
			$error[] = 'internalexception';
977
		}
978
979
		OC_Util::displayLoginPage(array_unique($error), $messages);
980
	}
981
982
	/**
983
	 * Remove outdated and therefore invalid tokens for a user
984
	 * @param string $user
985
	 */
986
	protected static function cleanupLoginTokens($user) {
987
		$config = \OC::$server->getConfig();
988
		$cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
989
		$tokens = $config->getUserKeys($user, 'login_token');
990
		foreach ($tokens as $token) {
991
			$time = $config->getUserValue($user, 'login_token', $token);
992
			if ($time < $cutoff) {
993
				$config->deleteUserValue($user, 'login_token', $token);
994
			}
995
		}
996
	}
997
998
	/**
999
	 * Try to login a user via HTTP authentication
1000
	 * @return bool|void
1001
	 */
1002
	protected static function tryApacheAuth() {
1003
		$return = OC_User::handleApacheAuth();
1004
1005
		// if return is true we are logged in -> redirect to the default page
1006
		if ($return === true) {
1007
			$_REQUEST['redirect_url'] = \OC::$server->getRequest()->getRequestUri();
1008
			OC_Util::redirectToDefaultPage();
1009
			exit;
1010
		}
1011
1012
		// in case $return is null apache based auth is not enabled
1013
		return is_null($return) ? false : true;
1014
	}
1015
1016
	/**
1017
	 * Try to login a user using the remember me cookie.
1018
	 * @return bool Whether the provided cookie was valid
1019
	 */
1020
	protected static function tryRememberLogin() {
1021
		if (!isset($_COOKIE["oc_remember_login"])
1022
			|| !isset($_COOKIE["oc_token"])
1023
			|| !isset($_COOKIE["oc_username"])
1024
			|| !$_COOKIE["oc_remember_login"]
1025
			|| !OC_Util::rememberLoginAllowed()
1026
		) {
1027
			return false;
1028
		}
1029
1030
		if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
1031
			\OCP\Util::writeLog('core', 'Trying to login from cookie', \OCP\Util::DEBUG);
1032
		}
1033
1034
		if(OC_User::userExists($_COOKIE['oc_username'])) {
1035
			self::cleanupLoginTokens($_COOKIE['oc_username']);
1036
			// verify whether the supplied "remember me" token was valid
1037
			$granted = OC_User::loginWithCookie(
1038
				$_COOKIE['oc_username'], $_COOKIE['oc_token']);
1039
			if($granted === true) {
1040
				OC_Util::redirectToDefaultPage();
1041
				// doesn't return
1042
			}
1043
			\OCP\Util::writeLog('core', 'Authentication cookie rejected for user ' .
1044
				$_COOKIE['oc_username'], \OCP\Util::WARN);
1045
			// if you reach this point you have changed your password
1046
			// or you are an attacker
1047
			// we can not delete tokens here because users may reach
1048
			// this point multiple times after a password change
1049
		}
1050
1051
		OC_User::unsetMagicInCookie();
1052
		return true;
1053
	}
1054
1055
	/**
1056
	 * Tries to login a user using the form based authentication
1057
	 * @return bool|void
1058
	 */
1059
	protected static function tryFormLogin() {
1060
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
1061
			return false;
1062
		}
1063
1064
		if(!OC_Util::isCallRegistered()) {
1065
			return false;
1066
		}
1067
		OC_App::loadApps();
1068
1069
		//setup extra user backends
1070
		OC_User::setupBackends();
1071
1072
		if (OC_User::login((string)$_POST["user"], (string)$_POST["password"])) {
1073
			$userId = OC_User::getUser();
1074
1075
			// setting up the time zone
1076
			if (isset($_POST['timezone-offset'])) {
1077
				self::$server->getSession()->set('timezone', (string)$_POST['timezone-offset']);
1078
				self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string)$_POST['timezone']);
1079
			}
1080
1081
			self::cleanupLoginTokens($userId);
1082
			if (!empty($_POST["remember_login"])) {
1083
				$config = self::$server->getConfig();
1084
				if ($config->getSystemValue('debug', false)) {
1085
					self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
1086
				}
1087
				$token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
1088
				$config->setUserValue($userId, 'login_token', $token, time());
1089
				OC_User::setMagicInCookie($userId, $token);
1090
			} else {
1091
				OC_User::unsetMagicInCookie();
1092
			}
1093
			OC_Util::redirectToDefaultPage();
1094
			exit();
1095
		}
1096
		return true;
1097
	}
1098
1099
}
1100
1101
1102
OC::init();
1103