Completed
Push — stable8.1 ( 7a1b8f...6080a3 )
by
unknown
107:52
created

base.php ➔ get_temp_dir()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7.392
Metric Value
cc 7
eloc 11
nc 7
nop 0
dl 0
loc 14
ccs 8
cts 10
cp 0.8
crap 7.392
rs 8.2222
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 Jakob Sack <[email protected]>
17
 * @author Jan-Christoph Borchardt <[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 Michael Gapczynski <[email protected]>
23
 * @author Morris Jobke <[email protected]>
24
 * @author Owen Winkler <[email protected]>
25
 * @author Ramiro Aparicio <[email protected]>
26
 * @author Robin Appelman <[email protected]>
27
 * @author Robin McCorkell <[email protected]>
28
 * @author scolebrook <[email protected]>
29
 * @author Stefan Herbrechtsmeier <[email protected]>
30
 * @author Thomas Müller <[email protected]>
31
 * @author Thomas Tanghus <[email protected]>
32
 * @author Victor Dubiniuk <[email protected]>
33
 * @author Vincent Petry <[email protected]>
34
 * @author Volkan Gezer <[email protected]>
35
 *
36
 * @copyright Copyright (c) 2015, ownCloud, Inc.
37
 * @license AGPL-3.0
38
 *
39
 * This code is free software: you can redistribute it and/or modify
40
 * it under the terms of the GNU Affero General Public License, version 3,
41
 * as published by the Free Software Foundation.
42
 *
43
 * This program is distributed in the hope that it will be useful,
44
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46
 * GNU Affero General Public License for more details.
47
 *
48
 * You should have received a copy of the GNU Affero General Public License, version 3,
49
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
50
 *
51
 */
52
53
require_once 'public/constants.php';
54
55
/**
56
 * Class that is a namespace for all global OC variables
57
 * No, we can not put this class in its own file because it is used by
58
 * OC_autoload!
59
 */
60
class OC {
61
	/**
62
	 * Associative array for autoloading. classname => filename
63
	 */
64
	public static $CLASSPATH = array();
65
	/**
66
	 * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
67
	 */
68
	public static $SERVERROOT = '';
69
	/**
70
	 * the current request path relative to the owncloud root (e.g. files/index.php)
71
	 */
72
	private static $SUBURI = '';
73
	/**
74
	 * the owncloud root path for http requests (e.g. owncloud/)
75
	 */
76
	public static $WEBROOT = '';
77
	/**
78
	 * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
79
	 */
80
	public static $THIRDPARTYROOT = '';
81
	/**
82
	 * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
83
	 */
84
	public static $THIRDPARTYWEBROOT = '';
85
	/**
86
	 * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
87
	 * web path in 'url'
88
	 */
89
	public static $APPSROOTS = array();
90
91
	public static $configDir;
92
93
	/**
94
	 * requested app
95
	 */
96
	public static $REQUESTEDAPP = '';
97
98
	/**
99
	 * check if ownCloud runs in cli mode
100
	 */
101
	public static $CLI = false;
102
103
	/**
104
	 * @var \OC\Autoloader $loader
105
	 */
106
	public static $loader = null;
107
108
	/**
109
	 * @var \OC\Server
110
	 */
111
	public static $server = null;
112
113
	/**
114
	 * @throws \RuntimeException when the 3rdparty directory is missing or
115
	 * the app path list is empty or contains an invalid path
116
	 */
117
	public static function initPaths() {
118
		// calculate the root directories
119
		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
120
121
		// ensure we can find OC_Config
122
		set_include_path(
123
			OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
124
			get_include_path()
125
		);
126
127
		if(defined('PHPUNIT_CONFIG_DIR')) {
128
			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
129
		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
130
			self::$configDir = OC::$SERVERROOT . '/tests/config/';
131
		} else {
132
			self::$configDir = OC::$SERVERROOT . '/config/';
133
		}
134
		OC_Config::$object = new \OC\Config(self::$configDir);
135
136
		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
		/**
138
		 * FIXME: The following line is required because of a cyclic dependency
139
		 *        on IRequest.
140
		 */
141
		$params = [
142
			'server' => [
143
				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
			],
146
		];
147
		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig()));
148
		$scriptName = $fakeRequest->getScriptName();
149
		if (substr($scriptName, -1) == '/') {
150
			$scriptName .= 'index.php';
151
			//make sure suburi follows the same rules as scriptName
152
			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
				if (substr(OC::$SUBURI, -1) != '/') {
154
					OC::$SUBURI = OC::$SUBURI . '/';
155
				}
156
				OC::$SUBURI = OC::$SUBURI . 'index.php';
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 in case it does not already exists
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 && \OCP\Util::needUpgrade()) {
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 preform 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
	public static function checkUpgrade($showTemplate = true) {
346
		if (\OCP\Util::needUpgrade()) {
347
			$systemConfig = \OC::$server->getSystemConfig();
348
			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
349
				$version = OC_Util::getVersion();
350
				$oldTheme = $systemConfig->getValue('theme');
351
				$systemConfig->setValue('theme', '');
352
				OC_Util::addScript('config'); // needed for web root
353
				OC_Util::addScript('update');
354
				$tmpl = new OC_Template('', 'update.admin', 'guest');
355
				$tmpl->assign('version', OC_Util::getVersionString());
356
357
				// get third party apps
358
				$apps = OC_App::getEnabledApps();
359
				$incompatibleApps = array();
360
				foreach ($apps as $appId) {
361
					$info = OC_App::getAppInfo($appId);
362
					if(!OC_App::isAppCompatible($version, $info)) {
0 ignored issues
show
Documentation introduced by
$version is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug introduced by
It seems like $info defined by \OC_App::getAppInfo($appId) on line 361 can also be of type null; however, OC_App::isAppCompatible() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
363
						$incompatibleApps[] = $info;
364
					}
365
				}
366
				$tmpl->assign('appList', $incompatibleApps);
367
				$tmpl->assign('productName', 'ownCloud'); // for now
368
				$tmpl->assign('oldTheme', $oldTheme);
369
				$tmpl->printPage();
370
				exit();
371
			} else {
372
				return true;
373
			}
374
		}
375
		return false;
376
	}
377
378
	public static function initTemplateEngine() {
379
		// Add the stuff we need always
380
		// following logic will import all vendor libraries that are
381
		// specified in core/js/core.json
382
		$fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
383
		if($fileContent !== false) {
384
			$coreDependencies = json_decode($fileContent, true);
385
			foreach($coreDependencies['vendor'] as $vendorLibrary) {
386
				// remove trailing ".js" as addVendorScript will append it
387
				OC_Util::addVendorScript(
388
					substr($vendorLibrary, 0, strlen($vendorLibrary) - 3));
389
			}
390
		} else {
391
			throw new \Exception('Cannot read core/js/core.json');
392
		}
393
394
		OC_Util::addScript("placeholders");
395
		OC_Util::addScript("jquery-tipsy");
396
		OC_Util::addScript("compatibility");
397
		OC_Util::addScript("jquery.ocdialog");
398
		OC_Util::addScript("oc-dialogs");
399
		OC_Util::addScript("js");
400
		OC_Util::addScript("l10n");
401
		OC_Util::addTranslations("core");
402
		OC_Util::addScript("octemplate");
403
		OC_Util::addScript("eventsource");
404
		OC_Util::addScript("config");
405
		//OC_Util::addScript( "multiselect" );
406
		OC_Util::addScript('search', 'search');
407
		OC_Util::addScript("oc-requesttoken");
408
		OC_Util::addScript("apps");
409
		OC_Util::addVendorScript('snapjs/dist/latest/snap');
410
411
		// avatars
412
		if (\OC::$server->getSystemConfig()->getValue('enable_avatars', true) === true) {
413
			\OC_Util::addScript('placeholder');
414
			\OC_Util::addVendorScript('blueimp-md5/js/md5');
415
			\OC_Util::addScript('jquery.avatar');
416
			\OC_Util::addScript('avatar');
417
		}
418
419
		OC_Util::addStyle("styles");
420
		OC_Util::addStyle("header");
421
		OC_Util::addStyle("mobile");
422
		OC_Util::addStyle("icons");
423
		OC_Util::addStyle("fonts");
424
		OC_Util::addStyle("apps");
425
		OC_Util::addStyle("fixes");
426
		OC_Util::addStyle("multiselect");
427
		OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui');
428
		OC_Util::addStyle('jquery-ui-fixes');
429
		OC_Util::addStyle("jquery-tipsy");
430
		OC_Util::addStyle("jquery.ocdialog");
431
	}
432
433
	public static function initSession() {
434
		// prevents javascript from accessing php session cookies
435
		ini_set('session.cookie_httponly', true);
436
437
		// set the cookie path to the ownCloud directory
438
		$cookie_path = OC::$WEBROOT ? : '/';
439
		ini_set('session.cookie_path', $cookie_path);
440
441
		// Let the session name be changed in the initSession Hook
442
		$sessionName = OC_Util::getInstanceId();
443
444
		try {
445
			// Allow session apps to create a custom session object
446
			$useCustomSession = false;
447
			$session = self::$server->getSession();
448
			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
449
			if($useCustomSession) {
450
				// use the session reference as the new Session
451
				self::$server->setSession($session);
452
			} else {
453
				// set the session name to the instance id - which is unique
454
				self::$server->setSession(new \OC\Session\Internal($sessionName));
455
			}
456
			// if session cant be started break with http 500 error
457
		} catch (Exception $e) {
458
			\OCP\Util::logException('base', $e);
459
			//show the user a detailed error page
460
			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
461
			OC_Template::printExceptionErrorPage($e);
462
		}
463
464
		$sessionLifeTime = self::getSessionLifeTime();
465
		// regenerate session id periodically to avoid session fixation
466
		/**
467
		 * @var \OCP\ISession $session
468
		 */
469
		$session = self::$server->getSession();
470
		if (!$session->exists('SID_CREATED')) {
471
			$session->set('SID_CREATED', time());
472
		} else if (time() - $session->get('SID_CREATED') > $sessionLifeTime / 2) {
473
			session_regenerate_id(true);
474
			$session->set('SID_CREATED', time());
475
		}
476
477
		// session timeout
478
		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
479
			if (isset($_COOKIE[session_name()])) {
480
				setcookie(session_name(), '', time() - 42000, $cookie_path);
481
			}
482
			session_unset();
483
			session_destroy();
484
			session_start();
485
		}
486
487
		$session->set('LAST_ACTIVITY', time());
488
	}
