Completed
Pull Request — stable8.2 (#24656)
by Joas
12:22
created

OC::checkConfig()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56
Metric Value
dl 0
loc 29
ccs 0
cts 23
cp 0
rs 6.7272
cc 7
eloc 20
nc 6
nop 0
crap 56
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
	 * @throws \RuntimeException when the 3rdparty directory is missing or
117
	 * the app path list is empty or contains an invalid path
118
	 */
119
	public static function initPaths() {
120
		// ensure we can find OC_Config
121
		set_include_path(
122
			OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
123
			get_include_path()
124
		);
125
126
		if(defined('PHPUNIT_CONFIG_DIR')) {
127
			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
128
		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
129
			self::$configDir = OC::$SERVERROOT . '/tests/config/';
130
		} else {
131
			self::$configDir = OC::$SERVERROOT . '/config/';
132
		}
133
		OC_Config::$object = new \OC\Config(self::$configDir);
134
135
		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
136
		/**
137
		 * FIXME: The following lines are required because we can't yet instantiiate
138
		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
139
		 */
140
		$params = [
141
			'server' => [
142
				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
143
				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
144
			],
145
		];
146
		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig()));
147
		$scriptName = $fakeRequest->getScriptName();
148
		if (substr($scriptName, -1) == '/') {
149
			$scriptName .= 'index.php';
150
			//make sure suburi follows the same rules as scriptName
151
			if (substr(OC::$SUBURI, -9) != 'index.php') {
152
				if (substr(OC::$SUBURI, -1) != '/') {
153
					OC::$SUBURI = OC::$SUBURI . '/';
154
				}
155
				OC::$SUBURI = OC::$SUBURI . 'index.php';
156
			}
157
		}
158
159
160
		if (OC::$CLI) {
161
			OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
162
		} else {
163
			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
164
				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
165
166
				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
167
					OC::$WEBROOT = '/' . OC::$WEBROOT;
168
				}
169
			} else {
170
				// The scriptName is not ending with OC::$SUBURI
171
				// This most likely means that we are calling from CLI.
172
				// However some cron jobs still need to generate
173
				// a web URL, so we use overwritewebroot as a fallback.
174
				OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
175
			}
176
		}
177
178
		// search the 3rdparty folder
179
		OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', null);
180
		OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', null);
181
182
		if (empty(OC::$THIRDPARTYROOT) && empty(OC::$THIRDPARTYWEBROOT)) {
183
			if (file_exists(OC::$SERVERROOT . '/3rdparty')) {
184
				OC::$THIRDPARTYROOT = OC::$SERVERROOT;
185
				OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
186
			} elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
187
				OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
188
				OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
189
			}
190
		}
191
		if (empty(OC::$THIRDPARTYROOT) || !file_exists(OC::$THIRDPARTYROOT)) {
192
			throw new \RuntimeException('3rdparty directory not found! Please put the ownCloud 3rdparty'
193
				. ' folder in the ownCloud folder or the folder above.'
194
				. ' You can also configure the location in the config.php file.');
195
		}
196
197
		// search the apps folder
198
		$config_paths = OC_Config::getValue('apps_paths', array());
199
		if (!empty($config_paths)) {
200
			foreach ($config_paths as $paths) {
201
				if (isset($paths['url']) && isset($paths['path'])) {
202
					$paths['url'] = rtrim($paths['url'], '/');
203
					$paths['path'] = rtrim($paths['path'], '/');
204
					OC::$APPSROOTS[] = $paths;
205
				}
206
			}
207 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...
208
			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
209
		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
210
			OC::$APPSROOTS[] = array(
211
				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
212
				'url' => '/apps',
213
				'writable' => true
214
			);
215
		}
216
217
		if (empty(OC::$APPSROOTS)) {
218
			throw new \RuntimeException('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
219
				. ' or the folder above. You can also configure the location in the config.php file.');
220
		}
221
		$paths = array();
