Completed
Push — stable7 ( 35746e...825360 )
by
unknown
29:41
created

base.php ➔ get_temp_dir()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 7
eloc 11
nc 7
nop 0
dl 0
loc 14
rs 8.2222
1
<?php
2
/**
3
 * ownCloud
4
 *
5
 * @author Frank Karlitschek
6
 * @copyright 2012 Frank Karlitschek [email protected]
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
10
 * License as published by the Free Software Foundation; either
11
 * version 3 of the License, or any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public
19
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
23
require_once 'public/constants.php';
24
25
/**
26
 * Class that is a namespace for all global OC variables
27
 * No, we can not put this class in its own file because it is used by
28
 * OC_autoload!
29
 */
30
class OC {
31
	/**
32
	 * Associative array for autoloading. classname => filename
33
	 */
34
	public static $CLASSPATH = array();
35
	/**
36
	 * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
37
	 */
38
	public static $SERVERROOT = '';
39
	/**
40
	 * the current request path relative to the owncloud root (e.g. files/index.php)
41
	 */
42
	private static $SUBURI = '';
43
	/**
44
	 * the owncloud root path for http requests (e.g. owncloud/)
45
	 */
46
	public static $WEBROOT = '';
47
	/**
48
	 * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
49
	 */
50
	public static $THIRDPARTYROOT = '';
51
	/**
52
	 * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
53
	 */
54
	public static $THIRDPARTYWEBROOT = '';
55
	/**
56
	 * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
57
	 * web path in 'url'
58
	 */
59
	public static $APPSROOTS = array();
60
61
	public static $configDir;
62
63
	/**
64
	 * requested app
65
	 */
66
	public static $REQUESTEDAPP = '';
67
68
	/**
69
	 * check if owncloud runs in cli mode
70
	 */
71
	public static $CLI = false;
72
73
	/**
74
	 * @var \OC\Session\Session
75
	 */
76
	public static $session = null;
77
78
	/**
79
	 * @var \OC\Autoloader $loader
80
	 */
81
	public static $loader = null;
82
83
	/**
84
	 * @var \OC\Server
85
	 */
86
	public static $server = null;
87
88
	public static function initPaths() {
89
		// calculate the root directories
90
		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
91
92
		// ensure we can find OC_Config
93
		set_include_path(
94
			OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
95
			get_include_path()
96
		);
97
98
		if(defined('PHPUNIT_CONFIG_DIR')) {
99
			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
100
		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
101
			self::$configDir = OC::$SERVERROOT . '/tests/config/';
102
		} else {
103
			self::$configDir = OC::$SERVERROOT . '/config/';
104
		}
105
		OC_Config::$object = new \OC\Config(self::$configDir);
106
107
		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
108
		$scriptName = OC_Request::scriptName();
109
		if (substr($scriptName, -1) == '/') {
110
			$scriptName .= 'index.php';
111
			//make sure suburi follows the same rules as scriptName
112
			if (substr(OC::$SUBURI, -9) != 'index.php') {
113
				if (substr(OC::$SUBURI, -1) != '/') {
114
					OC::$SUBURI = OC::$SUBURI . '/';
115
				}
116
				OC::$SUBURI = OC::$SUBURI . 'index.php';
117
			}
118
		}
119
120
		if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
121
			OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
122
123
			if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
124
				OC::$WEBROOT = '/' . OC::$WEBROOT;
125
			}
126
		} else {
127
			// The scriptName is not ending with OC::$SUBURI
128
			// This most likely means that we are calling from CLI.
129
			// However some cron jobs still need to generate
130
			// a web URL, so we use overwritewebroot as a fallback.
131
			OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
132
		}
133
134
		// search the 3rdparty folder
135
		if (OC_Config::getValue('3rdpartyroot', '') <> '' and OC_Config::getValue('3rdpartyurl', '') <> '') {
136
			OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', '');
137
			OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', '');
138
		} elseif (file_exists(OC::$SERVERROOT . '/3rdparty')) {
139
			OC::$THIRDPARTYROOT = OC::$SERVERROOT;
140
			OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
141
		} elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
142
			OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
143
			OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
144
		} else {
145
			throw new Exception('3rdparty directory not found! Please put the ownCloud 3rdparty'
146
				. ' folder in the ownCloud folder or the folder above.'
147
				. ' You can also configure the location in the config.php file.');
148
		}