489
490
	/**
491
	 * @return string
492
	 */
493
	private static function getSessionLifeTime() {
494
		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
495
	}
496
497
	public static function loadAppClassPaths() {
498 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...
499
			$file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
500
			if (file_exists($file)) {
501
				require_once $file;
502
			}
503
		}
504
	}
505
506
	/**
507
	 * Try to set some values to the required ownCloud default
508
	 */
509
	public static function setRequiredIniValues() {
510
		@ini_set('default_charset', 'UTF-8');
511
	}
512
513
	public static function init() {
514
		// register autoloader
515
		$loaderStart = microtime(true);
516
		require_once __DIR__ . '/autoloader.php';
517
		self::$loader = new \OC\Autoloader();
518
		spl_autoload_register(array(self::$loader, 'load'));
519
		$loaderEnd = microtime(true);
520
521
		self::$CLI = (php_sapi_name() == 'cli');
522
523
		try {
524
			self::initPaths();
525
			// setup 3rdparty autoloader
526
			$vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
527
			if (!file_exists($vendorAutoLoad)) {
528
				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty".');
529
			}
530
			require_once $vendorAutoLoad;
531
532
		} catch (\RuntimeException $e) {
533
			OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
534
			// we can't use the template error page here, because this needs the
535
			// DI container which isn't available yet
536
			print($e->getMessage());
537
			exit();
538
		}
539
540
		// setup the basic server
541
		self::$server = new \OC\Server(\OC::$WEBROOT);
542
		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
543
		\OC::$server->getEventLogger()->start('boot', 'Initialize');
544
545
		// Don't display errors and log them
546
		error_reporting(E_ALL | E_STRICT);
547
		@ini_set('display_errors', 0);
548
		@ini_set('log_errors', 1);
549
550
		date_default_timezone_set('UTC');
551
552
		//try to configure php to enable big file uploads.
553
		//this doesn´t work always depending on the webserver and php configuration.
554
		//Let´s try to overwrite some defaults anyways
555
556
		//try to set the maximum execution time to 60min
557
		@set_time_limit(3600);
558
		@ini_set('max_execution_time', 3600);
559
		@ini_set('max_input_time', 3600);
560
561
		//try to set the maximum filesize to 10G
562
		@ini_set('upload_max_filesize', '10G');
563
		@ini_set('post_max_size', '10G');
564
		@ini_set('file_uploads', '50');
565
566
		self::setRequiredIniValues();
567
		self::handleAuthHeaders();
568
		self::registerAutoloaderCache();
569
570
		// initialize intl fallback is necessary
571
		\Patchwork\Utf8\Bootup::initIntl();
572
		OC_Util::isSetLocaleWorking();
573
574
		if (!defined('PHPUNIT_RUN')) {
575
			OC\Log\ErrorHandler::setLogger(OC_Log::$object);
576
			if (defined('DEBUG') and DEBUG) {
577
				OC\Log\ErrorHandler::register(true);
578
				set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
579
			} else {
580
				OC\Log\ErrorHandler::register();
581
			}
582
		}
583
584
		// register the stream wrappers
585
		stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
586
		stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
587
		stream_wrapper_register('close', 'OC\Files\Stream\Close');
588
		stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
589
		stream_wrapper_register('oc', 'OC\Files\Stream\OC');
590
591
		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
592
		OC_App::loadApps(array('session'));
593
		if (!self::$CLI) {
594
			self::initSession();
595
		}
596
		\OC::$server->getEventLogger()->end('init_session');
597
		self::initTemplateEngine();
598
		self::checkConfig();
599
		self::checkInstalled();
600
601
		OC_Response::addSecurityHeaders();
602
		if(self::$server->getRequest()->getServerProtocol() === 'https') {
603
			ini_set('session.cookie_secure', true);
604
		}
605
606
		if (!defined('OC_CONSOLE')) {
607
			$errors = OC_Util::checkServer(\OC::$server->getConfig());
608
			if (count($errors) > 0) {
609
				if (self::$CLI) {
610
					// Convert l10n string into regular string for usage in database
611
					$staticErrors = [];
612
					foreach ($errors as $error) {
613
						echo $error['error'] . "\n";
614
						echo $error['hint'] . "\n\n";
615
						$staticErrors[] = [
616
							'error' => (string)$error['error'],
617
							'hint' => (string)$error['hint'],
618
						];
619
					}
620
621
					try {
622
						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
623
					} catch (\Exception $e) {
624
						echo('Writing to database failed');
625
					}
626
					exit(1);
627
				} else {
628
					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
629
					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
630
					exit;
631
				}
632 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...
633
				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
634
			}
635
		}
636
		//try to set the session lifetime
637
		$sessionLifeTime = self::getSessionLifeTime();
638
		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
639
640
		$systemConfig = \OC::$server->getSystemConfig();
641
642
		// User and Groups
643
		if (!$systemConfig->getValue("installed", false)) {
644
			self::$server->getSession()->set('user_id', '');
645
		}
646
647
		OC_User::useBackend(new OC_User_Database());
648
		OC_Group::useBackend(new OC_Group_Database());
649
650
		//setup extra user backends
651
		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...
652
			OC_User::setupBackends();
653
		}