222
		foreach (OC::$APPSROOTS as $path) {
223
			$paths[] = $path['path'];
224
			if (!is_dir($path['path'])) {
225
				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the ownCloud apps folder in the'
226
					. ' ownCloud folder or the folder above. You can also configure the location in the'
227
					. ' config.php file.', $path['path']));
228
			}
229
		}
230
231
		// set the right include path
232
		set_include_path(
233
			OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
234
			OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
235
			OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
236
			implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
237
			get_include_path() . PATH_SEPARATOR .
238
			OC::$SERVERROOT
239
		);
240
	}
241
242
	public static function checkConfig() {
243
		$l = \OC::$server->getL10N('lib');
244
245
		// Create config if it does not already exist
246
		$configFilePath = self::$configDir .'/config.php';
247
		if(!file_exists($configFilePath)) {
248
			@touch($configFilePath);
249
		}
250
251
		// Check if config is writable
252
		$configFileWritable = is_writable($configFilePath);
253
		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
			|| !$configFileWritable && self::checkUpgrade(false)) {
255
			if (self::$CLI) {
256
				echo $l->t('Cannot write into "config" directory!')."\n";
257
				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
258
				echo "\n";
259
				echo $l->t('See %s', array(\OC_Helper::linkToDocs('admin-dir_permissions')))."\n";
260
				exit;
261
			} else {
262
				OC_Template::printErrorPage(
263
					$l->t('Cannot write into "config" directory!'),
264
					$l->t('This can usually be fixed by '
265
					. '%sgiving the webserver write access to the config directory%s.',
266
					 array('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>'))
267
				);
268
			}
269
		}
270
	}
271
272
	public static function checkInstalled() {
273
		if (defined('OC_CONSOLE')) {
274
			return;
275
		}
276
		// Redirect to installer if not installed
277
		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
278
			if (OC::$CLI) {
279
				throw new Exception('Not installed');
280
			} else {
281
				$url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
282
				header('Location: ' . $url);
283
			}
284
			exit();
285
		}
286
	}
287
288
	public static function checkMaintenanceMode() {
289
		// Allow ajax update script to execute without being stopped
290
		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
291
			// send http status 503
292
			header('HTTP/1.1 503 Service Temporarily Unavailable');
293
			header('Status: 503 Service Temporarily Unavailable');
294
			header('Retry-After: 120');
295
296
			// render error page
297
			$template = new OC_Template('', 'update.user', 'guest');
298
			OC_Util::addscript('maintenance-check');
299
			$template->printPage();
300
			die();
301
		}
302
	}
303
304
	public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
305
		if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
306
			return;
307
		}
308
		$user = OC_User::getUserSession()->getUser();
309
		if ($user) {
310
			$group = \OC::$server->getGroupManager()->get('admin');
311
			if ($group->inGroup($user)) {
312
				return;
313
			}
314
		} else {
315
			if(!$lockIfNoUserLoggedIn) {
316
				return;
317
			}
318
		}
319
		// send http status 503
320
		header('HTTP/1.1 503 Service Temporarily Unavailable');
321
		header('Status: 503 Service Temporarily Unavailable');
322
		header('Retry-After: 120');
323
324
		// render error page
325
		$template = new OC_Template('', 'singleuser.user', 'guest');
326
		$template->printPage();
327
		die();
328
	}
329
330
	/**
331
	 * check if the instance needs to perform an upgrade
332
	 *
333
	 * @return bool
334
	 * @deprecated use \OCP\Util::needUpgrade() instead
335
	 */
336
	public static function needUpgrade() {
337
		return \OCP\Util::needUpgrade();
338
	}
339
340
	/**
341
	 * Checks if the version requires an update and shows
342
	 * @param bool $showTemplate Whether an update screen should get shown
343
	 * @return bool|void
344
	 */
345 14
	public static function checkUpgrade($showTemplate = true) {
346 14
		if (\OCP\Util::needUpgrade()) {
347
			$systemConfig = \OC::$server->getSystemConfig();
348
			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
349
				self::printUpgradePage();
350
				exit();
351
			} else {
352
				return true;
353
			}
354
		}
355 14
		return false;