149
		// search the apps folder
150
		$config_paths = OC_Config::getValue('apps_paths', array());
151
		if (!empty($config_paths)) {
152
			foreach ($config_paths as $paths) {
153
				if (isset($paths['url']) && isset($paths['path'])) {
154
					$paths['url'] = rtrim($paths['url'], '/');
155
					$paths['path'] = rtrim($paths['path'], '/');
156
					OC::$APPSROOTS[] = $paths;
157
				}
158
			}
159
		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
160
			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
161
		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
162
			OC::$APPSROOTS[] = array(
163
				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
164
				'url' => '/apps',
165
				'writable' => true
166
			);
167
		}
168
169
		if (empty(OC::$APPSROOTS)) {
170
			throw new Exception('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
171
				. ' or the folder above. You can also configure the location in the config.php file.');
172
		}
173
		$paths = array();
174
		foreach (OC::$APPSROOTS as $path) {
175
			$paths[] = $path['path'];
176
		}
177
178
		// set the right include path
179
		set_include_path(
180
			OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
181
			OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
182
			OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
183
			implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
184
			get_include_path() . PATH_SEPARATOR .
185
			OC::$SERVERROOT
186
		);
187
	}
188
189
	public static function checkConfig() {
190
		$l = OC_L10N::get('lib');
191
192
		// Create config in case it does not already exists
193
		$configFilePath = self::$configDir .'/config.php';
194
		if(!file_exists($configFilePath)) {
195
			@touch($configFilePath);
196
		}
197
198
		// Check if config is writable
199
		$configFileWritable = is_writable($configFilePath);
200
		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
201
			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
202
			if (self::$CLI) {
203
				echo $l->t('Cannot write into "config" directory!')."\n";
204
				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
205
				echo "\n";
206
				echo $l->t('See %s', array(\OC_Helper::linkToDocs('admin-dir_permissions')))."\n";
207
				exit;
208
			} else {
209
				OC_Template::printErrorPage(
210
					$l->t('Cannot write into "config" directory!'),
211
					$l->t('This can usually be fixed by '
212
					. '%sgiving the webserver write access to the config directory%s.',
213
					 array('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>'))
214
				);
215
			}
216
		}
217
	}
218
219
	public static function checkInstalled() {
220
		// Redirect to installer if not installed
221
		if (!OC_Config::getValue('installed', false) && OC::$SUBURI != '/index.php') {
222
			if (!OC::$CLI) {
223
				$url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
224
				header("Location: $url");
225
			}
226
			exit();
227
		}
228
	}
229
230
	public static function checkSSL() {
231
		// redirect to https site if configured
232
		if (OC_Config::getValue("forcessl", false)) {
233
			header('Strict-Transport-Security: max-age=31536000');
234
			ini_set("session.cookie_secure", "on");
235
			if (OC_Request::serverProtocol() <> 'https' and !OC::$CLI) {
236
				$url = "https://" . OC_Request::serverHost() . OC_Request::requestUri();
237
				header("Location: $url");
238
				exit();
239
			}
240
		} else {
241
			// Invalidate HSTS headers
242
			if (OC_Request::serverProtocol() === 'https') {
243
				header('Strict-Transport-Security: max-age=0');
244
			}
245
		}
246
	}
247
248
	public static function checkMaintenanceMode() {
249
		// Allow ajax update script to execute without being stopped
250
		if (OC_Config::getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
251
			// send http status 503
252
			header('HTTP/1.1 503 Service Temporarily Unavailable');
253
			header('Status: 503 Service Temporarily Unavailable');
254
			header('Retry-After: 120');
255
256
			// render error page
257
			$template = new OC_Template('', 'update.user', 'guest');
258
			$template->printPage();
259
			die();
260
		}
261
	}
262
263
	public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
264
		if (!\OCP\Config::getSystemValue('singleuser', false)) {
265
			return;
266
		}
267
		$user = OC_User::getUserSession()->getUser();
268
		if ($user) {
269
			$group = \OC::$server->getGroupManager()->get('admin');
270
			if ($group->inGroup($user)) {
271
				return;
272
			}
273
		} else {
274
			if(!$lockIfNoUserLoggedIn) {
275
				return;
276
			}
277
		}
278
		// send http status 503