654
655
		self::registerCacheHooks();
656
		self::registerFilesystemHooks();
657
		if (\OC::$server->getSystemConfig()->getValue('enable_previews', true)) {
658
			self::registerPreviewHooks();
659
		}	
660
		self::registerShareHooks();
661
		self::registerLogRotate();
662
		self::registerLocalAddressBook();
663
		self::registerEncryptionWrapper();
664
		self::registerEncryptionHooks();
665
666
		//make sure temporary files are cleaned up
667
		$tmpManager = \OC::$server->getTempManager();
668
		register_shutdown_function(array($tmpManager, 'clean'));
669
		$lockProvider = \OC::$server->getLockingProvider();
670
		register_shutdown_function(array($lockProvider, 'releaseAll'));
671
672
		if ($systemConfig->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...
673
			if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
674
				OC_Util::addScript('backgroundjobs');
675
			}
676
		}
677
678
		// Check whether the sample configuration has been copied
679
		if($systemConfig->getValue('copied_sample_config', false)) {
680
			$l = \OC::$server->getL10N('lib');
681
			header('HTTP/1.1 503 Service Temporarily Unavailable');
682
			header('Status: 503 Service Temporarily Unavailable');
683
			OC_Template::printErrorPage(
684
				$l->t('Sample configuration detected'),
685
				$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')
686
			);
687
			return;
688
		}