356
	}
357
358
	/**
359
	 * Prints the upgrade page
360
	 */
361
	private static function printUpgradePage() {
362
		$systemConfig = \OC::$server->getSystemConfig();
363
		$oldTheme = $systemConfig->getValue('theme');
364
		$systemConfig->setValue('theme', '');
365
		\OCP\Util::addScript('config'); // needed for web root
366
		\OCP\Util::addScript('update');
367
368
		// check whether this is a core update or apps update
369
		$installedVersion = $systemConfig->getValue('version', '0.0.0');
370
		$currentVersion = implode('.', OC_Util::getVersion());
371
372
		$appManager = \OC::$server->getAppManager();
373
374
		$tmpl = new OC_Template('', 'update.admin', 'guest');
375
		$tmpl->assign('version', OC_Util::getVersionString());
376
377
		// if not a core upgrade, then it's apps upgrade
378
		if (version_compare($currentVersion, $installedVersion, '=')) {
379
			$tmpl->assign('isAppsOnlyUpgrade', true);
380
		} else {
381
			$tmpl->assign('isAppsOnlyUpgrade', false);
382
		}
383
384
		// get third party apps
385
		$ocVersion = OC_Util::getVersion();
386
		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
387
		$tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
388
		$tmpl->assign('productName', 'ownCloud'); // for now
389
		$tmpl->assign('oldTheme', $oldTheme);
390
		$tmpl->printPage();
391
	}
392
393
	public static function initSession() {
394
		// prevents javascript from accessing php session cookies
395
		ini_set('session.cookie_httponly', true);
396
397
		// set the cookie path to the ownCloud directory
398
		$cookie_path = OC::$WEBROOT ? : '/';
399
		ini_set('session.cookie_path', $cookie_path);
400
401
		// Let the session name be changed in the initSession Hook
402
		$sessionName = OC_Util::getInstanceId();
403
404
		try {
405
			// Allow session apps to create a custom session object
406
			$useCustomSession = false;
407
			$session = self::$server->getSession();
408
			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
409
			if (!$useCustomSession) {
410
				// set the session name to the instance id - which is unique
411
				$session = new \OC\Session\Internal($sessionName);
412
			}
413
414
			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
415
			$session = $cryptoWrapper->wrapSession($session);
416
			self::$server->setSession($session);
417
418
			// if session cant be started break with http 500 error
419
		} catch (Exception $e) {
420
			\OCP\Util::logException('base', $e);
421
			//show the user a detailed error page
422
			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
423
			OC_Template::printExceptionErrorPage($e);
424
		}
425
426
		$sessionLifeTime = self::getSessionLifeTime();
427
		// regenerate session id periodically to avoid session fixation
428
		/**
429
		 * @var \OCP\ISession $session
430
		 */
431
		$session = self::$server->getSession();
432
		if (!$session->exists('SID_CREATED')) {
433
			$session->set('SID_CREATED', time());
434
		} else if (time() - $session->get('SID_CREATED') > $sessionLifeTime / 2) {
435
			session_regenerate_id(true);
436
			$session->set('SID_CREATED', time());
437
		}
438
439
		// session timeout
440
		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441
			if (isset($_COOKIE[session_name()])) {
442
				setcookie(session_name(), '', time() - 42000, $cookie_path);
443
			}
444
			$session->clear();
445
		}
446
447
		$session->set('LAST_ACTIVITY', time());
448
	}
449
450
	/**
451
	 * @return string
452
	 */
453
	private static function getSessionLifeTime() {
454
		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
455
	}
456
457
	public static function loadAppClassPaths() {
458 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...
459
			$file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
460
			if (file_exists($file)) {
461
				require_once $file;
462
			}
463
		}
464
	}
465
466
	/**
467
	 * Try to set some values to the required ownCloud default
468
	 */
469
	public static function setRequiredIniValues() {
470
		@ini_set('default_charset', 'UTF-8');
471
	}