279
		header('HTTP/1.1 503 Service Temporarily Unavailable');
280
		header('Status: 503 Service Temporarily Unavailable');
281
		header('Retry-After: 120');
282
283
		// render error page
284
		$template = new OC_Template('', 'singleuser.user', 'guest');
285
		$template->printPage();
286
		die();
287
	}
288
289
	/**
290
	 * check if the instance needs to preform an upgrade
291
	 *
292
	 * @return bool
293
	 * @deprecated use \OCP\Util::needUpgrade instead
294
	 */
295
	public static function needUpgrade() {
296
		return \OCP\Util::needUpgrade();
297
	}
298
299
	/**
300
	 * Checks if the version requires an update and shows
301
	 * @param bool $showTemplate Whether an update screen should get shown
302
	 * @return bool|void
303
	 */
304
	public static function checkUpgrade($showTemplate = true) {
305
		if (\OCP\Util::needUpgrade()) {
306
			if ($showTemplate && !OC_Config::getValue('maintenance', false)) {
307
				$version = OC_Util::getVersion();
308
				$oldTheme = OC_Config::getValue('theme');
309
				OC_Config::setValue('theme', '');
310
				OC_Util::addScript('config'); // needed for web root
311
				OC_Util::addScript('update');
312
				$tmpl = new OC_Template('', 'update.admin', 'guest');
313
				$tmpl->assign('version', OC_Util::getVersionString());
314
315
				// get third party apps
316
				$apps = OC_App::getEnabledApps();
317
				$incompatibleApps = array();
318
				foreach ($apps as $appId) {
319
					$info = OC_App::getAppInfo($appId);
320
					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 319 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...
321
						$incompatibleApps[] = $info;
322
					}
323
				}
324
				$tmpl->assign('appList', $incompatibleApps);
325
				$tmpl->assign('productName', 'ownCloud'); // for now
326
				$tmpl->assign('oldTheme', $oldTheme);
327
				$tmpl->printPage();
328
				exit();
329
			} else {
330
				return true;
331
			}
332
		}
333
		return false;
334
	}
335
336
	public static function initTemplateEngine() {
337
		// Add the stuff we need always
338
		// TODO: read from core/js/core.json
339
		OC_Util::addScript("jquery-1.10.0.min");
340
		OC_Util::addScript("jquery-migrate-1.2.1.min");
341
		OC_Util::addScript("jquery-ui-1.10.0.custom");
342
		OC_Util::addScript("jquery-showpassword");
343
		OC_Util::addScript("placeholders");
344
		OC_Util::addScript("jquery-tipsy");
345
		OC_Util::addScript("compatibility");
346
		OC_Util::addScript("underscore");
347
		OC_Util::addScript("jquery.ocdialog");
348
		OC_Util::addScript("oc-dialogs");
349
		OC_Util::addScript("js");
350
		OC_Util::addScript("octemplate");
351
		OC_Util::addScript("eventsource");
352
		OC_Util::addScript("config");
353
		//OC_Util::addScript( "multiselect" );
354
		OC_Util::addScript('search', 'result');
355
		OC_Util::addScript("oc-requesttoken");
356
		OC_Util::addScript("apps");
357
		OC_Util::addScript("snap");
358
359
		// avatars
360
		if (\OC_Config::getValue('enable_avatars', true) === true) {
361
			\OC_Util::addScript('placeholder');
362
			\OC_Util::addScript('3rdparty', 'md5/md5.min');
363
			\OC_Util::addScript('jquery.avatar');
364
			\OC_Util::addScript('avatar');
365
		}
366
367
		OC_Util::addStyle("styles");
368
		OC_Util::addStyle("header");
369
		OC_Util::addStyle("mobile");
370
		OC_Util::addStyle("icons");
371
		OC_Util::addStyle("fonts");
372
		OC_Util::addStyle("apps");
373
		OC_Util::addStyle("fixes");
374
		OC_Util::addStyle("multiselect");
375
		OC_Util::addStyle("jquery-ui-1.10.0.custom");
376
		OC_Util::addStyle("jquery-tipsy");
377
		OC_Util::addStyle("jquery.ocdialog");
378
	}