689
690
		$request = \OC::$server->getRequest();
691
		$host = $request->getInsecureServerHost();
692
		/**
693
		 * if the host passed in headers isn't trusted
694
		 * FIXME: Should not be in here at all :see_no_evil:
695
		 */
696
		if (!OC::$CLI
697
			// overwritehost is always trusted, workaround to not have to make
698
			// \OC\AppFramework\Http\Request::getOverwriteHost public
699
			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
700
			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
701
			&& self::$server->getConfig()->getSystemValue('installed', false)
702
		) {
703
			header('HTTP/1.1 400 Bad Request');
704
			header('Status: 400 Bad Request');
705
706
			$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
707
			$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...
708
			$tmpl->printPage();
709
710
			exit();
711
		}
712
		\OC::$server->getEventLogger()->end('boot');
713
	}
714
715
	private static function registerLocalAddressBook() {
716
		self::$server->getContactsManager()->register(function() {
717
			$userManager = \OC::$server->getUserManager();
718
			\OC::$server->getContactsManager()->registerAddressBook(
719
				new \OC\Contacts\LocalAddressBook($userManager));
720
		});
721
	}
722
723
	/**
724
	 * register hooks for the cache
725
	 */
726 125
	public static function registerCacheHooks() {
727
		//don't try to do this before we are properly setup
728
		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
729
730
			// NOTE: This will be replaced to use OCP
731
			$userSession = self::$server->getUserSession();
732 125
			$userSession->listen('\OC\User', 'postLogin', function () {
733
				try {
734 125
					$cache = new \OC\Cache\File();
735 125
					$cache->gc();
736 125
				} catch (\OC\ServerNotAvailableException $e) {
737
					// not a GC exception, pass it on
738
					throw $e;
739
				} catch (\Exception $e) {
740
					// a GC exception should not prevent users from using OC,
741
					// so log the exception
742
					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
743
				}
744 125
			});
745
		}