472
473
	public static function init() {
474
		// calculate the root directories
475
		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
476
477
		// register autoloader
478
		$loaderStart = microtime(true);
479
		require_once __DIR__ . '/autoloader.php';
480
		self::$loader = new \OC\Autoloader([
481
			OC::$SERVERROOT . '/lib',
482
			OC::$SERVERROOT . '/core',
483
			OC::$SERVERROOT . '/settings',
484
			OC::$SERVERROOT . '/ocs',
485
			OC::$SERVERROOT . '/ocs-provider',
486
			OC::$SERVERROOT . '/3rdparty',
487
			OC::$SERVERROOT . '/tests',
488
		]);
489
		spl_autoload_register(array(self::$loader, 'load'));
490
		$loaderEnd = microtime(true);
491
492
		self::$CLI = (php_sapi_name() == 'cli');
493
494
		try {
495
			self::initPaths();
496
			// setup 3rdparty autoloader
497
			$vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
498
			if (!file_exists($vendorAutoLoad)) {
499
				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".');
500
			}
501
			require_once $vendorAutoLoad;
502
503
		} catch (\RuntimeException $e) {
504
			OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
505
			// we can't use the template error page here, because this needs the
506
			// DI container which isn't available yet
507
			print($e->getMessage());
508
			exit();
509
		}
510
511
		// setup the basic server
512
		self::$server = new \OC\Server(\OC::$WEBROOT);
513
		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
514
		\OC::$server->getEventLogger()->start('boot', 'Initialize');
515
516
		// Don't display errors and log them
517
		error_reporting(E_ALL | E_STRICT);
518
		@ini_set('display_errors', 0);
519
		@ini_set('log_errors', 1);
520
521
		date_default_timezone_set('UTC');
522
523
		//try to configure php to enable big file uploads.
524
		//this doesn´t work always depending on the webserver and php configuration.
525
		//Let´s try to overwrite some defaults anyway
526
527
		//try to set the maximum execution time to 60min
528
		@set_time_limit(3600);
529
		@ini_set('max_execution_time', 3600);
530
		@ini_set('max_input_time', 3600);
531
532
		//try to set the maximum filesize to 10G
533
		@ini_set('upload_max_filesize', '10G');
534
		@ini_set('post_max_size', '10G');
535
		@ini_set('file_uploads', '50');
536
537
		self::setRequiredIniValues();
538
		self::handleAuthHeaders();
539
		self::registerAutoloaderCache();
540
541
		// initialize intl fallback is necessary
542
		\Patchwork\Utf8\Bootup::initIntl();
543
		OC_Util::isSetLocaleWorking();
544
545
		if (!defined('PHPUNIT_RUN')) {
546
			$logger = \OC::$server->getLogger();
547
			OC\Log\ErrorHandler::setLogger($logger);
548
			if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
549
				OC\Log\ErrorHandler::register(true);
550
				set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
551
			} else {
552
				OC\Log\ErrorHandler::register();
553
			}
554
		}
555
556
		// register the stream wrappers
557
		stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
558
		stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
559
		stream_wrapper_register('close', 'OC\Files\Stream\Close');
560
		stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
561
		stream_wrapper_register('oc', 'OC\Files\Stream\OC');
562
563
		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
564
		OC_App::loadApps(array('session'));
565
		if (!self::$CLI) {
566
			self::initSession();
567
		}
568
		\OC::$server->getEventLogger()->end('init_session');
569
		self::checkConfig();
570
		self::checkInstalled();
571
572
		OC_Response::addSecurityHeaders();
573
		if(self::$server->getRequest()->getServerProtocol() === 'https') {
574
			ini_set('session.cookie_secure', true);
575
		}
576
577
		if (!defined('OC_CONSOLE')) {
578
			$errors = OC_Util::checkServer(\OC::$server->getConfig());
579
			if (count($errors) > 0) {
580
				if (self::$CLI) {
581
					// Convert l10n string into regular string for usage in database
582
					$staticErrors = [];
583
					foreach ($errors as $error) {
584
						echo $error['error'] . "\n";
585
						echo $error['hint'] . "\n\n";
586
						$staticErrors[] = [
587
							'error' => (string)$error['error'],
588
							'hint' => (string)$error['hint'],
589
						];
590
					}
591
592
					try {
593
						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
594
					} catch (\Exception $e) {
595
						echo('Writing to database failed');
596
					}
597
					exit(1);
598
				} else {
599
					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
600
					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
601
					exit;
602
				}
603 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...
604
				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
605
			}
606
		}