379
380
	public static function initSession() {
381
		// prevents javascript from accessing php session cookies
382
		ini_set('session.cookie_httponly', '1;');
383
384
		// set the cookie path to the ownCloud directory
385
		$cookie_path = OC::$WEBROOT ? : '/';
386
		ini_set('session.cookie_path', $cookie_path);
387
388
		//set the session object to a dummy session so code relying on the session existing still works
389
		self::$session = new \OC\Session\Memory('');
390
391
		// Let the session name be changed in the initSession Hook
392
		$sessionName = OC_Util::getInstanceId();
393
394
		try {
395
			// Allow session apps to create a custom session object
396
			$useCustomSession = false;
397
			OC_Hook::emit('OC', 'initSession', array('session' => &self::$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
398
			if(!$useCustomSession) {
399
				// set the session name to the instance id - which is unique
400
				self::$session = new \OC\Session\Internal($sessionName);
401
			}
402
			// if session cant be started break with http 500 error
403
		} catch (Exception $e) {
404
			//show the user a detailed error page
405
			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
406
			OC_Template::printExceptionErrorPage($e);
407
		}
408
409
		$sessionLifeTime = self::getSessionLifeTime();
410
		// regenerate session id periodically to avoid session fixation
411
		if (!self::$session->exists('SID_CREATED')) {
412
			self::$session->set('SID_CREATED', time());
413
		} else if (time() - self::$session->get('SID_CREATED') > $sessionLifeTime / 2) {
414
			session_regenerate_id(true);
415
			self::$session->set('SID_CREATED', time());
416
		}
417
418
		// session timeout
419
		if (self::$session->exists('LAST_ACTIVITY') && (time() - self::$session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
420
			if (isset($_COOKIE[session_name()])) {
421
				setcookie(session_name(), '', time() - 42000, $cookie_path);
422
			}
423
			session_unset();
424
			session_destroy();
425
			session_start();
426
		}
427
428
		self::$session->set('LAST_ACTIVITY', time());
429
	}
430
431
	/**
432
	 * @return string
433
	 */
434
	private static function getSessionLifeTime() {
435
		return OC_Config::getValue('session_lifetime', 60 * 60 * 24);
436
	}
437
438
	public static function loadAppClassPaths() {
439
		foreach (OC_APP::getEnabledApps() as $app) {
440
			$file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
441
			if (file_exists($file)) {
442
				require_once $file;
443
			}
444
		}
445
	}
446
447
448
	public static function init() {
449
		// register autoloader
450
		require_once __DIR__ . '/autoloader.php';
451
		self::$loader = new \OC\Autoloader();
452
		self::$loader->registerPrefix('Doctrine\\Common', 'doctrine/common/lib');
453
		self::$loader->registerPrefix('Doctrine\\DBAL', 'doctrine/dbal/lib');
454
		self::$loader->registerPrefix('Symfony\\Component\\Routing', 'symfony/routing');
455
		self::$loader->registerPrefix('Symfony\\Component\\Console', 'symfony/console');
456
		self::$loader->registerPrefix('Patchwork', '3rdparty');
457
		self::$loader->registerPrefix('Pimple', '3rdparty/Pimple');
458
		spl_autoload_register(array(self::$loader, 'load'));
459
460
		// make a dummy session available as early as possible since error pages need it
461
		self::$session = new \OC\Session\Memory('');
462
463
		// set some stuff
464
		//ob_start();
465
		error_reporting(E_ALL | E_STRICT);
466
		if (defined('DEBUG') && DEBUG) {
467
			ini_set('display_errors', 1);
468
		}
469
		self::$CLI = (php_sapi_name() == 'cli');
470
471
		date_default_timezone_set('UTC');
472
		ini_set('arg_separator.output', '&amp;');
473
474
		// try to switch magic quotes off.
475
		if (get_magic_quotes_gpc() == 1) {
476
			ini_set('magic_quotes_runtime', 0);
477
		}
478
479
		//try to configure php to enable big file uploads.
480
		//this doesn´t work always depending on the webserver and php configuration.
481
		//Let´s try to overwrite some defaults anyways
482
483
		//try to set the maximum execution time to 60min
484
		@set_time_limit(3600);
485
		@ini_set('max_execution_time', 3600);
486
		@ini_set('max_input_time', 3600);
487
488
		//try to set the maximum filesize to 10G
489
		@ini_set('upload_max_filesize', '10G');
490
		@ini_set('post_max_size', '10G');
491
		@ini_set('file_uploads', '50');
492
493
		self::handleAuthHeaders();
494
		self::initPaths();
495
		self::registerAutoloaderCache();
496
497
		OC_Util::isSetLocaleWorking();
498
499
		// setup 3rdparty autoloader
500
		$vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
501
		if (file_exists($vendorAutoLoad)) {
502
			require_once $vendorAutoLoad;
503
		}
504
505
		if (!defined('PHPUNIT_RUN')) {
506
			OC\Log\ErrorHandler::setLogger(OC_Log::$object);
507
			if (defined('DEBUG') and DEBUG) {
508
				OC\Log\ErrorHandler::register(true);
509
				set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
510
			} else {
511
				OC\Log\ErrorHandler::register();
512
			}
513
		}
514
515
		// register the stream wrappers
516
		stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
517
		stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
518
		stream_wrapper_register('close', 'OC\Files\Stream\Close');
519
		stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
520
		stream_wrapper_register('oc', 'OC\Files\Stream\OC');
521
522
		// setup the basic server
523
		self::$server = new \OC\Server();
524
525
		self::initTemplateEngine();
526
		OC_App::loadApps(array('session'));
527
		if (!self::$CLI) {
528
			self::initSession();
529
		} else {
530
			self::$session = new \OC\Session\Memory('');
531
		}
532
		self::checkConfig();
533
		self::checkInstalled();
534
		self::checkSSL();
535
		OC_Response::addSecurityHeaders();
536
537
		$errors = OC_Util::checkServer(\OC::$server->getConfig());
538
		if (count($errors) > 0) {
539
			if (self::$CLI) {
540
				foreach ($errors as $error) {
541
					echo $error['error'] . "\n";
542
					echo $error['hint'] . "\n\n";
543
				}
544
			} else {
545
				OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
546
				OC_Template::printGuestPage('', 'error', array('errors' => $errors));
547
			}
548
			exit;
549
		}
550
551
		//try to set the session lifetime
552
		$sessionLifeTime = self::getSessionLifeTime();
553
		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
554
555
		// User and Groups
556
		if (!OC_Config::getValue("installed", false)) {
557
			self::$session->set('user_id', '');
558
		}
559
560
		OC_User::useBackend(new OC_User_Database());
561
		OC_Group::useBackend(new OC_Group_Database());
562
563
		//setup extra user backends
564
		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...
565
			OC_User::setupBackends();
566
		}
567
568
		self::registerCacheHooks();
569
		self::registerFilesystemHooks();
570
		self::registerPreviewHooks();
571
		self::registerShareHooks();
572
		self::registerLogRotate();
573
		self::registerLocalAddressBook();
574
575
		//make sure temporary files are cleaned up
576
		$tmpManager = \OC::$server->getTempManager();
577
		register_shutdown_function(array($tmpManager, 'clean'));
578
579
		if (OC_Config::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...
580
			if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
581
				OC_Util::addScript('backgroundjobs');
582
			}
583
		}
584
585
		$host = OC_Request::insecureServerHost();
586
		// if the host passed in headers isn't trusted
587
		if (!OC::$CLI
588
			// overwritehost is always trusted
589
			&& OC_Request::getOverwriteHost() === null
590
			&& !OC_Request::isTrustedDomain($host)
591
		) {
592
			header('HTTP/1.1 400 Bad Request');
593
			header('Status: 400 Bad Request');
594
595
			$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
596
			$tmpl->assign('domain', $_SERVER['SERVER_NAME']);
597
			$tmpl->printPage();
598
599
			exit();
600
		}
601
	}
602
603
	private static function registerLocalAddressBook() {
604
		self::$server->getContactsManager()->register(function() {
605
			$userManager = \OC::$server->getUserManager();
606
			\OC::$server->getContactsManager()->registerAddressBook(
607
				new \OC\Contacts\LocalAddressBook($userManager));
608
		});
609
	}
610
611
	/**
612
	 * register hooks for the cache
613
	 */
614
	public static function registerCacheHooks() {
615
		if (OC_Config::getValue('installed', false) && !\OCP\Util::needUpgrade()) { //don't try to do this before we are properly setup
616
			\OCP\BackgroundJob::registerJob('OC\Cache\FileGlobalGC');
617
618
			// NOTE: This will be replaced to use OCP
619
			$userSession = \OC_User::getUserSession();
620
			$userSession->listen('postLogin', '\OC\Cache\File', 'loginListener');
621
		}
622
	}
623
624
	/**
625
	 * register hooks for the cache
626
	 */
627
	public static function registerLogRotate() {
628
		if (OC_Config::getValue('installed', false) && OC_Config::getValue('log_rotate_size', false) && !\OCP\Util::needUpgrade()) {
629
			//don't try to do this before we are properly setup
630
			//use custom logfile path if defined, otherwise use default of owncloud.log in data directory
631
			\OCP\BackgroundJob::registerJob('OC\Log\Rotate', OC_Config::getValue('logfile', OC_Config::getValue("datadirectory", OC::$SERVERROOT . '/data') . '/owncloud.log'));
632
		}
633
	}
634
635
	/**
636
	 * register hooks for the filesystem
637
	 */
638
	public static function registerFilesystemHooks() {
639
		// Check for blacklisted files
640
		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
641
		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
642
	}
643
644
	/**
645
	 * register hooks for previews
646
	 */
647
	public static function registerPreviewHooks() {
648
		OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
649
		OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
650
		OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
651
		OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
652
		OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
653
		OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete');
654
		OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
655
	}
656
657
	/**
658
	 * register hooks for sharing
659
	 */
660
	public static function registerShareHooks() {
661
		if (\OC_Config::getValue('installed')) {
662
			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
663
			OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
664
			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
665
			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
666
		}
667
	}
668
669
	protected static function registerAutoloaderCache() {
670
		// The class loader takes an optional low-latency cache, which MUST be
671
		// namespaced. The instanceid is used for namespacing, but might be
672
		// unavailable at this point. Futhermore, it might not be possible to
673
		// generate an instanceid via \OC_Util::getInstanceId() because the
674
		// config file may not be writable. As such, we only register a class
675
		// loader cache if instanceid is available without trying to create one.
676
		$instanceId = OC_Config::getValue('instanceid', null);
677
		if ($instanceId) {
678
			try {
679
				$memcacheFactory = new \OC\Memcache\Factory($instanceId);
680
				self::$loader->setMemoryCache($memcacheFactory->createLowLatency('Autoloader'));
681
			} catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
682
			}
683
		}
684
	}