746
	}
747
748
	private static function registerEncryptionWrapper() {
749
		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OC\Encryption\Manager', 'setupStorage');
750
	}
751
752
	private static function registerEncryptionHooks() {
753
		$enabled = self::$server->getEncryptionManager()->isEnabled();
754
		if ($enabled) {
755
			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
756
			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
757
			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
758
			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
759
		}
760
	}
761
762
	/**
763
	 * register hooks for the cache
764
	 */
765
	public static function registerLogRotate() {
766
		$systemConfig = \OC::$server->getSystemConfig();
767
		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !\OCP\Util::needUpgrade()) {
768
			//don't try to do this before we are properly setup
769
			//use custom logfile path if defined, otherwise use default of owncloud.log in data directory
770
			\OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
771
		}
772
	}
773
774
	/**
775
	 * register hooks for the filesystem
776
	 */
777
	public static function registerFilesystemHooks() {
778
		// Check for blacklisted files
779
		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
780
		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
781
	}
782
783
	/**
784
	 * register hooks for previews
785
	 */
786
	public static function registerPreviewHooks() {
787
		OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
788
		OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
789
		OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
790
		OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
791
		OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
792
		OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete');
793
		OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
794
	}
795
796
	/**
797
	 * register hooks for sharing
798
	 */