607
		//try to set the session lifetime
608
		$sessionLifeTime = self::getSessionLifeTime();
609
		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
610
611
		$systemConfig = \OC::$server->getSystemConfig();
612
613
		// User and Groups
614
		if (!$systemConfig->getValue("installed", false)) {
615
			self::$server->getSession()->set('user_id', '');
616
		}
617
618
		OC_User::useBackend(new OC_User_Database());
619
		OC_Group::useBackend(new OC_Group_Database());
620
621
		// Subscribe to the hook
622
		\OCP\Util::connectHook(
623
			'\OCA\Files_Sharing\API\Server2Server',
624
			'preLoginNameUsedAsUserName',
625
			'\OC_User_Database',
626
			'preLoginNameUsedAsUserName'
627
		);
628
629
		//setup extra user backends
630
		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...
631
			OC_User::setupBackends();
632
		}
633
634
		self::registerCacheHooks();
635
		self::registerFilesystemHooks();
636
		if ($systemConfig->getValue('enable_previews', true)) {
637
			self::registerPreviewHooks();
638
		}
639
		self::registerShareHooks();
640
		self::registerLogRotate();
641
		self::registerLocalAddressBook();
642
		self::registerEncryptionWrapper();
643
		self::registerEncryptionHooks();
644
645
		//make sure temporary files are cleaned up
646
		$tmpManager = \OC::$server->getTempManager();
647
		register_shutdown_function(array($tmpManager, 'clean'));
648
		$lockProvider = \OC::$server->getLockingProvider();
649
		register_shutdown_function(array($lockProvider, 'releaseAll'));
650
651
		// Check whether the sample configuration has been copied
652
		if($systemConfig->getValue('copied_sample_config', false)) {
653
			$l = \OC::$server->getL10N('lib');
654
			header('HTTP/1.1 503 Service Temporarily Unavailable');
655
			header('Status: 503 Service Temporarily Unavailable');
656
			OC_Template::printErrorPage(
657
				$l->t('Sample configuration detected'),
658
				$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')
659
			);
660
			return;
661
		}
662
663
		$request = \OC::$server->getRequest();
664
		$host = $request->getInsecureServerHost();
665
		/**
666
		 * if the host passed in headers isn't trusted
667
		 * FIXME: Should not be in here at all :see_no_evil:
668
		 */
669
		if (!OC::$CLI
670
			// overwritehost is always trusted, workaround to not have to make
671
			// \OC\AppFramework\Http\Request::getOverwriteHost public
672
			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
673
			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
674
			&& self::$server->getConfig()->getSystemValue('installed', false)
675
		) {
676
			header('HTTP/1.1 400 Bad Request');
677
			header('Status: 400 Bad Request');
678
679
			$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
680
			$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...
681
			$tmpl->printPage();
682
683
			exit();
684
		}
685
		\OC::$server->getEventLogger()->end('boot');
686
	}
687
688
	private static function registerLocalAddressBook() {
689
		self::$server->getContactsManager()->register(function() {
690
			$userManager = \OC::$server->getUserManager();
691
			\OC::$server->getContactsManager()->registerAddressBook(
692
				new \OC\Contacts\LocalAddressBook($userManager));
693
		});
694
	}
695
696
	/**
697
	 * register hooks for the cache
698
	 */