685
686
	/**
687
	 * Handle the request
688
	 */
689
	public static function handleRequest() {
690
		$l = \OC_L10N::get('lib');
0 ignored issues
show
Unused Code introduced by
$l is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
691
		// load all the classpaths from the enabled apps so they are available
692
		// in the routing files of each app
693
		OC::loadAppClassPaths();
694
695
		// Check if ownCloud is installed or in maintenance (update) mode
696
		if (!OC_Config::getValue('installed', false)) {
697
			$controller = new OC\Core\Setup\Controller(\OC::$server->getConfig());
698
			$controller->run($_POST);
699
			exit();
700
		}
701
702
		$request = OC_Request::getPathInfo();
703
		if (substr($request, -3) !== '.js') { // we need these files during the upgrade
704
			self::checkMaintenanceMode();
705
			self::checkUpgrade();
706
		}
707
708
		if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
709
			try {
710
				if (!OC_Config::getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
711
					OC_App::loadApps(array('authentication'));
712
					OC_App::loadApps(array('filesystem', 'logging'));
713
					OC_App::loadApps();
714
				}
715
				self::checkSingleUserMode();
716
				OC_Util::setupFS();
717
				OC::$server->getRouter()->match(OC_Request::getRawPathInfo());
718
				return;
719
			} 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...
720
				//header('HTTP/1.0 404 Not Found');
721
			} 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...