799 73
	public static function registerShareHooks() {
800 73
		if (\OC::$server->getSystemConfig()->getValue('installed')) {
801 73
			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
802 73
			OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
803 73
			OC_Hook::connect('OC_Group', 'pre_addToGroup', 'OC\Share\Hooks', 'pre_addToGroup');
804 73
			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
805 73
			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
806 73
		}
807 73
	}
808
809
	protected static function registerAutoloaderCache() {
810
		// The class loader takes an optional low-latency cache, which MUST be
811
		// namespaced. The instanceid is used for namespacing, but might be
812
		// unavailable at this point. Futhermore, it might not be possible to
813
		// generate an instanceid via \OC_Util::getInstanceId() because the
814
		// config file may not be writable. As such, we only register a class
815
		// loader cache if instanceid is available without trying to create one.
816
		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
817
		if ($instanceId) {
818
			try {
819
				$memcacheFactory = \OC::$server->getMemCacheFactory();
820
				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...
821
			} catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
822
			}
823
		}
824
	}
825
826
	/**
827
	 * Handle the request
828
	 */
829
	public static function handleRequest() {
830
831
		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
832
		$systemConfig = \OC::$server->getSystemConfig();
833
		// load all the classpaths from the enabled apps so they are available
834
		// in the routing files of each app
835
		OC::loadAppClassPaths();
836
837
		// Check if ownCloud is installed or in maintenance (update) mode
838
		if (!$systemConfig->getValue('installed', false)) {
839
			\OC::$server->getSession()->clear();
840
			$setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'), new \OC_Defaults());
841
			$controller = new OC\Core\Setup\Controller($setupHelper);
842
			$controller->run($_POST);
843
			exit();
844
		}
845
846
		$request = \OC::$server->getRequest()->getPathInfo();
847
		if (substr($request, -3) !== '.js') { // we need these files during the upgrade
848
			self::checkMaintenanceMode();
849
			self::checkUpgrade();
850
		}
851
852
		// Always load authentication apps
853
		OC_App::loadApps(['authentication']);
854
855
		// Load minimum set of apps
856
		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...
857
			&& !$systemConfig->getValue('maintenance', false)
858
			&& !\OCP\Util::needUpgrade()) {
859
			// For logged-in users: Load everything
860
			if(OC_User::isLoggedIn()) {
861
				OC_App::loadApps();
862
			} else {
863
				// For guests: Load only filesystem and logging
864
				OC_App::loadApps(array('filesystem', 'logging'));
865
				\OC_User::tryBasicAuthLogin();
866
			}
867
		}
868
869
		if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
870
			try {
871
				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
872
					OC_App::loadApps(array('filesystem', 'logging'));
873
					OC_App::loadApps();
874
				}
875
				self::checkSingleUserMode();
876
				OC_Util::setupFS();
877
				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
878
				return;
879
			} 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...
880
				//header('HTTP/1.0 404 Not Found');
881
			} 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...
882
				OC_Response::setStatus(405);
883
				return;
884
			}
885
		}
886
887
		// Handle redirect URL for logged in users
888
		if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
889
			$location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
890
891
			// Deny the redirect if the URL contains a @
892
			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
893
			if (strpos($location, '@') === false) {
894
				header('Location: ' . $location);
895
				return;
896
			}
897
		}
898
		// Handle WebDAV
899
		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