699 263
	public static function registerCacheHooks() {
700
		//don't try to do this before we are properly setup
701
		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...
702
703
			// NOTE: This will be replaced to use OCP
704
			$userSession = self::$server->getUserSession();
705 263
			$userSession->listen('\OC\User', 'postLogin', function () {
706
				try {
707 263
					$cache = new \OC\Cache\File();
708 263
					$cache->gc();
709 263
				} catch (\OC\ServerNotAvailableException $e) {
710
					// not a GC exception, pass it on
711
					throw $e;
712
				} catch (\Exception $e) {
713
					// a GC exception should not prevent users from using OC,
714 263
					// so log the exception
715
					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
716
				}
717
			});
718
		}
719
	}
720
721
	private static function registerEncryptionWrapper() {
722
		$manager = self::$server->getEncryptionManager();
723
		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
724
	}
725
726
	private static function registerEncryptionHooks() {
727
		$enabled = self::$server->getEncryptionManager()->isEnabled();
728
		if ($enabled) {
729
			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
730
			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
731
			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
732
			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
733
		}
734
	}
735
736
	/**
737
	 * register hooks for the cache
738
	 */
739
	public static function registerLogRotate() {
740
		$systemConfig = \OC::$server->getSystemConfig();
741
		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...
742
			//don't try to do this before we are properly setup
743
			//use custom logfile path if defined, otherwise use default of owncloud.log in data directory
744
			\OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
745
		}
746
	}
747
748
	/**
749
	 * register hooks for the filesystem
750
	 */
751
	public static function registerFilesystemHooks() {
752
		// Check for blacklisted files
753
		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
754
		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
755
	}
756
757
	/**
758
	 * register hooks for previews
759
	 */
760
	public static function registerPreviewHooks() {
761
		OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
762
		OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
763
		OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
764
		OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
765
		OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
766
		OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
767
		OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
768
		OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
769
	}
770 78
771 78
	/**
772 78
	 * register hooks for sharing
773 78
	 */
774 78
	public static function registerShareHooks() {
775 78
		if (\OC::$server->getSystemConfig()->getValue('installed')) {
776 78
			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
777 78
			OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
778 78
			OC_Hook::connect('OC_Group', 'pre_addToGroup', 'OC\Share\Hooks', 'pre_addToGroup');
779
			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
780
			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
781
		}
782
	}
783
784
	protected static function registerAutoloaderCache() {
785
		// The class loader takes an optional low-latency cache, which MUST be
786
		// namespaced. The instanceid is used for namespacing, but might be
787
		// unavailable at this point. Futhermore, it might not be possible to
788
		// generate an instanceid via \OC_Util::getInstanceId() because the
789
		// config file may not be writable. As such, we only register a class
790
		// loader cache if instanceid is available without trying to create one.
791
		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
792
		if ($instanceId) {
793
			try {
794
				$memcacheFactory = \OC::$server->getMemCacheFactory();
795
				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...
796
			} catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
797
			}
798
		}
799
	}
800
801
	/**
802
	 * Handle the request
803
	 */
804
	public static function handleRequest() {
805
806
		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
807
		$systemConfig = \OC::$server->getSystemConfig();
808
		// load all the classpaths from the enabled apps so they are available
809
		// in the routing files of each app
810
		OC::loadAppClassPaths();
811
812
		// Check if ownCloud is installed or in maintenance (update) mode
813
		if (!$systemConfig->getValue('installed', false)) {
814
			\OC::$server->getSession()->clear();
815
			$setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
816
				\OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
817
				\OC::$server->getSecureRandom());
818
			$controller = new OC\Core\Setup\Controller($setupHelper);
819
			$controller->run($_POST);
820
			exit();
821
		}
822
823
		$request = \OC::$server->getRequest()->getPathInfo();
824
		if (substr($request, -3) !== '.js') { // we need these files during the upgrade
825
			self::checkMaintenanceMode();
826
			self::checkUpgrade();
827
		}
828
829
		// Always load authentication apps
830
		OC_App::loadApps(['authentication']);
831
832
		// Load minimum set of apps
833
		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...
834
			&& !$systemConfig->getValue('maintenance', false)) {
835
			// For logged-in users: Load everything
836
			if(OC_User::isLoggedIn()) {
837
				OC_App::loadApps();
838
			} else {
839
				// For guests: Load only filesystem and logging
840
				OC_App::loadApps(array('filesystem', 'logging'));
841
				\OC_User::tryBasicAuthLogin();
842
			}
843
		}