722
				OC_Response::setStatus(405);
723
				return;
724
			}
725
		}
726
727
		// Load minimum set of apps
728
		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...
729
			// For logged-in users: Load everything
730
			if(OC_User::isLoggedIn()) {
731
				OC_App::loadApps();
732
			} else {
733
				// For guests: Load only authentication, filesystem and logging
734
				OC_App::loadApps(array('authentication'));
735
				OC_App::loadApps(array('filesystem', 'logging'));
736
			}
737
		}
738
739
		// Handle redirect URL for logged in users
740
		if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
741
			$location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
742
743
			// Deny the redirect if the URL contains a @
744
			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
745
			if (strpos($location, '@') === false) {
746
				header('Location: ' . $location);
747
				return;
748
			}
749
		}
750
		// Handle WebDAV
751
		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
752
			// not allowed any more to prevent people
753
			// mounting this root directly.
754
			// Users need to mount remote.php/webdav instead.
755
			header('HTTP/1.1 405 Method Not Allowed');
756
			header('Status: 405 Method Not Allowed');
757
			return;
758
		}
759
760
		// Redirect to index if the logout link is accessed without valid session
761
		// this is needed to prevent "Token expired" messages while login if a session is expired
762
		// @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
763
		if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \OC_User::isLoggedIn() of type boolean|null 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...