900
			// not allowed any more to prevent people
901
			// mounting this root directly.
902
			// Users need to mount remote.php/webdav instead.
903
			header('HTTP/1.1 405 Method Not Allowed');
904
			header('Status: 405 Method Not Allowed');
905
			return;
906
		}
907
908
		// Redirect to index if the logout link is accessed without valid session
909
		// this is needed to prevent "Token expired" messages while login if a session is expired
910
		// @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
911
		if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
912
			header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
913
			return;
914
		}
915
916
		// Someone is logged in
917
		if (OC_User::isLoggedIn()) {
918
			OC_App::loadApps();
919
			OC_User::setupBackends();
920
			OC_Util::setupFS();
921
			if (isset($_GET["logout"]) and ($_GET["logout"])) {
922
				OC_JSON::callCheck();
923
				if (isset($_COOKIE['oc_token'])) {
924
					\OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
925
				}
926
				OC_User::logout();
927
				// redirect to webroot and add slash if webroot is empty
928
				header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
929
			} else {
930
				// Redirect to default application
931
				OC_Util::redirectToDefaultPage();
932
			}
933
		} else {
934
			// Not handled and not logged in
935
			self::handleLogin();
936
		}
937
	}
938
939
	protected static function handleAuthHeaders() {
940
		//copy http auth headers for apache+php-fcgid work around
941
		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
942
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
943
		}
944
945
		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
946
		$vars = array(
947
			'HTTP_AUTHORIZATION', // apache+php-cgi work around
948
			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
949
		);
950
		foreach ($vars as $var) {
951
			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
952
				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
953
				$_SERVER['PHP_AUTH_USER'] = $name;
954
				$_SERVER['PHP_AUTH_PW'] = $password;
955
				break;
956
			}
957
		}
958
	}
959
960
	protected static function handleLogin() {
961
		OC_App::loadApps(array('prelogin'));
962
		$error = array();
963
		$messages = [];
964
965
		try {
966
			// auth possible via apache module?
967
			if (OC::tryApacheAuth()) {
968
				$error[] = 'apacheauthfailed';
969
			} // remember was checked after last login
970
			elseif (OC::tryRememberLogin()) {
971
				$error[] = 'invalidcookie';
972
			} // logon via web form
973
			elseif (OC::tryFormLogin()) {
974
				$error[] = 'invalidpassword';
975
			}
976
		} catch (\OC\User\LoginException $e) {
977
			$messages[] = $e->getMessage();
978
		} catch (\Exception $ex) {
979
			\OCP\Util::logException('handleLogin', $ex);
980
			// do not disclose information. show generic error
981
			$error[] = 'internalexception';
982
		}
983
984
		OC_Util::displayLoginPage(array_unique($error), $messages);
985
	}
986
987
	/**
988
	 * Remove outdated and therefore invalid tokens for a user
989
	 * @param string $user
990
	 */
991
	protected static function cleanupLoginTokens($user) {
992
		$config = \OC::$server->getConfig();
993
		$cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
994
		$tokens = $config->getUserKeys($user, 'login_token');
995
		foreach ($tokens as $token) {
996
			$time = $config->getUserValue($user, 'login_token', $token);
997
			if ($time < $cutoff) {
998
				$config->deleteUserValue($user, 'login_token', $token);
999
			}
1000
		}
1001
	}
1002
1003
	/**
1004
	 * Try to login a user via HTTP authentication
1005
	 * @return bool|void
1006
	 */
1007
	protected static function tryApacheAuth() {
1008
		$return = OC_User::handleApacheAuth();
1009
1010
		// if return is true we are logged in -> redirect to the default page
1011
		if ($return === true) {
1012
			$_REQUEST['redirect_url'] = \OC::$server->getRequest()->getRequestUri();
1013
			OC_Util::redirectToDefaultPage();
1014
			exit;
1015
		}
1016
1017
		// in case $return is null apache based auth is not enabled
1018
		return is_null($return) ? false : true;
1019
	}