844
845
		if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
846
			try {
847
				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...
848
					OC_App::loadApps(array('filesystem', 'logging'));
849
					OC_App::loadApps();
850
				}
851
				self::checkSingleUserMode();
852
				OC_Util::setupFS();
853
				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
854
				return;
855
			} 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...
856
				//header('HTTP/1.0 404 Not Found');
857
			} 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...
858
				OC_Response::setStatus(405);
859
				return;
860
			}
861
		}
862
863
		// Handle redirect URL for logged in users
864
		if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
865
			$location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
866
867
			// Deny the redirect if the URL contains a @
868
			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
869
			if (strpos($location, '@') === false) {
870
				header('Location: ' . $location);
871
				return;
872
			}
873
		}
874
		// Handle WebDAV
875
		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
876
			// not allowed any more to prevent people
877
			// mounting this root directly.
878
			// Users need to mount remote.php/webdav instead.
879
			header('HTTP/1.1 405 Method Not Allowed');
880
			header('Status: 405 Method Not Allowed');
881
			return;
882
		}
883
884
		// Redirect to index if the logout link is accessed without valid session
885
		// this is needed to prevent "Token expired" messages while login if a session is expired
886
		// @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
887
		if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
888
			header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
889
			return;
890
		}
891
892
		// Someone is logged in
893
		if (OC_User::isLoggedIn()) {
894
			OC_App::loadApps();
895
			OC_User::setupBackends();
896
			OC_Util::setupFS();
897
			if (isset($_GET["logout"]) and ($_GET["logout"])) {
898
				OC_JSON::callCheck();
899
				if (isset($_COOKIE['oc_token'])) {
900
					\OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
901
				}
902
				OC_User::logout();
903
				// redirect to webroot and add slash if webroot is empty
904
				header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
905
			} else {
906
				// Redirect to default application
907
				OC_Util::redirectToDefaultPage();
908
			}
909
		} else {
910
			// Not handled and not logged in
911
			self::handleLogin();
912
		}
913
	}
914
915
	protected static function handleAuthHeaders() {
916
		//copy http auth headers for apache+php-fcgid work around
917
		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
918
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
919
		}
920
921
		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
922
		$vars = array(
923
			'HTTP_AUTHORIZATION', // apache+php-cgi work around
924
			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
925
		);
926
		foreach ($vars as $var) {
927
			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
928
				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
929
				$_SERVER['PHP_AUTH_USER'] = $name;
930
				$_SERVER['PHP_AUTH_PW'] = $password;
931
				break;
932
			}
933
		}
934
	}
935
936
	protected static function handleLogin() {
937
		OC_App::loadApps(array('prelogin'));
938
		$error = array();
939
		$messages = [];
940
941
		try {
942
			// auth possible via apache module?
943
			if (OC::tryApacheAuth()) {
944
				$error[] = 'apacheauthfailed';
945
			} // remember was checked after last login
946
			elseif (OC::tryRememberLogin()) {
947
				$error[] = 'invalidcookie';
948
			} // logon via web form
949
			elseif (OC::tryFormLogin()) {
950
				$error[] = 'invalidpassword';
951
			}
952
		} catch (\OC\User\LoginException $e) {
953
			$messages[] = $e->getMessage();
954
		} catch (\Exception $ex) {
955
			\OCP\Util::logException('handleLogin', $ex);
956
			// do not disclose information. show generic error
957
			$error[] = 'internalexception';
958
		}
959
960
		OC_Util::displayLoginPage(array_unique($error), $messages);
961
	}
962
963
	/**
964
	 * Remove outdated and therefore invalid tokens for a user
965
	 * @param string $user
966
	 */
967
	protected static function cleanupLoginTokens($user) {
968
		$config = \OC::$server->getConfig();
969
		$cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
970
		$tokens = $config->getUserKeys($user, 'login_token');
971
		foreach ($tokens as $token) {
972
			$time = $config->getUserValue($user, 'login_token', $token);
973
			if ($time < $cutoff) {
974
				$config->deleteUserValue($user, 'login_token', $token);
975
			}
976
		}
977
	}