764
			header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
765
			return;
766
		}
767
768
		// Someone is logged in
769
		if (OC_User::isLoggedIn()) {
770
			OC_App::loadApps();
771
			OC_User::setupBackends();
772
			OC_Util::setupFS();
773
			if (isset($_GET["logout"]) and ($_GET["logout"])) {
774
				OC_JSON::callCheck();
775
				if (isset($_COOKIE['oc_token'])) {
776
					OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
777
				}
778
				OC_User::logout();
779
				// redirect to webroot and add slash if webroot is empty
780
				header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
781
			} else {
782
				// Redirect to default application
783
				OC_Util::redirectToDefaultPage();
784
			}
785
		} else {
786
			// Not handled and not logged in
787
			self::handleLogin();
788
		}
789
	}
790
791
	/**
792
	 * Load a PHP file belonging to the specified application
793
	 * @param array $param The application and file to load
794
	 * @return bool Whether the file has been found (will return 404 and false if not)
795
	 * @deprecated This function will be removed in ownCloud 8 - use proper routing instead
796
	 * @param $param
797
	 * @return bool Whether the file has been found (will return 404 and false if not)
798
	 */
799
	public static function loadAppScriptFile($param) {
800
		OC_App::loadApps();
801
		$app = $param['app'];
802
		$file = $param['file'];
803
		$app_path = OC_App::getAppPath($app);
804
		$file = $app_path . '/' . $file;
805
806
		if (OC_App::isEnabled($app) && $app_path !== false && OC_Helper::issubdirectory($file, $app_path)) {
807
			unset($app, $app_path);
808
			if (file_exists($file)) {
809
				require_once $file;
810
				return true;
811
			}
812
		}
813
		header('HTTP/1.0 404 Not Found');
814
		return false;
815
	}
816
817
	protected static function handleAuthHeaders() {
818
		//copy http auth headers for apache+php-fcgid work around
819
		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
820
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
821
		}
822
823
		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
824
		$vars = array(
825
			'HTTP_AUTHORIZATION', // apache+php-cgi work around
826
			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
827
		);
828
		foreach ($vars as $var) {
829
			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
830
				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
831
				$_SERVER['PHP_AUTH_USER'] = $name;
832
				$_SERVER['PHP_AUTH_PW'] = $password;
833
				break;
834
			}
835
		}
836
	}
837
838
	protected static function handleLogin() {
839
		OC_App::loadApps(array('prelogin'));
840
		$error = array();
841
842
		try {
843
			// auth possible via apache module?
844
			if (OC::tryApacheAuth()) {
845
				$error[] = 'apacheauthfailed';
846
			} // remember was checked after last login
847
			elseif (OC::tryRememberLogin()) {
848
				$error[] = 'invalidcookie';
849
			} // logon via web form
850
			elseif (OC::tryFormLogin()) {
851
				$error[] = 'invalidpassword';
852
			}
853
		} catch (\Exception $ex) {
854
			\OCP\Util::logException('handleLogin', $ex);
855
			// do not disclose information. show generic error
856
			$error[] = 'internalexception';
857
		}
858
859
		OC_Util::displayLoginPage(array_unique($error));
860
	}
861
862
	/**
863
	 * Remove outdated and therefore invalid tokens for a user
864
	 * @param string $user
865
	 */
866
	protected static function cleanupLoginTokens($user) {
867
		$cutoff = time() - OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
868
		$tokens = OC_Preferences::getKeys($user, 'login_token');
869
		foreach ($tokens as $token) {
870
			$time = OC_Preferences::getValue($user, 'login_token', $token);
871
			if ($time < $cutoff) {
872
				OC_Preferences::deleteKey($user, 'login_token', $token);
873
			}
874
		}
875
	}