1020
1021
	/**
1022
	 * Try to login a user using the remember me cookie.
1023
	 * @return bool Whether the provided cookie was valid
1024
	 */
1025
	protected static function tryRememberLogin() {
1026
		if (!isset($_COOKIE["oc_remember_login"])
1027
			|| !isset($_COOKIE["oc_token"])
1028
			|| !isset($_COOKIE["oc_username"])
1029
			|| !$_COOKIE["oc_remember_login"]
1030
			|| !OC_Util::rememberLoginAllowed()
1031
		) {
1032
			return false;
1033
		}
1034
1035
		if (defined("DEBUG") && DEBUG) {
1036
			OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
1037
		}
1038
1039
		if(OC_User::userExists($_COOKIE['oc_username'])) {
1040
			self::cleanupLoginTokens($_COOKIE['oc_username']);
1041
			// verify whether the supplied "remember me" token was valid
1042
			$granted = OC_User::loginWithCookie(
1043
				$_COOKIE['oc_username'], $_COOKIE['oc_token']);
1044
			if($granted === true) {
1045
				OC_Util::redirectToDefaultPage();
1046
				// doesn't return
1047
			}
1048
			OC_Log::write('core', 'Authentication cookie rejected for user ' .
1049
				$_COOKIE['oc_username'], OC_Log::WARN);
1050
			// if you reach this point you have changed your password
1051
			// or you are an attacker
1052
			// we can not delete tokens here because users may reach
1053
			// this point multiple times after a password change
1054
		}
1055
1056
		OC_User::unsetMagicInCookie();
1057
		return true;
1058
	}
1059
1060
	/**
1061
	 * Tries to login a user using the form based authentication
1062
	 * @return bool|void
1063
	 */
1064
	protected static function tryFormLogin() {
1065
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
1066
			return false;
1067
		}
1068
1069
		if(!OC_Util::isCallRegistered()) {
1070
			return false;
1071
		}
1072
		OC_App::loadApps();
1073
1074
		//setup extra user backends
1075
		OC_User::setupBackends();
1076
1077
		if (OC_User::login((string)$_POST["user"], (string)$_POST["password"])) {
1078
			$userId = OC_User::getUser();
1079
1080
			// setting up the time zone
1081
			if (isset($_POST['timezone-offset'])) {
1082
				self::$server->getSession()->set('timezone', (string)$_POST['timezone-offset']);
1083
				self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string)$_POST['timezone']);
1084
			}
1085
1086
			self::cleanupLoginTokens($userId);
1087
			if (!empty($_POST["remember_login"])) {
1088
				if (defined("DEBUG") && DEBUG) {
1089
					self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
1090
				}
1091
				$token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
1092
				self::$server->getConfig()->setUserValue($userId, 'login_token', $token, time());
1093
				OC_User::setMagicInCookie($userId, $token);
1094
			} else {
1095
				OC_User::unsetMagicInCookie();
1096
			}
1097
			OC_Util::redirectToDefaultPage();
1098
			exit();
1099
		}
1100
		return true;
1101
	}
1102
}
1103
1104
if (!function_exists('get_temp_dir')) {
1105
	/**
1106
	 * Get the temporary dir to store uploaded data
1107
	 * @return null|string Path to the temporary directory or null
1108
	 */
1109
	function get_temp_dir() {
1110 12
		if ($temp = ini_get('upload_tmp_dir')) return $temp;
1111 12
		if ($temp = getenv('TMP')) return $temp;
1112 12
		if ($temp = getenv('TEMP')) return $temp;
1113 12
		if ($temp = getenv('TMPDIR')) return $temp;
1114 12
		$temp = tempnam(__FILE__, '');
1115 12
		if (file_exists($temp)) {
1116 12
			unlink($temp);
1117 12
			return dirname($temp);
1118
		}
1119
		if ($temp = sys_get_temp_dir()) return $temp;
1120
1121
		return null;
1122
	}
1123
}
1124
1125
OC::init();
1126