978
979
	/**
980
	 * Try to login a user via HTTP authentication
981
	 * @return bool|void
982
	 */
983
	protected static function tryApacheAuth() {
984
		$return = OC_User::handleApacheAuth();
985
986
		// if return is true we are logged in -> redirect to the default page
987
		if ($return === true) {
988
			$_REQUEST['redirect_url'] = \OC::$server->getRequest()->getRequestUri();
989
			OC_Util::redirectToDefaultPage();
990
			exit;
991
		}
992
993
		// in case $return is null apache based auth is not enabled
994
		return is_null($return) ? false : true;
995
	}
996
997
	/**
998
	 * Try to login a user using the remember me cookie.
999
	 * @return bool Whether the provided cookie was valid
1000
	 */
1001
	protected static function tryRememberLogin() {
1002
		if (!isset($_COOKIE["oc_remember_login"])
1003
			|| !isset($_COOKIE["oc_token"])
1004
			|| !isset($_COOKIE["oc_username"])
1005
			|| !$_COOKIE["oc_remember_login"]
1006
			|| !OC_Util::rememberLoginAllowed()
1007
		) {
1008
			return false;
1009
		}
1010
1011
		if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
1012
			\OCP\Util::writeLog('core', 'Trying to login from cookie', \OCP\Util::DEBUG);
1013
		}
1014
1015
		if(OC_User::userExists($_COOKIE['oc_username'])) {
1016
			self::cleanupLoginTokens($_COOKIE['oc_username']);
1017
			// verify whether the supplied "remember me" token was valid
1018
			$granted = OC_User::loginWithCookie(
1019
				$_COOKIE['oc_username'], $_COOKIE['oc_token']);
1020
			if($granted === true) {
1021
				OC_Util::redirectToDefaultPage();
1022
				// doesn't return
1023
			}
1024
			\OCP\Util::writeLog('core', 'Authentication cookie rejected for user ' .
1025
				$_COOKIE['oc_username'], \OCP\Util::WARN);
1026
			// if you reach this point you have changed your password
1027
			// or you are an attacker
1028
			// we can not delete tokens here because users may reach
1029
			// this point multiple times after a password change
1030
		}
1031
1032
		OC_User::unsetMagicInCookie();
1033
		return true;
1034
	}
1035
1036
	/**
1037
	 * Tries to login a user using the form based authentication
1038
	 * @return bool|void
1039
	 */
1040
	protected static function tryFormLogin() {
1041
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
1042
			return false;
1043
		}
1044
1045
		if(!OC_Util::isCallRegistered()) {
1046
			return false;
1047
		}
1048
		OC_App::loadApps();
1049
1050
		//setup extra user backends
1051
		OC_User::setupBackends();
1052
1053
		if (OC_User::login((string)$_POST["user"], (string)$_POST["password"])) {
1054
			$userId = OC_User::getUser();
1055
1056
			// setting up the time zone
1057
			if (isset($_POST['timezone-offset'])) {
1058
				self::$server->getSession()->set('timezone', (string)$_POST['timezone-offset']);
1059
				self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string)$_POST['timezone']);
1060
			}
1061
1062
			self::cleanupLoginTokens($userId);
1063
			if (!empty($_POST["remember_login"])) {
1064
				$config = self::$server->getConfig();
1065
				if ($config->getSystemValue('debug', false)) {
1066
					self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
1067
				}
1068
				$token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
1069
				$config->setUserValue($userId, 'login_token', $token, time());
1070
				OC_User::setMagicInCookie($userId, $token);
1071
			} else {
1072
				OC_User::unsetMagicInCookie();
1073
			}
1074
			OC_Util::redirectToDefaultPage();
1075
			exit();
1076
		}
1077
		return true;
1078
	}
1079
1080
}
1081
1082
1083
OC::init();
1084