876
877
	/**
878
	 * Try to login a user via HTTP authentication
879
	 * @return bool|void
880
	 */
881
	protected static function tryApacheAuth() {
882
		$return = OC_User::handleApacheAuth();
883
884
		// if return is true we are logged in -> redirect to the default page
885
		if ($return === true) {
886
			$_REQUEST['redirect_url'] = \OC_Request::requestUri();
887
			OC_Util::redirectToDefaultPage();
888
			exit;
889
		}
890
891
		// in case $return is null apache based auth is not enabled
892
		return is_null($return) ? false : true;
893
	}
894
895
	/**
896
	 * Try to login a user using the remember me cookie.
897
	 * @return bool Whether the provided cookie was valid
898
	 */
899
	protected static function tryRememberLogin() {
900
		if (!isset($_COOKIE["oc_remember_login"])
901
			|| !isset($_COOKIE["oc_token"])
902
			|| !isset($_COOKIE["oc_username"])
903
			|| !$_COOKIE["oc_remember_login"]
904
			|| !OC_Util::rememberLoginAllowed()
905
		) {
906
			return false;
907
		}
908
909
		if (defined("DEBUG") && DEBUG) {
910
			OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
911
		}
912
913
		if(OC_User::userExists($_COOKIE['oc_username'])) {
914
			self::cleanupLoginTokens($_COOKIE['oc_username']);
915
			// verify whether the supplied "remember me" token was valid
916
			$granted = OC_User::loginWithCookie(
917
				$_COOKIE['oc_username'], $_COOKIE['oc_token']);
918
			if($granted === true) {
919
				OC_Util::redirectToDefaultPage();
920
				// doesn't return
921
			}
922
			OC_Log::write('core', 'Authentication cookie rejected for user ' .
923
				$_COOKIE['oc_username'], OC_Log::WARN);
924
			// if you reach this point you have changed your password
925
			// or you are an attacker
926
			// we can not delete tokens here because users may reach
927
			// this point multiple times after a password change
928
		}
929
930
		OC_User::unsetMagicInCookie();
931
		return true;
932
	}
933
934
	/**
935
	 * Tries to login a user using the formbased authentication
936
	 * @return bool|void
937
	 */
938
	protected static function tryFormLogin() {
939
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
940
			return false;
941
		}
942
943
		if(!OC_Util::isCallRegistered()) {
944
			return false;
945
		}
946
		OC_App::loadApps();
947
948
		//setup extra user backends
949
		OC_User::setupBackends();
950
951
		if (OC_User::login($_POST["user"], $_POST["password"])) {
952
			// setting up the time zone
953
			if (isset($_POST['timezone-offset'])) {
954
				self::$session->set('timezone', $_POST['timezone-offset']);
955
			}
956
957
			$userid = OC_User::getUser();
958
			self::cleanupLoginTokens($userid);
959
			if (!empty($_POST["remember_login"])) {
960
				if (defined("DEBUG") && DEBUG) {
961
					OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
962
				}
963
				$token = OC_Util::generateRandomBytes(32);
964
				OC_Preferences::setValue($userid, 'login_token', $token, time());
965
				OC_User::setMagicInCookie($userid, $token);
966
			} else {
967
				OC_User::unsetMagicInCookie();
968
			}
969
			OC_Util::redirectToDefaultPage();
970
			exit();
971
		}
972
		return true;
973
	}
974
975
976
}
977
978
if (!function_exists('get_temp_dir')) {
979
	/**
980
	 * Get the temporary dir to store uploaded data
981
	 * @return null|string Path to the temporary directory or null
982
	 */
983
	function get_temp_dir() {
984
		if ($temp = ini_get('upload_tmp_dir')) return $temp;
985
		if ($temp = getenv('TMP')) return $temp;
986
		if ($temp = getenv('TEMP')) return $temp;
987
		if ($temp = getenv('TMPDIR')) return $temp;
988
		$temp = tempnam(__FILE__, '');
989
		if (file_exists($temp)) {
990
			unlink($temp);
991
			return dirname($temp);
992
		}
993
		if ($temp = sys_get_temp_dir()) return $temp;
994
995
		return null;
996
	}
997
}
998
999
OC::init();
1000