Completed
Pull Request — master (#9293)
by Blizzz
18:49
created
lib/base.php 1 patch
Indentation   +992 added lines, -992 removed lines patch added patch discarded remove patch
@@ -68,998 +68,998 @@
 block discarded – undo
68 68
  * OC_autoload!
69 69
  */
70 70
 class OC {
71
-	/**
72
-	 * Associative array for autoloading. classname => filename
73
-	 */
74
-	public static $CLASSPATH = array();
75
-	/**
76
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
-	 */
78
-	public static $SERVERROOT = '';
79
-	/**
80
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
-	 */
82
-	private static $SUBURI = '';
83
-	/**
84
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
85
-	 */
86
-	public static $WEBROOT = '';
87
-	/**
88
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
-	 * web path in 'url'
90
-	 */
91
-	public static $APPSROOTS = array();
92
-
93
-	/**
94
-	 * @var string
95
-	 */
96
-	public static $configDir;
97
-
98
-	/**
99
-	 * requested app
100
-	 */
101
-	public static $REQUESTEDAPP = '';
102
-
103
-	/**
104
-	 * check if Nextcloud runs in cli mode
105
-	 */
106
-	public static $CLI = false;
107
-
108
-	/**
109
-	 * @var \OC\Autoloader $loader
110
-	 */
111
-	public static $loader = null;
112
-
113
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
-	public static $composerAutoloader = null;
115
-
116
-	/**
117
-	 * @var \OC\Server
118
-	 */
119
-	public static $server = null;
120
-
121
-	/**
122
-	 * @var \OC\Config
123
-	 */
124
-	private static $config = null;
125
-
126
-	/**
127
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
128
-	 * the app path list is empty or contains an invalid path
129
-	 */
130
-	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
137
-		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
139
-		}
140
-		self::$config = new \OC\Config(self::$configDir);
141
-
142
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
-		/**
144
-		 * FIXME: The following lines are required because we can't yet instantiate
145
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
-		 */
147
-		$params = [
148
-			'server' => [
149
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
-			],
152
-		];
153
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
-		$scriptName = $fakeRequest->getScriptName();
155
-		if (substr($scriptName, -1) == '/') {
156
-			$scriptName .= 'index.php';
157
-			//make sure suburi follows the same rules as scriptName
158
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
159
-				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
161
-				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
163
-			}
164
-		}
165
-
166
-
167
-		if (OC::$CLI) {
168
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
-		} else {
170
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
-
173
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
175
-				}
176
-			} else {
177
-				// The scriptName is not ending with OC::$SUBURI
178
-				// This most likely means that we are calling from CLI.
179
-				// However some cron jobs still need to generate
180
-				// a web URL, so we use overwritewebroot as a fallback.
181
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
-			}
183
-
184
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
-			// slash which is required by URL generation.
186
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
-				header('Location: '.\OC::$WEBROOT.'/');
189
-				exit();
190
-			}
191
-		}
192
-
193
-		// search the apps folder
194
-		$config_paths = self::$config->getValue('apps_paths', array());
195
-		if (!empty($config_paths)) {
196
-			foreach ($config_paths as $paths) {
197
-				if (isset($paths['url']) && isset($paths['path'])) {
198
-					$paths['url'] = rtrim($paths['url'], '/');
199
-					$paths['path'] = rtrim($paths['path'], '/');
200
-					OC::$APPSROOTS[] = $paths;
201
-				}
202
-			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
-			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
-				'url' => '/apps',
209
-				'writable' => true
210
-			);
211
-		}
212
-
213
-		if (empty(OC::$APPSROOTS)) {
214
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
-				. ' or the folder above. You can also configure the location in the config.php file.');
216
-		}
217
-		$paths = array();
218
-		foreach (OC::$APPSROOTS as $path) {
219
-			$paths[] = $path['path'];
220
-			if (!is_dir($path['path'])) {
221
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
223
-					. ' config.php file.', $path['path']));
224
-			}
225
-		}
226
-
227
-		// set the right include path
228
-		set_include_path(
229
-			implode(PATH_SEPARATOR, $paths)
230
-		);
231
-	}
232
-
233
-	public static function checkConfig() {
234
-		$l = \OC::$server->getL10N('lib');
235
-
236
-		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
239
-			@touch($configFilePath);
240
-		}
241
-
242
-		// Check if config is writable
243
-		$configFileWritable = is_writable($configFilePath);
244
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
246
-
247
-			$urlGenerator = \OC::$server->getURLGenerator();
248
-
249
-			if (self::$CLI) {
250
-				echo $l->t('Cannot write into "config" directory!')."\n";
251
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
-				echo "\n";
253
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
254
-				exit;
255
-			} else {
256
-				OC_Template::printErrorPage(
257
-					$l->t('Cannot write into "config" directory!'),
258
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
259
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
260
-				);
261
-			}
262
-		}
263
-	}
264
-
265
-	public static function checkInstalled() {
266
-		if (defined('OC_CONSOLE')) {
267
-			return;
268
-		}
269
-		// Redirect to installer if not installed
270
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
271
-			if (OC::$CLI) {
272
-				throw new Exception('Not installed');
273
-			} else {
274
-				$url = OC::$WEBROOT . '/index.php';
275
-				header('Location: ' . $url);
276
-			}
277
-			exit();
278
-		}
279
-	}
280
-
281
-	public static function checkMaintenanceMode() {
282
-		// Allow ajax update script to execute without being stopped
283
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
284
-			// send http status 503
285
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
286
-			header('Status: 503 Service Temporarily Unavailable');
287
-			header('Retry-After: 120');
288
-
289
-			// render error page
290
-			$template = new OC_Template('', 'update.user', 'guest');
291
-			OC_Util::addScript('maintenance-check');
292
-			OC_Util::addStyle('core', 'guest');
293
-			$template->printPage();
294
-			die();
295
-		}
296
-	}
297
-
298
-	/**
299
-	 * Prints the upgrade page
300
-	 *
301
-	 * @param \OC\SystemConfig $systemConfig
302
-	 */
303
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
304
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
305
-		$tooBig = false;
306
-		if (!$disableWebUpdater) {
307
-			$apps = \OC::$server->getAppManager();
308
-			if ($apps->isInstalled('user_ldap')) {
309
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
310
-
311
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
312
-					->from('ldap_user_mapping')
313
-					->execute();
314
-				$row = $result->fetch();
315
-				$result->closeCursor();
316
-
317
-				$tooBig = ($row['user_count'] > 50);
318
-			}
319
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
320
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
321
-
322
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
323
-					->from('user_saml_users')
324
-					->execute();
325
-				$row = $result->fetch();
326
-				$result->closeCursor();
327
-
328
-				$tooBig = ($row['user_count'] > 50);
329
-			}
330
-			if (!$tooBig) {
331
-				// count users
332
-				$stats = \OC::$server->getUserManager()->countUsers();
333
-				$totalUsers = array_sum($stats);
334
-				$tooBig = ($totalUsers > 50);
335
-			}
336
-		}
337
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
338
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
339
-
340
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
341
-			// send http status 503
342
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
343
-			header('Status: 503 Service Temporarily Unavailable');
344
-			header('Retry-After: 120');
345
-
346
-			// render error page
347
-			$template = new OC_Template('', 'update.use-cli', 'guest');
348
-			$template->assign('productName', 'nextcloud'); // for now
349
-			$template->assign('version', OC_Util::getVersionString());
350
-			$template->assign('tooBig', $tooBig);
351
-
352
-			$template->printPage();
353
-			die();
354
-		}
355
-
356
-		// check whether this is a core update or apps update
357
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
358
-		$currentVersion = implode('.', \OCP\Util::getVersion());
359
-
360
-		// if not a core upgrade, then it's apps upgrade
361
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
362
-
363
-		$oldTheme = $systemConfig->getValue('theme');
364
-		$systemConfig->setValue('theme', '');
365
-		OC_Util::addScript('config'); // needed for web root
366
-		OC_Util::addScript('update');
367
-
368
-		/** @var \OC\App\AppManager $appManager */
369
-		$appManager = \OC::$server->getAppManager();
370
-
371
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
372
-		$tmpl->assign('version', OC_Util::getVersionString());
373
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
374
-
375
-		// get third party apps
376
-		$ocVersion = \OCP\Util::getVersion();
377
-		$ocVersion = implode('.', $ocVersion);
378
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
379
-		$incompatibleShippedApps = [];
380
-		foreach ($incompatibleApps as $appInfo) {
381
-			if ($appManager->isShipped($appInfo['id'])) {
382
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
383
-			}
384
-		}
385
-
386
-		if (!empty($incompatibleShippedApps)) {
387
-			$l = \OC::$server->getL10N('core');
388
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
389
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
390
-		}
391
-
392
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
393
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
394
-		$tmpl->assign('productName', 'Nextcloud'); // for now
395
-		$tmpl->assign('oldTheme', $oldTheme);
396
-		$tmpl->printPage();
397
-	}
398
-
399
-	public static function initSession() {
400
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
401
-			ini_set('session.cookie_secure', true);
402
-		}
403
-
404
-		// prevents javascript from accessing php session cookies
405
-		ini_set('session.cookie_httponly', 'true');
406
-
407
-		// set the cookie path to the Nextcloud directory
408
-		$cookie_path = OC::$WEBROOT ? : '/';
409
-		ini_set('session.cookie_path', $cookie_path);
410
-
411
-		// Let the session name be changed in the initSession Hook
412
-		$sessionName = OC_Util::getInstanceId();
413
-
414
-		try {
415
-			// Allow session apps to create a custom session object
416
-			$useCustomSession = false;
417
-			$session = self::$server->getSession();
418
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
419
-			if (!$useCustomSession) {
420
-				// set the session name to the instance id - which is unique
421
-				$session = new \OC\Session\Internal($sessionName);
422
-			}
423
-
424
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
425
-			$session = $cryptoWrapper->wrapSession($session);
426
-			self::$server->setSession($session);
427
-
428
-			// if session can't be started break with http 500 error
429
-		} catch (Exception $e) {
430
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
431
-			//show the user a detailed error page
432
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
433
-			OC_Template::printExceptionErrorPage($e);
434
-			die();
435
-		}
436
-
437
-		$sessionLifeTime = self::getSessionLifeTime();
438
-
439
-		// session timeout
440
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441
-			if (isset($_COOKIE[session_name()])) {
442
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
443
-			}
444
-			\OC::$server->getUserSession()->logout();
445
-		}
446
-
447
-		$session->set('LAST_ACTIVITY', time());
448
-	}
449
-
450
-	/**
451
-	 * @return string
452
-	 */
453
-	private static function getSessionLifeTime() {
454
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
455
-	}
456
-
457
-	public static function loadAppClassPaths() {
458
-		foreach (OC_App::getEnabledApps() as $app) {
459
-			$appPath = OC_App::getAppPath($app);
460
-			if ($appPath === false) {
461
-				continue;
462
-			}
463
-
464
-			$file = $appPath . '/appinfo/classpath.php';
465
-			if (file_exists($file)) {
466
-				require_once $file;
467
-			}
468
-		}
469
-	}
470
-
471
-	/**
472
-	 * Try to set some values to the required Nextcloud default
473
-	 */
474
-	public static function setRequiredIniValues() {
475
-		@ini_set('default_charset', 'UTF-8');
476
-		@ini_set('gd.jpeg_ignore_warning', '1');
477
-	}
478
-
479
-	/**
480
-	 * Send the same site cookies
481
-	 */
482
-	private static function sendSameSiteCookies() {
483
-		$cookieParams = session_get_cookie_params();
484
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
485
-		$policies = [
486
-			'lax',
487
-			'strict',
488
-		];
489
-
490
-		// Append __Host to the cookie if it meets the requirements
491
-		$cookiePrefix = '';
492
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
493
-			$cookiePrefix = '__Host-';
494
-		}
495
-
496
-		foreach($policies as $policy) {
497
-			header(
498
-				sprintf(
499
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
500
-					$cookiePrefix,
501
-					$policy,
502
-					$cookieParams['path'],
503
-					$policy
504
-				),
505
-				false
506
-			);
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
512
-	 * be set in every request if cookies are sent to add a second level of
513
-	 * defense against CSRF.
514
-	 *
515
-	 * If the cookie is not sent this will set the cookie and reload the page.
516
-	 * We use an additional cookie since we want to protect logout CSRF and
517
-	 * also we can't directly interfere with PHP's session mechanism.
518
-	 */
519
-	private static function performSameSiteCookieProtection() {
520
-		$request = \OC::$server->getRequest();
521
-
522
-		// Some user agents are notorious and don't really properly follow HTTP
523
-		// specifications. For those, have an automated opt-out. Since the protection
524
-		// for remote.php is applied in base.php as starting point we need to opt out
525
-		// here.
526
-		$incompatibleUserAgents = [
527
-			// OS X Finder
528
-			'/^WebDAVFS/',
529
-			'/^Microsoft-WebDAV-MiniRedir/',
530
-		];
531
-		if($request->isUserAgent($incompatibleUserAgents)) {
532
-			return;
533
-		}
534
-
535
-		if(count($_COOKIE) > 0) {
536
-			$requestUri = $request->getScriptName();
537
-			$processingScript = explode('/', $requestUri);
538
-			$processingScript = $processingScript[count($processingScript)-1];
539
-
540
-			// index.php routes are handled in the middleware
541
-			if($processingScript === 'index.php') {
542
-				return;
543
-			}
544
-
545
-			// All other endpoints require the lax and the strict cookie
546
-			if(!$request->passesStrictCookieCheck()) {
547
-				self::sendSameSiteCookies();
548
-				// Debug mode gets access to the resources without strict cookie
549
-				// due to the fact that the SabreDAV browser also lives there.
550
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
-					exit();
553
-				}
554
-			}
555
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
-			self::sendSameSiteCookies();
557
-		}
558
-	}
559
-
560
-	public static function init() {
561
-		// calculate the root directories
562
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
-
564
-		// register autoloader
565
-		$loaderStart = microtime(true);
566
-		require_once __DIR__ . '/autoloader.php';
567
-		self::$loader = new \OC\Autoloader([
568
-			OC::$SERVERROOT . '/lib/private/legacy',
569
-		]);
570
-		if (defined('PHPUNIT_RUN')) {
571
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
-		}
573
-		spl_autoload_register(array(self::$loader, 'load'));
574
-		$loaderEnd = microtime(true);
575
-
576
-		self::$CLI = (php_sapi_name() == 'cli');
577
-
578
-		// Add default composer PSR-4 autoloader
579
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
-
581
-		try {
582
-			self::initPaths();
583
-			// setup 3rdparty autoloader
584
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
-			if (!file_exists($vendorAutoLoad)) {
586
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
587
-			}
588
-			require_once $vendorAutoLoad;
589
-
590
-		} catch (\RuntimeException $e) {
591
-			if (!self::$CLI) {
592
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
593
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
594
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
595
-			}
596
-			// we can't use the template error page here, because this needs the
597
-			// DI container which isn't available yet
598
-			print($e->getMessage());
599
-			exit();
600
-		}
601
-
602
-		// setup the basic server
603
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
604
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
605
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
606
-
607
-		// Don't display errors and log them
608
-		error_reporting(E_ALL | E_STRICT);
609
-		@ini_set('display_errors', '0');
610
-		@ini_set('log_errors', '1');
611
-
612
-		if(!date_default_timezone_set('UTC')) {
613
-			throw new \RuntimeException('Could not set timezone to UTC');
614
-		}
615
-
616
-		//try to configure php to enable big file uploads.
617
-		//this doesn´t work always depending on the webserver and php configuration.
618
-		//Let´s try to overwrite some defaults anyway
619
-
620
-		//try to set the maximum execution time to 60min
621
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
622
-			@set_time_limit(3600);
623
-		}
624
-		@ini_set('max_execution_time', '3600');
625
-		@ini_set('max_input_time', '3600');
626
-
627
-		//try to set the maximum filesize to 10G
628
-		@ini_set('upload_max_filesize', '10G');
629
-		@ini_set('post_max_size', '10G');
630
-		@ini_set('file_uploads', '50');
631
-
632
-		self::setRequiredIniValues();
633
-		self::handleAuthHeaders();
634
-		self::registerAutoloaderCache();
635
-
636
-		// initialize intl fallback is necessary
637
-		\Patchwork\Utf8\Bootup::initIntl();
638
-		OC_Util::isSetLocaleWorking();
639
-
640
-		if (!defined('PHPUNIT_RUN')) {
641
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
642
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
643
-			OC\Log\ErrorHandler::register($debug);
644
-		}
645
-
646
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
647
-		OC_App::loadApps(array('session'));
648
-		if (!self::$CLI) {
649
-			self::initSession();
650
-		}
651
-		\OC::$server->getEventLogger()->end('init_session');
652
-		self::checkConfig();
653
-		self::checkInstalled();
654
-
655
-		OC_Response::addSecurityHeaders();
656
-
657
-		self::performSameSiteCookieProtection();
658
-
659
-		if (!defined('OC_CONSOLE')) {
660
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
661
-			if (count($errors) > 0) {
662
-				if (self::$CLI) {
663
-					// Convert l10n string into regular string for usage in database
664
-					$staticErrors = [];
665
-					foreach ($errors as $error) {
666
-						echo $error['error'] . "\n";
667
-						echo $error['hint'] . "\n\n";
668
-						$staticErrors[] = [
669
-							'error' => (string)$error['error'],
670
-							'hint' => (string)$error['hint'],
671
-						];
672
-					}
673
-
674
-					try {
675
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
676
-					} catch (\Exception $e) {
677
-						echo('Writing to database failed');
678
-					}
679
-					exit(1);
680
-				} else {
681
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
682
-					OC_Util::addStyle('guest');
683
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
684
-					exit;
685
-				}
686
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
687
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
688
-			}
689
-		}
690
-		//try to set the session lifetime
691
-		$sessionLifeTime = self::getSessionLifeTime();
692
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
693
-
694
-		$systemConfig = \OC::$server->getSystemConfig();
695
-
696
-		// User and Groups
697
-		if (!$systemConfig->getValue("installed", false)) {
698
-			self::$server->getSession()->set('user_id', '');
699
-		}
700
-
701
-		OC_User::useBackend(new \OC\User\Database());
702
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
703
-
704
-		// Subscribe to the hook
705
-		\OCP\Util::connectHook(
706
-			'\OCA\Files_Sharing\API\Server2Server',
707
-			'preLoginNameUsedAsUserName',
708
-			'\OC\User\Database',
709
-			'preLoginNameUsedAsUserName'
710
-		);
711
-
712
-		//setup extra user backends
713
-		if (!\OCP\Util::needUpgrade()) {
714
-			OC_User::setupBackends();
715
-		} else {
716
-			// Run upgrades in incognito mode
717
-			OC_User::setIncognitoMode(true);
718
-		}
719
-
720
-		self::registerCleanupHooks();
721
-		self::registerFilesystemHooks();
722
-		self::registerShareHooks();
723
-		self::registerEncryptionWrapper();
724
-		self::registerEncryptionHooks();
725
-		self::registerAccountHooks();
726
-
727
-		// Make sure that the application class is not loaded before the database is setup
728
-		if ($systemConfig->getValue("installed", false)) {
729
-			$settings = new \OC\Settings\Application();
730
-			$settings->register();
731
-		}
732
-
733
-		//make sure temporary files are cleaned up
734
-		$tmpManager = \OC::$server->getTempManager();
735
-		register_shutdown_function(array($tmpManager, 'clean'));
736
-		$lockProvider = \OC::$server->getLockingProvider();
737
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
738
-
739
-		// Check whether the sample configuration has been copied
740
-		if($systemConfig->getValue('copied_sample_config', false)) {
741
-			$l = \OC::$server->getL10N('lib');
742
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
743
-			header('Status: 503 Service Temporarily Unavailable');
744
-			OC_Template::printErrorPage(
745
-				$l->t('Sample configuration detected'),
746
-				$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')
747
-			);
748
-			return;
749
-		}
750
-
751
-		$request = \OC::$server->getRequest();
752
-		$host = $request->getInsecureServerHost();
753
-		/**
754
-		 * if the host passed in headers isn't trusted
755
-		 * FIXME: Should not be in here at all :see_no_evil:
756
-		 */
757
-		if (!OC::$CLI
758
-			// overwritehost is always trusted, workaround to not have to make
759
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
760
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
761
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
762
-			&& self::$server->getConfig()->getSystemValue('installed', false)
763
-		) {
764
-			// Allow access to CSS resources
765
-			$isScssRequest = false;
766
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
767
-				$isScssRequest = true;
768
-			}
769
-
770
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
771
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
772
-				header('Status: 400 Bad Request');
773
-				header('Content-Type: application/json');
774
-				echo '{"error": "Trusted domain error.", "code": 15}';
775
-				exit();
776
-			}
777
-
778
-			if (!$isScssRequest) {
779
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
780
-				header('Status: 400 Bad Request');
781
-
782
-				\OC::$server->getLogger()->info(
783
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
784
-					[
785
-						'app' => 'core',
786
-						'remoteAddress' => $request->getRemoteAddress(),
787
-						'host' => $host,
788
-					]
789
-				);
790
-
791
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
792
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
793
-				$tmpl->printPage();
794
-
795
-				exit();
796
-			}
797
-		}
798
-		\OC::$server->getEventLogger()->end('boot');
799
-	}
800
-
801
-	/**
802
-	 * register hooks for the cleanup of cache and bruteforce protection
803
-	 */
804
-	public static function registerCleanupHooks() {
805
-		//don't try to do this before we are properly setup
806
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
807
-
808
-			// NOTE: This will be replaced to use OCP
809
-			$userSession = self::$server->getUserSession();
810
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
811
-				if (!defined('PHPUNIT_RUN')) {
812
-					// reset brute force delay for this IP address and username
813
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
814
-					$request = \OC::$server->getRequest();
815
-					$throttler = \OC::$server->getBruteForceThrottler();
816
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
817
-				}
818
-
819
-				try {
820
-					$cache = new \OC\Cache\File();
821
-					$cache->gc();
822
-				} catch (\OC\ServerNotAvailableException $e) {
823
-					// not a GC exception, pass it on
824
-					throw $e;
825
-				} catch (\OC\ForbiddenException $e) {
826
-					// filesystem blocked for this request, ignore
827
-				} catch (\Exception $e) {
828
-					// a GC exception should not prevent users from using OC,
829
-					// so log the exception
830
-					\OC::$server->getLogger()->logException($e, [
831
-						'message' => 'Exception when running cache gc.',
832
-						'level' => ILogger::WARN,
833
-						'app' => 'core',
834
-					]);
835
-				}
836
-			});
837
-		}
838
-	}
839
-
840
-	private static function registerEncryptionWrapper() {
841
-		$manager = self::$server->getEncryptionManager();
842
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
843
-	}
844
-
845
-	private static function registerEncryptionHooks() {
846
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
847
-		if ($enabled) {
848
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
849
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
850
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
851
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
852
-		}
853
-	}
854
-
855
-	private static function registerAccountHooks() {
856
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
857
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
858
-	}
859
-
860
-	/**
861
-	 * register hooks for the filesystem
862
-	 */
863
-	public static function registerFilesystemHooks() {
864
-		// Check for blacklisted files
865
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
866
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
867
-	}
868
-
869
-	/**
870
-	 * register hooks for sharing
871
-	 */
872
-	public static function registerShareHooks() {
873
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
874
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
875
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
876
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
877
-		}
878
-	}
879
-
880
-	protected static function registerAutoloaderCache() {
881
-		// The class loader takes an optional low-latency cache, which MUST be
882
-		// namespaced. The instanceid is used for namespacing, but might be
883
-		// unavailable at this point. Furthermore, it might not be possible to
884
-		// generate an instanceid via \OC_Util::getInstanceId() because the
885
-		// config file may not be writable. As such, we only register a class
886
-		// loader cache if instanceid is available without trying to create one.
887
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
888
-		if ($instanceId) {
889
-			try {
890
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
891
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
892
-			} catch (\Exception $ex) {
893
-			}
894
-		}
895
-	}
896
-
897
-	/**
898
-	 * Handle the request
899
-	 */
900
-	public static function handleRequest() {
901
-
902
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
903
-		$systemConfig = \OC::$server->getSystemConfig();
904
-		// load all the classpaths from the enabled apps so they are available
905
-		// in the routing files of each app
906
-		OC::loadAppClassPaths();
907
-
908
-		// Check if Nextcloud is installed or in maintenance (update) mode
909
-		if (!$systemConfig->getValue('installed', false)) {
910
-			\OC::$server->getSession()->clear();
911
-			$setupHelper = new OC\Setup(
912
-				$systemConfig,
913
-				\OC::$server->getIniWrapper(),
914
-				\OC::$server->getL10N('lib'),
915
-				\OC::$server->query(\OCP\Defaults::class),
916
-				\OC::$server->getLogger(),
917
-				\OC::$server->getSecureRandom(),
918
-				\OC::$server->query(\OC\Installer::class)
919
-			);
920
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
921
-			$controller->run($_POST);
922
-			exit();
923
-		}
924
-
925
-		$request = \OC::$server->getRequest();
926
-		$requestPath = $request->getRawPathInfo();
927
-		if ($requestPath === '/heartbeat') {
928
-			return;
929
-		}
930
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
931
-			self::checkMaintenanceMode();
932
-
933
-			if (\OCP\Util::needUpgrade()) {
934
-				if (function_exists('opcache_reset')) {
935
-					opcache_reset();
936
-				}
937
-				if (!$systemConfig->getValue('maintenance', false)) {
938
-					self::printUpgradePage($systemConfig);
939
-					exit();
940
-				}
941
-			}
942
-		}
943
-
944
-		// emergency app disabling
945
-		if ($requestPath === '/disableapp'
946
-			&& $request->getMethod() === 'POST'
947
-			&& ((array)$request->getParam('appid')) !== ''
948
-		) {
949
-			\OC_JSON::callCheck();
950
-			\OC_JSON::checkAdminUser();
951
-			$appIds = (array)$request->getParam('appid');
952
-			foreach($appIds as $appId) {
953
-				$appId = \OC_App::cleanAppId($appId);
954
-				\OC::$server->getAppManager()->disableApp($appId);
955
-			}
956
-			\OC_JSON::success();
957
-			exit();
958
-		}
959
-
960
-		// Always load authentication apps
961
-		OC_App::loadApps(['authentication']);
962
-
963
-		// Load minimum set of apps
964
-		if (!\OCP\Util::needUpgrade()
965
-			&& !$systemConfig->getValue('maintenance', false)) {
966
-			// For logged-in users: Load everything
967
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
968
-				OC_App::loadApps();
969
-			} else {
970
-				// For guests: Load only filesystem and logging
971
-				OC_App::loadApps(array('filesystem', 'logging'));
972
-				self::handleLogin($request);
973
-			}
974
-		}
975
-
976
-		if (!self::$CLI) {
977
-			try {
978
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
979
-					OC_App::loadApps(array('filesystem', 'logging'));
980
-					OC_App::loadApps();
981
-				}
982
-				OC_Util::setupFS();
983
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
984
-				return;
985
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
986
-				//header('HTTP/1.0 404 Not Found');
987
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
988
-				OC_Response::setStatus(405);
989
-				return;
990
-			}
991
-		}
992
-
993
-		// Handle WebDAV
994
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
995
-			// not allowed any more to prevent people
996
-			// mounting this root directly.
997
-			// Users need to mount remote.php/webdav instead.
998
-			header('HTTP/1.1 405 Method Not Allowed');
999
-			header('Status: 405 Method Not Allowed');
1000
-			return;
1001
-		}
1002
-
1003
-		// Someone is logged in
1004
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1005
-			OC_App::loadApps();
1006
-			OC_User::setupBackends();
1007
-			OC_Util::setupFS();
1008
-			// FIXME
1009
-			// Redirect to default application
1010
-			OC_Util::redirectToDefaultPage();
1011
-		} else {
1012
-			// Not handled and not logged in
1013
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1014
-		}
1015
-	}
1016
-
1017
-	/**
1018
-	 * Check login: apache auth, auth token, basic auth
1019
-	 *
1020
-	 * @param OCP\IRequest $request
1021
-	 * @return boolean
1022
-	 */
1023
-	static function handleLogin(OCP\IRequest $request) {
1024
-		$userSession = self::$server->getUserSession();
1025
-		if (OC_User::handleApacheAuth()) {
1026
-			return true;
1027
-		}
1028
-		if ($userSession->tryTokenLogin($request)) {
1029
-			return true;
1030
-		}
1031
-		if (isset($_COOKIE['nc_username'])
1032
-			&& isset($_COOKIE['nc_token'])
1033
-			&& isset($_COOKIE['nc_session_id'])
1034
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1035
-			return true;
1036
-		}
1037
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1038
-			return true;
1039
-		}
1040
-		return false;
1041
-	}
1042
-
1043
-	protected static function handleAuthHeaders() {
1044
-		//copy http auth headers for apache+php-fcgid work around
1045
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1046
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1047
-		}
1048
-
1049
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1050
-		$vars = array(
1051
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1052
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1053
-		);
1054
-		foreach ($vars as $var) {
1055
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1056
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1057
-				$_SERVER['PHP_AUTH_USER'] = $name;
1058
-				$_SERVER['PHP_AUTH_PW'] = $password;
1059
-				break;
1060
-			}
1061
-		}
1062
-	}
71
+    /**
72
+     * Associative array for autoloading. classname => filename
73
+     */
74
+    public static $CLASSPATH = array();
75
+    /**
76
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
+     */
78
+    public static $SERVERROOT = '';
79
+    /**
80
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
+     */
82
+    private static $SUBURI = '';
83
+    /**
84
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
85
+     */
86
+    public static $WEBROOT = '';
87
+    /**
88
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
+     * web path in 'url'
90
+     */
91
+    public static $APPSROOTS = array();
92
+
93
+    /**
94
+     * @var string
95
+     */
96
+    public static $configDir;
97
+
98
+    /**
99
+     * requested app
100
+     */
101
+    public static $REQUESTEDAPP = '';
102
+
103
+    /**
104
+     * check if Nextcloud runs in cli mode
105
+     */
106
+    public static $CLI = false;
107
+
108
+    /**
109
+     * @var \OC\Autoloader $loader
110
+     */
111
+    public static $loader = null;
112
+
113
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
+    public static $composerAutoloader = null;
115
+
116
+    /**
117
+     * @var \OC\Server
118
+     */
119
+    public static $server = null;
120
+
121
+    /**
122
+     * @var \OC\Config
123
+     */
124
+    private static $config = null;
125
+
126
+    /**
127
+     * @throws \RuntimeException when the 3rdparty directory is missing or
128
+     * the app path list is empty or contains an invalid path
129
+     */
130
+    public static function initPaths() {
131
+        if(defined('PHPUNIT_CONFIG_DIR')) {
132
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+            self::$configDir = rtrim($dir, '/') . '/';
137
+        } else {
138
+            self::$configDir = OC::$SERVERROOT . '/config/';
139
+        }
140
+        self::$config = new \OC\Config(self::$configDir);
141
+
142
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
+        /**
144
+         * FIXME: The following lines are required because we can't yet instantiate
145
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
+         */
147
+        $params = [
148
+            'server' => [
149
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
+            ],
152
+        ];
153
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
+        $scriptName = $fakeRequest->getScriptName();
155
+        if (substr($scriptName, -1) == '/') {
156
+            $scriptName .= 'index.php';
157
+            //make sure suburi follows the same rules as scriptName
158
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
159
+                if (substr(OC::$SUBURI, -1) != '/') {
160
+                    OC::$SUBURI = OC::$SUBURI . '/';
161
+                }
162
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
163
+            }
164
+        }
165
+
166
+
167
+        if (OC::$CLI) {
168
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
+        } else {
170
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
+
173
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
175
+                }
176
+            } else {
177
+                // The scriptName is not ending with OC::$SUBURI
178
+                // This most likely means that we are calling from CLI.
179
+                // However some cron jobs still need to generate
180
+                // a web URL, so we use overwritewebroot as a fallback.
181
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
+            }
183
+
184
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
+            // slash which is required by URL generation.
186
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
+                header('Location: '.\OC::$WEBROOT.'/');
189
+                exit();
190
+            }
191
+        }
192
+
193
+        // search the apps folder
194
+        $config_paths = self::$config->getValue('apps_paths', array());
195
+        if (!empty($config_paths)) {
196
+            foreach ($config_paths as $paths) {
197
+                if (isset($paths['url']) && isset($paths['path'])) {
198
+                    $paths['url'] = rtrim($paths['url'], '/');
199
+                    $paths['path'] = rtrim($paths['path'], '/');
200
+                    OC::$APPSROOTS[] = $paths;
201
+                }
202
+            }
203
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
+            OC::$APPSROOTS[] = array(
207
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
+                'url' => '/apps',
209
+                'writable' => true
210
+            );
211
+        }
212
+
213
+        if (empty(OC::$APPSROOTS)) {
214
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
+                . ' or the folder above. You can also configure the location in the config.php file.');
216
+        }
217
+        $paths = array();
218
+        foreach (OC::$APPSROOTS as $path) {
219
+            $paths[] = $path['path'];
220
+            if (!is_dir($path['path'])) {
221
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
223
+                    . ' config.php file.', $path['path']));
224
+            }
225
+        }
226
+
227
+        // set the right include path
228
+        set_include_path(
229
+            implode(PATH_SEPARATOR, $paths)
230
+        );
231
+    }
232
+
233
+    public static function checkConfig() {
234
+        $l = \OC::$server->getL10N('lib');
235
+
236
+        // Create config if it does not already exist
237
+        $configFilePath = self::$configDir .'/config.php';
238
+        if(!file_exists($configFilePath)) {
239
+            @touch($configFilePath);
240
+        }
241
+
242
+        // Check if config is writable
243
+        $configFileWritable = is_writable($configFilePath);
244
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
246
+
247
+            $urlGenerator = \OC::$server->getURLGenerator();
248
+
249
+            if (self::$CLI) {
250
+                echo $l->t('Cannot write into "config" directory!')."\n";
251
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
+                echo "\n";
253
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
254
+                exit;
255
+            } else {
256
+                OC_Template::printErrorPage(
257
+                    $l->t('Cannot write into "config" directory!'),
258
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
259
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
260
+                );
261
+            }
262
+        }
263
+    }
264
+
265
+    public static function checkInstalled() {
266
+        if (defined('OC_CONSOLE')) {
267
+            return;
268
+        }
269
+        // Redirect to installer if not installed
270
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
271
+            if (OC::$CLI) {
272
+                throw new Exception('Not installed');
273
+            } else {
274
+                $url = OC::$WEBROOT . '/index.php';
275
+                header('Location: ' . $url);
276
+            }
277
+            exit();
278
+        }
279
+    }
280
+
281
+    public static function checkMaintenanceMode() {
282
+        // Allow ajax update script to execute without being stopped
283
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
284
+            // send http status 503
285
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
286
+            header('Status: 503 Service Temporarily Unavailable');
287
+            header('Retry-After: 120');
288
+
289
+            // render error page
290
+            $template = new OC_Template('', 'update.user', 'guest');
291
+            OC_Util::addScript('maintenance-check');
292
+            OC_Util::addStyle('core', 'guest');
293
+            $template->printPage();
294
+            die();
295
+        }
296
+    }
297
+
298
+    /**
299
+     * Prints the upgrade page
300
+     *
301
+     * @param \OC\SystemConfig $systemConfig
302
+     */
303
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
304
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
305
+        $tooBig = false;
306
+        if (!$disableWebUpdater) {
307
+            $apps = \OC::$server->getAppManager();
308
+            if ($apps->isInstalled('user_ldap')) {
309
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
310
+
311
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
312
+                    ->from('ldap_user_mapping')
313
+                    ->execute();
314
+                $row = $result->fetch();
315
+                $result->closeCursor();
316
+
317
+                $tooBig = ($row['user_count'] > 50);
318
+            }
319
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
320
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
321
+
322
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
323
+                    ->from('user_saml_users')
324
+                    ->execute();
325
+                $row = $result->fetch();
326
+                $result->closeCursor();
327
+
328
+                $tooBig = ($row['user_count'] > 50);
329
+            }
330
+            if (!$tooBig) {
331
+                // count users
332
+                $stats = \OC::$server->getUserManager()->countUsers();
333
+                $totalUsers = array_sum($stats);
334
+                $tooBig = ($totalUsers > 50);
335
+            }
336
+        }
337
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
338
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
339
+
340
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
341
+            // send http status 503
342
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
343
+            header('Status: 503 Service Temporarily Unavailable');
344
+            header('Retry-After: 120');
345
+
346
+            // render error page
347
+            $template = new OC_Template('', 'update.use-cli', 'guest');
348
+            $template->assign('productName', 'nextcloud'); // for now
349
+            $template->assign('version', OC_Util::getVersionString());
350
+            $template->assign('tooBig', $tooBig);
351
+
352
+            $template->printPage();
353
+            die();
354
+        }
355
+
356
+        // check whether this is a core update or apps update
357
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
358
+        $currentVersion = implode('.', \OCP\Util::getVersion());
359
+
360
+        // if not a core upgrade, then it's apps upgrade
361
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
362
+
363
+        $oldTheme = $systemConfig->getValue('theme');
364
+        $systemConfig->setValue('theme', '');
365
+        OC_Util::addScript('config'); // needed for web root
366
+        OC_Util::addScript('update');
367
+
368
+        /** @var \OC\App\AppManager $appManager */
369
+        $appManager = \OC::$server->getAppManager();
370
+
371
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
372
+        $tmpl->assign('version', OC_Util::getVersionString());
373
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
374
+
375
+        // get third party apps
376
+        $ocVersion = \OCP\Util::getVersion();
377
+        $ocVersion = implode('.', $ocVersion);
378
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
379
+        $incompatibleShippedApps = [];
380
+        foreach ($incompatibleApps as $appInfo) {
381
+            if ($appManager->isShipped($appInfo['id'])) {
382
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
383
+            }
384
+        }
385
+
386
+        if (!empty($incompatibleShippedApps)) {
387
+            $l = \OC::$server->getL10N('core');
388
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
389
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
390
+        }
391
+
392
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
393
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
394
+        $tmpl->assign('productName', 'Nextcloud'); // for now
395
+        $tmpl->assign('oldTheme', $oldTheme);
396
+        $tmpl->printPage();
397
+    }
398
+
399
+    public static function initSession() {
400
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
401
+            ini_set('session.cookie_secure', true);
402
+        }
403
+
404
+        // prevents javascript from accessing php session cookies
405
+        ini_set('session.cookie_httponly', 'true');
406
+
407
+        // set the cookie path to the Nextcloud directory
408
+        $cookie_path = OC::$WEBROOT ? : '/';
409
+        ini_set('session.cookie_path', $cookie_path);
410
+
411
+        // Let the session name be changed in the initSession Hook
412
+        $sessionName = OC_Util::getInstanceId();
413
+
414
+        try {
415
+            // Allow session apps to create a custom session object
416
+            $useCustomSession = false;
417
+            $session = self::$server->getSession();
418
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
419
+            if (!$useCustomSession) {
420
+                // set the session name to the instance id - which is unique
421
+                $session = new \OC\Session\Internal($sessionName);
422
+            }
423
+
424
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
425
+            $session = $cryptoWrapper->wrapSession($session);
426
+            self::$server->setSession($session);
427
+
428
+            // if session can't be started break with http 500 error
429
+        } catch (Exception $e) {
430
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
431
+            //show the user a detailed error page
432
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
433
+            OC_Template::printExceptionErrorPage($e);
434
+            die();
435
+        }
436
+
437
+        $sessionLifeTime = self::getSessionLifeTime();
438
+
439
+        // session timeout
440
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441
+            if (isset($_COOKIE[session_name()])) {
442
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
443
+            }
444
+            \OC::$server->getUserSession()->logout();
445
+        }
446
+
447
+        $session->set('LAST_ACTIVITY', time());
448
+    }
449
+
450
+    /**
451
+     * @return string
452
+     */
453
+    private static function getSessionLifeTime() {
454
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
455
+    }
456
+
457
+    public static function loadAppClassPaths() {
458
+        foreach (OC_App::getEnabledApps() as $app) {
459
+            $appPath = OC_App::getAppPath($app);
460
+            if ($appPath === false) {
461
+                continue;
462
+            }
463
+
464
+            $file = $appPath . '/appinfo/classpath.php';
465
+            if (file_exists($file)) {
466
+                require_once $file;
467
+            }
468
+        }
469
+    }
470
+
471
+    /**
472
+     * Try to set some values to the required Nextcloud default
473
+     */
474
+    public static function setRequiredIniValues() {
475
+        @ini_set('default_charset', 'UTF-8');
476
+        @ini_set('gd.jpeg_ignore_warning', '1');
477
+    }
478
+
479
+    /**
480
+     * Send the same site cookies
481
+     */
482
+    private static function sendSameSiteCookies() {
483
+        $cookieParams = session_get_cookie_params();
484
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
485
+        $policies = [
486
+            'lax',
487
+            'strict',
488
+        ];
489
+
490
+        // Append __Host to the cookie if it meets the requirements
491
+        $cookiePrefix = '';
492
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
493
+            $cookiePrefix = '__Host-';
494
+        }
495
+
496
+        foreach($policies as $policy) {
497
+            header(
498
+                sprintf(
499
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
500
+                    $cookiePrefix,
501
+                    $policy,
502
+                    $cookieParams['path'],
503
+                    $policy
504
+                ),
505
+                false
506
+            );
507
+        }
508
+    }
509
+
510
+    /**
511
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
512
+     * be set in every request if cookies are sent to add a second level of
513
+     * defense against CSRF.
514
+     *
515
+     * If the cookie is not sent this will set the cookie and reload the page.
516
+     * We use an additional cookie since we want to protect logout CSRF and
517
+     * also we can't directly interfere with PHP's session mechanism.
518
+     */
519
+    private static function performSameSiteCookieProtection() {
520
+        $request = \OC::$server->getRequest();
521
+
522
+        // Some user agents are notorious and don't really properly follow HTTP
523
+        // specifications. For those, have an automated opt-out. Since the protection
524
+        // for remote.php is applied in base.php as starting point we need to opt out
525
+        // here.
526
+        $incompatibleUserAgents = [
527
+            // OS X Finder
528
+            '/^WebDAVFS/',
529
+            '/^Microsoft-WebDAV-MiniRedir/',
530
+        ];
531
+        if($request->isUserAgent($incompatibleUserAgents)) {
532
+            return;
533
+        }
534
+
535
+        if(count($_COOKIE) > 0) {
536
+            $requestUri = $request->getScriptName();
537
+            $processingScript = explode('/', $requestUri);
538
+            $processingScript = $processingScript[count($processingScript)-1];
539
+
540
+            // index.php routes are handled in the middleware
541
+            if($processingScript === 'index.php') {
542
+                return;
543
+            }
544
+
545
+            // All other endpoints require the lax and the strict cookie
546
+            if(!$request->passesStrictCookieCheck()) {
547
+                self::sendSameSiteCookies();
548
+                // Debug mode gets access to the resources without strict cookie
549
+                // due to the fact that the SabreDAV browser also lives there.
550
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
+                    exit();
553
+                }
554
+            }
555
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
+            self::sendSameSiteCookies();
557
+        }
558
+    }
559
+
560
+    public static function init() {
561
+        // calculate the root directories
562
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
+
564
+        // register autoloader
565
+        $loaderStart = microtime(true);
566
+        require_once __DIR__ . '/autoloader.php';
567
+        self::$loader = new \OC\Autoloader([
568
+            OC::$SERVERROOT . '/lib/private/legacy',
569
+        ]);
570
+        if (defined('PHPUNIT_RUN')) {
571
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
+        }
573
+        spl_autoload_register(array(self::$loader, 'load'));
574
+        $loaderEnd = microtime(true);
575
+
576
+        self::$CLI = (php_sapi_name() == 'cli');
577
+
578
+        // Add default composer PSR-4 autoloader
579
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
+
581
+        try {
582
+            self::initPaths();
583
+            // setup 3rdparty autoloader
584
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
+            if (!file_exists($vendorAutoLoad)) {
586
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
587
+            }
588
+            require_once $vendorAutoLoad;
589
+
590
+        } catch (\RuntimeException $e) {
591
+            if (!self::$CLI) {
592
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
593
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
594
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
595
+            }
596
+            // we can't use the template error page here, because this needs the
597
+            // DI container which isn't available yet
598
+            print($e->getMessage());
599
+            exit();
600
+        }
601
+
602
+        // setup the basic server
603
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
604
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
605
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
606
+
607
+        // Don't display errors and log them
608
+        error_reporting(E_ALL | E_STRICT);
609
+        @ini_set('display_errors', '0');
610
+        @ini_set('log_errors', '1');
611
+
612
+        if(!date_default_timezone_set('UTC')) {
613
+            throw new \RuntimeException('Could not set timezone to UTC');
614
+        }
615
+
616
+        //try to configure php to enable big file uploads.
617
+        //this doesn´t work always depending on the webserver and php configuration.
618
+        //Let´s try to overwrite some defaults anyway
619
+
620
+        //try to set the maximum execution time to 60min
621
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
622
+            @set_time_limit(3600);
623
+        }
624
+        @ini_set('max_execution_time', '3600');
625
+        @ini_set('max_input_time', '3600');
626
+
627
+        //try to set the maximum filesize to 10G
628
+        @ini_set('upload_max_filesize', '10G');
629
+        @ini_set('post_max_size', '10G');
630
+        @ini_set('file_uploads', '50');
631
+
632
+        self::setRequiredIniValues();
633
+        self::handleAuthHeaders();
634
+        self::registerAutoloaderCache();
635
+
636
+        // initialize intl fallback is necessary
637
+        \Patchwork\Utf8\Bootup::initIntl();
638
+        OC_Util::isSetLocaleWorking();
639
+
640
+        if (!defined('PHPUNIT_RUN')) {
641
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
642
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
643
+            OC\Log\ErrorHandler::register($debug);
644
+        }
645
+
646
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
647
+        OC_App::loadApps(array('session'));
648
+        if (!self::$CLI) {
649
+            self::initSession();
650
+        }
651
+        \OC::$server->getEventLogger()->end('init_session');
652
+        self::checkConfig();
653
+        self::checkInstalled();
654
+
655
+        OC_Response::addSecurityHeaders();
656
+
657
+        self::performSameSiteCookieProtection();
658
+
659
+        if (!defined('OC_CONSOLE')) {
660
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
661
+            if (count($errors) > 0) {
662
+                if (self::$CLI) {
663
+                    // Convert l10n string into regular string for usage in database
664
+                    $staticErrors = [];
665
+                    foreach ($errors as $error) {
666
+                        echo $error['error'] . "\n";
667
+                        echo $error['hint'] . "\n\n";
668
+                        $staticErrors[] = [
669
+                            'error' => (string)$error['error'],
670
+                            'hint' => (string)$error['hint'],
671
+                        ];
672
+                    }
673
+
674
+                    try {
675
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
676
+                    } catch (\Exception $e) {
677
+                        echo('Writing to database failed');
678
+                    }
679
+                    exit(1);
680
+                } else {
681
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
682
+                    OC_Util::addStyle('guest');
683
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
684
+                    exit;
685
+                }
686
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
687
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
688
+            }
689
+        }
690
+        //try to set the session lifetime
691
+        $sessionLifeTime = self::getSessionLifeTime();
692
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
693
+
694
+        $systemConfig = \OC::$server->getSystemConfig();
695
+
696
+        // User and Groups
697
+        if (!$systemConfig->getValue("installed", false)) {
698
+            self::$server->getSession()->set('user_id', '');
699
+        }
700
+
701
+        OC_User::useBackend(new \OC\User\Database());
702
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
703
+
704
+        // Subscribe to the hook
705
+        \OCP\Util::connectHook(
706
+            '\OCA\Files_Sharing\API\Server2Server',
707
+            'preLoginNameUsedAsUserName',
708
+            '\OC\User\Database',
709
+            'preLoginNameUsedAsUserName'
710
+        );
711
+
712
+        //setup extra user backends
713
+        if (!\OCP\Util::needUpgrade()) {
714
+            OC_User::setupBackends();
715
+        } else {
716
+            // Run upgrades in incognito mode
717
+            OC_User::setIncognitoMode(true);
718
+        }
719
+
720
+        self::registerCleanupHooks();
721
+        self::registerFilesystemHooks();
722
+        self::registerShareHooks();
723
+        self::registerEncryptionWrapper();
724
+        self::registerEncryptionHooks();
725
+        self::registerAccountHooks();
726
+
727
+        // Make sure that the application class is not loaded before the database is setup
728
+        if ($systemConfig->getValue("installed", false)) {
729
+            $settings = new \OC\Settings\Application();
730
+            $settings->register();
731
+        }
732
+
733
+        //make sure temporary files are cleaned up
734
+        $tmpManager = \OC::$server->getTempManager();
735
+        register_shutdown_function(array($tmpManager, 'clean'));
736
+        $lockProvider = \OC::$server->getLockingProvider();
737
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
738
+
739
+        // Check whether the sample configuration has been copied
740
+        if($systemConfig->getValue('copied_sample_config', false)) {
741
+            $l = \OC::$server->getL10N('lib');
742
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
743
+            header('Status: 503 Service Temporarily Unavailable');
744
+            OC_Template::printErrorPage(
745
+                $l->t('Sample configuration detected'),
746
+                $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')
747
+            );
748
+            return;
749
+        }
750
+
751
+        $request = \OC::$server->getRequest();
752
+        $host = $request->getInsecureServerHost();
753
+        /**
754
+         * if the host passed in headers isn't trusted
755
+         * FIXME: Should not be in here at all :see_no_evil:
756
+         */
757
+        if (!OC::$CLI
758
+            // overwritehost is always trusted, workaround to not have to make
759
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
760
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
761
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
762
+            && self::$server->getConfig()->getSystemValue('installed', false)
763
+        ) {
764
+            // Allow access to CSS resources
765
+            $isScssRequest = false;
766
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
767
+                $isScssRequest = true;
768
+            }
769
+
770
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
771
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
772
+                header('Status: 400 Bad Request');
773
+                header('Content-Type: application/json');
774
+                echo '{"error": "Trusted domain error.", "code": 15}';
775
+                exit();
776
+            }
777
+
778
+            if (!$isScssRequest) {
779
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
780
+                header('Status: 400 Bad Request');
781
+
782
+                \OC::$server->getLogger()->info(
783
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
784
+                    [
785
+                        'app' => 'core',
786
+                        'remoteAddress' => $request->getRemoteAddress(),
787
+                        'host' => $host,
788
+                    ]
789
+                );
790
+
791
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
792
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
793
+                $tmpl->printPage();
794
+
795
+                exit();
796
+            }
797
+        }
798
+        \OC::$server->getEventLogger()->end('boot');
799
+    }
800
+
801
+    /**
802
+     * register hooks for the cleanup of cache and bruteforce protection
803
+     */
804
+    public static function registerCleanupHooks() {
805
+        //don't try to do this before we are properly setup
806
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
807
+
808
+            // NOTE: This will be replaced to use OCP
809
+            $userSession = self::$server->getUserSession();
810
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
811
+                if (!defined('PHPUNIT_RUN')) {
812
+                    // reset brute force delay for this IP address and username
813
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
814
+                    $request = \OC::$server->getRequest();
815
+                    $throttler = \OC::$server->getBruteForceThrottler();
816
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
817
+                }
818
+
819
+                try {
820
+                    $cache = new \OC\Cache\File();
821
+                    $cache->gc();
822
+                } catch (\OC\ServerNotAvailableException $e) {
823
+                    // not a GC exception, pass it on
824
+                    throw $e;
825
+                } catch (\OC\ForbiddenException $e) {
826
+                    // filesystem blocked for this request, ignore
827
+                } catch (\Exception $e) {
828
+                    // a GC exception should not prevent users from using OC,
829
+                    // so log the exception
830
+                    \OC::$server->getLogger()->logException($e, [
831
+                        'message' => 'Exception when running cache gc.',
832
+                        'level' => ILogger::WARN,
833
+                        'app' => 'core',
834
+                    ]);
835
+                }
836
+            });
837
+        }
838
+    }
839
+
840
+    private static function registerEncryptionWrapper() {
841
+        $manager = self::$server->getEncryptionManager();
842
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
843
+    }
844
+
845
+    private static function registerEncryptionHooks() {
846
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
847
+        if ($enabled) {
848
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
849
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
850
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
851
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
852
+        }
853
+    }
854
+
855
+    private static function registerAccountHooks() {
856
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
857
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
858
+    }
859
+
860
+    /**
861
+     * register hooks for the filesystem
862
+     */
863
+    public static function registerFilesystemHooks() {
864
+        // Check for blacklisted files
865
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
866
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
867
+    }
868
+
869
+    /**
870
+     * register hooks for sharing
871
+     */
872
+    public static function registerShareHooks() {
873
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
874
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
875
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
876
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
877
+        }
878
+    }
879
+
880
+    protected static function registerAutoloaderCache() {
881
+        // The class loader takes an optional low-latency cache, which MUST be
882
+        // namespaced. The instanceid is used for namespacing, but might be
883
+        // unavailable at this point. Furthermore, it might not be possible to
884
+        // generate an instanceid via \OC_Util::getInstanceId() because the
885
+        // config file may not be writable. As such, we only register a class
886
+        // loader cache if instanceid is available without trying to create one.
887
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
888
+        if ($instanceId) {
889
+            try {
890
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
891
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
892
+            } catch (\Exception $ex) {
893
+            }
894
+        }
895
+    }
896
+
897
+    /**
898
+     * Handle the request
899
+     */
900
+    public static function handleRequest() {
901
+
902
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
903
+        $systemConfig = \OC::$server->getSystemConfig();
904
+        // load all the classpaths from the enabled apps so they are available
905
+        // in the routing files of each app
906
+        OC::loadAppClassPaths();
907
+
908
+        // Check if Nextcloud is installed or in maintenance (update) mode
909
+        if (!$systemConfig->getValue('installed', false)) {
910
+            \OC::$server->getSession()->clear();
911
+            $setupHelper = new OC\Setup(
912
+                $systemConfig,
913
+                \OC::$server->getIniWrapper(),
914
+                \OC::$server->getL10N('lib'),
915
+                \OC::$server->query(\OCP\Defaults::class),
916
+                \OC::$server->getLogger(),
917
+                \OC::$server->getSecureRandom(),
918
+                \OC::$server->query(\OC\Installer::class)
919
+            );
920
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
921
+            $controller->run($_POST);
922
+            exit();
923
+        }
924
+
925
+        $request = \OC::$server->getRequest();
926
+        $requestPath = $request->getRawPathInfo();
927
+        if ($requestPath === '/heartbeat') {
928
+            return;
929
+        }
930
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
931
+            self::checkMaintenanceMode();
932
+
933
+            if (\OCP\Util::needUpgrade()) {
934
+                if (function_exists('opcache_reset')) {
935
+                    opcache_reset();
936
+                }
937
+                if (!$systemConfig->getValue('maintenance', false)) {
938
+                    self::printUpgradePage($systemConfig);
939
+                    exit();
940
+                }
941
+            }
942
+        }
943
+
944
+        // emergency app disabling
945
+        if ($requestPath === '/disableapp'
946
+            && $request->getMethod() === 'POST'
947
+            && ((array)$request->getParam('appid')) !== ''
948
+        ) {
949
+            \OC_JSON::callCheck();
950
+            \OC_JSON::checkAdminUser();
951
+            $appIds = (array)$request->getParam('appid');
952
+            foreach($appIds as $appId) {
953
+                $appId = \OC_App::cleanAppId($appId);
954
+                \OC::$server->getAppManager()->disableApp($appId);
955
+            }
956
+            \OC_JSON::success();
957
+            exit();
958
+        }
959
+
960
+        // Always load authentication apps
961
+        OC_App::loadApps(['authentication']);
962
+
963
+        // Load minimum set of apps
964
+        if (!\OCP\Util::needUpgrade()
965
+            && !$systemConfig->getValue('maintenance', false)) {
966
+            // For logged-in users: Load everything
967
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
968
+                OC_App::loadApps();
969
+            } else {
970
+                // For guests: Load only filesystem and logging
971
+                OC_App::loadApps(array('filesystem', 'logging'));
972
+                self::handleLogin($request);
973
+            }
974
+        }
975
+
976
+        if (!self::$CLI) {
977
+            try {
978
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
979
+                    OC_App::loadApps(array('filesystem', 'logging'));
980
+                    OC_App::loadApps();
981
+                }
982
+                OC_Util::setupFS();
983
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
984
+                return;
985
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
986
+                //header('HTTP/1.0 404 Not Found');
987
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
988
+                OC_Response::setStatus(405);
989
+                return;
990
+            }
991
+        }
992
+
993
+        // Handle WebDAV
994
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
995
+            // not allowed any more to prevent people
996
+            // mounting this root directly.
997
+            // Users need to mount remote.php/webdav instead.
998
+            header('HTTP/1.1 405 Method Not Allowed');
999
+            header('Status: 405 Method Not Allowed');
1000
+            return;
1001
+        }
1002
+
1003
+        // Someone is logged in
1004
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1005
+            OC_App::loadApps();
1006
+            OC_User::setupBackends();
1007
+            OC_Util::setupFS();
1008
+            // FIXME
1009
+            // Redirect to default application
1010
+            OC_Util::redirectToDefaultPage();
1011
+        } else {
1012
+            // Not handled and not logged in
1013
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1014
+        }
1015
+    }
1016
+
1017
+    /**
1018
+     * Check login: apache auth, auth token, basic auth
1019
+     *
1020
+     * @param OCP\IRequest $request
1021
+     * @return boolean
1022
+     */
1023
+    static function handleLogin(OCP\IRequest $request) {
1024
+        $userSession = self::$server->getUserSession();
1025
+        if (OC_User::handleApacheAuth()) {
1026
+            return true;
1027
+        }
1028
+        if ($userSession->tryTokenLogin($request)) {
1029
+            return true;
1030
+        }
1031
+        if (isset($_COOKIE['nc_username'])
1032
+            && isset($_COOKIE['nc_token'])
1033
+            && isset($_COOKIE['nc_session_id'])
1034
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1035
+            return true;
1036
+        }
1037
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1038
+            return true;
1039
+        }
1040
+        return false;
1041
+    }
1042
+
1043
+    protected static function handleAuthHeaders() {
1044
+        //copy http auth headers for apache+php-fcgid work around
1045
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1046
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1047
+        }
1048
+
1049
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1050
+        $vars = array(
1051
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1052
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1053
+        );
1054
+        foreach ($vars as $var) {
1055
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1056
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1057
+                $_SERVER['PHP_AUTH_USER'] = $name;
1058
+                $_SERVER['PHP_AUTH_PW'] = $password;
1059
+                break;
1060
+            }
1061
+        }
1062
+    }
1063 1063
 }
1064 1064
 
1065 1065
 OC::init();
Please login to merge, or discard this patch.
lib/autoloader.php 1 patch
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -37,151 +37,151 @@
 block discarded – undo
37 37
 use OCP\ILogger;
38 38
 
39 39
 class Autoloader {
40
-	/** @var bool */
41
-	private $useGlobalClassPath = true;
42
-	/** @var array */
43
-	private $validRoots = [];
44
-
45
-	/**
46
-	 * Optional low-latency memory cache for class to path mapping.
47
-	 *
48
-	 * @var \OC\Memcache\Cache
49
-	 */
50
-	protected $memoryCache;
51
-
52
-	/**
53
-	 * Autoloader constructor.
54
-	 *
55
-	 * @param string[] $validRoots
56
-	 */
57
-	public function __construct(array $validRoots) {
58
-		foreach ($validRoots as $root) {
59
-			$this->validRoots[$root] = true;
60
-		}
61
-	}
62
-
63
-	/**
64
-	 * Add a path to the list of valid php roots for auto loading
65
-	 *
66
-	 * @param string $root
67
-	 */
68
-	public function addValidRoot(string $root) {
69
-		$root = stream_resolve_include_path($root);
70
-		$this->validRoots[$root] = true;
71
-	}
72
-
73
-	/**
74
-	 * disable the usage of the global classpath \OC::$CLASSPATH
75
-	 */
76
-	public function disableGlobalClassPath() {
77
-		$this->useGlobalClassPath = false;
78
-	}
79
-
80
-	/**
81
-	 * enable the usage of the global classpath \OC::$CLASSPATH
82
-	 */
83
-	public function enableGlobalClassPath() {
84
-		$this->useGlobalClassPath = true;
85
-	}
86
-
87
-	/**
88
-	 * get the possible paths for a class
89
-	 *
90
-	 * @param string $class
91
-	 * @return array an array of possible paths
92
-	 */
93
-	public function findClass(string $class): array {
94
-		$class = trim($class, '\\');
95
-
96
-		$paths = [];
97
-		if ($this->useGlobalClassPath && array_key_exists($class, \OC::$CLASSPATH)) {
98
-			$paths[] = \OC::$CLASSPATH[$class];
99
-			/**
100
-			 * @TODO: Remove this when necessary
101
-			 * Remove "apps/" from inclusion path for smooth migration to multi app dir
102
-			 */
103
-			if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
104
-				\OCP\Util::writeLog('core', 'include path for class "' . $class . '" starts with "apps/"', ILogger::DEBUG);
105
-				$paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
106
-			}
107
-		} elseif (strpos($class, 'OC_') === 0) {
108
-			$paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
109
-		} elseif (strpos($class, 'OCA\\') === 0) {
110
-			list(, $app, $rest) = explode('\\', $class, 3);
111
-			$app = strtolower($app);
112
-			$appPath = \OC_App::getAppPath($app);
113
-			if ($appPath && stream_resolve_include_path($appPath)) {
114
-				$paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
115
-				// If not found in the root of the app directory, insert '/lib' after app id and try again.
116
-				$paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
117
-			}
118
-		} elseif ($class === 'Test\\TestCase') {
119
-			// This File is considered public API, so we make sure that the class
120
-			// can still be loaded, although the PSR-4 paths have not been loaded.
121
-			$paths[] = \OC::$SERVERROOT . '/tests/lib/TestCase.php';
122
-		}
123
-		return $paths;
124
-	}
125
-
126
-	/**
127
-	 * @param string $fullPath
128
-	 * @return bool
129
-	 * @throws AutoloadNotAllowedException
130
-	 */
131
-	protected function isValidPath(string $fullPath): bool {
132
-		foreach ($this->validRoots as $root => $true) {
133
-			if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
134
-				return true;
135
-			}
136
-		}
137
-		throw new AutoloadNotAllowedException($fullPath);
138
-	}
139
-
140
-	/**
141
-	 * Load the specified class
142
-	 *
143
-	 * @param string $class
144
-	 * @return bool
145
-	 * @throws AutoloadNotAllowedException
146
-	 */
147
-	public function load(string $class): bool {
148
-		$pathsToRequire = null;
149
-		if ($this->memoryCache) {
150
-			$pathsToRequire = $this->memoryCache->get($class);
151
-		}
152
-
153
-		if(class_exists($class, false)) {
154
-			return false;
155
-		}
156
-
157
-		if (!is_array($pathsToRequire)) {
158
-			// No cache or cache miss
159
-			$pathsToRequire = array();
160
-			foreach ($this->findClass($class) as $path) {
161
-				$fullPath = stream_resolve_include_path($path);
162
-				if ($fullPath && $this->isValidPath($fullPath)) {
163
-					$pathsToRequire[] = $fullPath;
164
-				}
165
-			}
166
-
167
-			if ($this->memoryCache) {
168
-				$this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
169
-			}
170
-		}
171
-
172
-		foreach ($pathsToRequire as $fullPath) {
173
-			require_once $fullPath;
174
-		}
175
-
176
-		return false;
177
-	}
178
-
179
-	/**
180
-	 * Sets the optional low-latency cache for class to path mapping.
181
-	 *
182
-	 * @param \OC\Memcache\Cache $memoryCache Instance of memory cache.
183
-	 */
184
-	public function setMemoryCache(\OC\Memcache\Cache $memoryCache = null) {
185
-		$this->memoryCache = $memoryCache;
186
-	}
40
+    /** @var bool */
41
+    private $useGlobalClassPath = true;
42
+    /** @var array */
43
+    private $validRoots = [];
44
+
45
+    /**
46
+     * Optional low-latency memory cache for class to path mapping.
47
+     *
48
+     * @var \OC\Memcache\Cache
49
+     */
50
+    protected $memoryCache;
51
+
52
+    /**
53
+     * Autoloader constructor.
54
+     *
55
+     * @param string[] $validRoots
56
+     */
57
+    public function __construct(array $validRoots) {
58
+        foreach ($validRoots as $root) {
59
+            $this->validRoots[$root] = true;
60
+        }
61
+    }
62
+
63
+    /**
64
+     * Add a path to the list of valid php roots for auto loading
65
+     *
66
+     * @param string $root
67
+     */
68
+    public function addValidRoot(string $root) {
69
+        $root = stream_resolve_include_path($root);
70
+        $this->validRoots[$root] = true;
71
+    }
72
+
73
+    /**
74
+     * disable the usage of the global classpath \OC::$CLASSPATH
75
+     */
76
+    public function disableGlobalClassPath() {
77
+        $this->useGlobalClassPath = false;
78
+    }
79
+
80
+    /**
81
+     * enable the usage of the global classpath \OC::$CLASSPATH
82
+     */
83
+    public function enableGlobalClassPath() {
84
+        $this->useGlobalClassPath = true;
85
+    }
86
+
87
+    /**
88
+     * get the possible paths for a class
89
+     *
90
+     * @param string $class
91
+     * @return array an array of possible paths
92
+     */
93
+    public function findClass(string $class): array {
94
+        $class = trim($class, '\\');
95
+
96
+        $paths = [];
97
+        if ($this->useGlobalClassPath && array_key_exists($class, \OC::$CLASSPATH)) {
98
+            $paths[] = \OC::$CLASSPATH[$class];
99
+            /**
100
+             * @TODO: Remove this when necessary
101
+             * Remove "apps/" from inclusion path for smooth migration to multi app dir
102
+             */
103
+            if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
104
+                \OCP\Util::writeLog('core', 'include path for class "' . $class . '" starts with "apps/"', ILogger::DEBUG);
105
+                $paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
106
+            }
107
+        } elseif (strpos($class, 'OC_') === 0) {
108
+            $paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
109
+        } elseif (strpos($class, 'OCA\\') === 0) {
110
+            list(, $app, $rest) = explode('\\', $class, 3);
111
+            $app = strtolower($app);
112
+            $appPath = \OC_App::getAppPath($app);
113
+            if ($appPath && stream_resolve_include_path($appPath)) {
114
+                $paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
115
+                // If not found in the root of the app directory, insert '/lib' after app id and try again.
116
+                $paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
117
+            }
118
+        } elseif ($class === 'Test\\TestCase') {
119
+            // This File is considered public API, so we make sure that the class
120
+            // can still be loaded, although the PSR-4 paths have not been loaded.
121
+            $paths[] = \OC::$SERVERROOT . '/tests/lib/TestCase.php';
122
+        }
123
+        return $paths;
124
+    }
125
+
126
+    /**
127
+     * @param string $fullPath
128
+     * @return bool
129
+     * @throws AutoloadNotAllowedException
130
+     */
131
+    protected function isValidPath(string $fullPath): bool {
132
+        foreach ($this->validRoots as $root => $true) {
133
+            if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
134
+                return true;
135
+            }
136
+        }
137
+        throw new AutoloadNotAllowedException($fullPath);
138
+    }
139
+
140
+    /**
141
+     * Load the specified class
142
+     *
143
+     * @param string $class
144
+     * @return bool
145
+     * @throws AutoloadNotAllowedException
146
+     */
147
+    public function load(string $class): bool {
148
+        $pathsToRequire = null;
149
+        if ($this->memoryCache) {
150
+            $pathsToRequire = $this->memoryCache->get($class);
151
+        }
152
+
153
+        if(class_exists($class, false)) {
154
+            return false;
155
+        }
156
+
157
+        if (!is_array($pathsToRequire)) {
158
+            // No cache or cache miss
159
+            $pathsToRequire = array();
160
+            foreach ($this->findClass($class) as $path) {
161
+                $fullPath = stream_resolve_include_path($path);
162
+                if ($fullPath && $this->isValidPath($fullPath)) {
163
+                    $pathsToRequire[] = $fullPath;
164
+                }
165
+            }
166
+
167
+            if ($this->memoryCache) {
168
+                $this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
169
+            }
170
+        }
171
+
172
+        foreach ($pathsToRequire as $fullPath) {
173
+            require_once $fullPath;
174
+        }
175
+
176
+        return false;
177
+    }
178
+
179
+    /**
180
+     * Sets the optional low-latency cache for class to path mapping.
181
+     *
182
+     * @param \OC\Memcache\Cache $memoryCache Instance of memory cache.
183
+     */
184
+    public function setMemoryCache(\OC\Memcache\Cache $memoryCache = null) {
185
+        $this->memoryCache = $memoryCache;
186
+    }
187 187
 }
Please login to merge, or discard this patch.
lib/private/Log.php 1 patch
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -55,271 +55,271 @@
 block discarded – undo
55 55
  */
56 56
 class Log implements ILogger {
57 57
 
58
-	/** @var IWriter */
59
-	private $logger;
60
-
61
-	/** @var SystemConfig */
62
-	private $config;
63
-
64
-	/** @var boolean|null cache the result of the log condition check for the request */
65
-	private $logConditionSatisfied = null;
66
-
67
-	/** @var Normalizer */
68
-	private $normalizer;
69
-
70
-	/** @var IRegistry */
71
-	private $crashReporters;
72
-
73
-	/**
74
-	 * @param IWriter $logger The logger that should be used
75
-	 * @param SystemConfig $config the system config object
76
-	 * @param Normalizer|null $normalizer
77
-	 * @param IRegistry|null $registry
78
-	 */
79
-	public function __construct(IWriter $logger, SystemConfig $config = null, $normalizer = null, IRegistry $registry = null) {
80
-		// FIXME: Add this for backwards compatibility, should be fixed at some point probably
81
-		if ($config === null) {
82
-			$config = \OC::$server->getSystemConfig();
83
-		}
84
-
85
-		$this->config = $config;
86
-		$this->logger = $logger;
87
-		if ($normalizer === null) {
88
-			$this->normalizer = new Normalizer();
89
-		} else {
90
-			$this->normalizer = $normalizer;
91
-		}
92
-		$this->crashReporters = $registry;
93
-	}
94
-
95
-	/**
96
-	 * System is unusable.
97
-	 *
98
-	 * @param string $message
99
-	 * @param array $context
100
-	 * @return void
101
-	 */
102
-	public function emergency(string $message, array $context = []) {
103
-		$this->log(ILogger::FATAL, $message, $context);
104
-	}
105
-
106
-	/**
107
-	 * Action must be taken immediately.
108
-	 *
109
-	 * Example: Entire website down, database unavailable, etc. This should
110
-	 * trigger the SMS alerts and wake you up.
111
-	 *
112
-	 * @param string $message
113
-	 * @param array $context
114
-	 * @return void
115
-	 */
116
-	public function alert(string $message, array $context = []) {
117
-		$this->log(ILogger::ERROR, $message, $context);
118
-	}
119
-
120
-	/**
121
-	 * Critical conditions.
122
-	 *
123
-	 * Example: Application component unavailable, unexpected exception.
124
-	 *
125
-	 * @param string $message
126
-	 * @param array $context
127
-	 * @return void
128
-	 */
129
-	public function critical(string $message, array $context = []) {
130
-		$this->log(ILogger::ERROR, $message, $context);
131
-	}
132
-
133
-	/**
134
-	 * Runtime errors that do not require immediate action but should typically
135
-	 * be logged and monitored.
136
-	 *
137
-	 * @param string $message
138
-	 * @param array $context
139
-	 * @return void
140
-	 */
141
-	public function error(string $message, array $context = []) {
142
-		$this->log(ILogger::ERROR, $message, $context);
143
-	}
144
-
145
-	/**
146
-	 * Exceptional occurrences that are not errors.
147
-	 *
148
-	 * Example: Use of deprecated APIs, poor use of an API, undesirable things
149
-	 * that are not necessarily wrong.
150
-	 *
151
-	 * @param string $message
152
-	 * @param array $context
153
-	 * @return void
154
-	 */
155
-	public function warning(string $message, array $context = []) {
156
-		$this->log(ILogger::WARN, $message, $context);
157
-	}
158
-
159
-	/**
160
-	 * Normal but significant events.
161
-	 *
162
-	 * @param string $message
163
-	 * @param array $context
164
-	 * @return void
165
-	 */
166
-	public function notice(string $message, array $context = []) {
167
-		$this->log(ILogger::INFO, $message, $context);
168
-	}
169
-
170
-	/**
171
-	 * Interesting events.
172
-	 *
173
-	 * Example: User logs in, SQL logs.
174
-	 *
175
-	 * @param string $message
176
-	 * @param array $context
177
-	 * @return void
178
-	 */
179
-	public function info(string $message, array $context = []) {
180
-		$this->log(ILogger::INFO, $message, $context);
181
-	}
182
-
183
-	/**
184
-	 * Detailed debug information.
185
-	 *
186
-	 * @param string $message
187
-	 * @param array $context
188
-	 * @return void
189
-	 */
190
-	public function debug(string $message, array $context = []) {
191
-		$this->log(ILogger::DEBUG, $message, $context);
192
-	}
193
-
194
-
195
-	/**
196
-	 * Logs with an arbitrary level.
197
-	 *
198
-	 * @param int $level
199
-	 * @param string $message
200
-	 * @param array $context
201
-	 * @return void
202
-	 */
203
-	public function log(int $level, string $message, array $context = []) {
204
-		$minLevel = $this->getLogLevel($context);
205
-
206
-		array_walk($context, [$this->normalizer, 'format']);
207
-
208
-		$app = $context['app'] ?? 'no app in context';
209
-
210
-		// interpolate $message as defined in PSR-3
211
-		$replace = [];
212
-		foreach ($context as $key => $val) {
213
-			$replace['{' . $key . '}'] = $val;
214
-		}
215
-		$message = strtr($message, $replace);
216
-
217
-		if ($level >= $minLevel) {
218
-			$this->writeLog($app, $message, $level);
219
-		}
220
-	}
221
-
222
-	private function getLogLevel($context) {
223
-		/**
224
-		 * check for a special log condition - this enables an increased log on
225
-		 * a per request/user base
226
-		 */
227
-		if ($this->logConditionSatisfied === null) {
228
-			// default to false to just process this once per request
229
-			$this->logConditionSatisfied = false;
230
-			if (!empty($logCondition)) {
231
-
232
-				// check for secret token in the request
233
-				if (isset($logCondition['shared_secret'])) {
234
-					$request = \OC::$server->getRequest();
235
-
236
-					// if token is found in the request change set the log condition to satisfied
237
-					if ($request && hash_equals($logCondition['shared_secret'], $request->getParam('log_secret', ''))) {
238
-						$this->logConditionSatisfied = true;
239
-					}
240
-				}
241
-
242
-				// check for user
243
-				if (isset($logCondition['users'])) {
244
-					$user = \OC::$server->getUserSession()->getUser();
245
-
246
-					// if the user matches set the log condition to satisfied
247
-					if ($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
248
-						$this->logConditionSatisfied = true;
249
-					}
250
-				}
251
-			}
252
-		}
253
-
254
-		// if log condition is satisfied change the required log level to DEBUG
255
-		if ($this->logConditionSatisfied) {
256
-			return ILogger::DEBUG;
257
-		}
258
-
259
-		if (isset($context['app'])) {
260
-			$logCondition = $this->config->getValue('log.condition', []);
261
-			$app = $context['app'];
262
-
263
-			/**
264
-			 * check log condition based on the context of each log message
265
-			 * once this is met -> change the required log level to debug
266
-			 */
267
-			if (!empty($logCondition)
268
-				&& isset($logCondition['apps'])
269
-				&& in_array($app, $logCondition['apps'], true)) {
270
-				return ILogger::DEBUG;
271
-			}
272
-		}
273
-
274
-		return min($this->config->getValue('loglevel', ILogger::WARN), ILogger::FATAL);
275
-	}
276
-
277
-	/**
278
-	 * Logs an exception very detailed
279
-	 *
280
-	 * @param \Exception|\Throwable $exception
281
-	 * @param array $context
282
-	 * @return void
283
-	 * @since 8.2.0
284
-	 */
285
-	public function logException(\Throwable $exception, array $context = []) {
286
-		$app = $context['app'] ?? 'no app in context';
287
-		$level = $context['level'] ?? ILogger::ERROR;
288
-
289
-		$serializer = new ExceptionSerializer();
290
-		$data = $serializer->serializeException($exception);
291
-		$data['CustomMessage'] = $context['message'] ?? '--';
292
-
293
-		$minLevel = $this->getLogLevel($context);
294
-
295
-		array_walk($context, [$this->normalizer, 'format']);
296
-
297
-		if ($level >= $minLevel) {
298
-			if (!$this->logger instanceof IFileBased) {
299
-				$data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);
300
-			}
301
-			$this->writeLog($app, $data, $level);
302
-		}
303
-
304
-		$context['level'] = $level;
305
-		if (!is_null($this->crashReporters)) {
306
-			$this->crashReporters->delegateReport($exception, $context);
307
-		}
308
-	}
309
-
310
-	/**
311
-	 * @param string $app
312
-	 * @param string|array $entry
313
-	 * @param int $level
314
-	 */
315
-	protected function writeLog(string $app, $entry, int $level) {
316
-		$this->logger->write($app, $entry, $level);
317
-	}
318
-
319
-	public function getLogPath():string {
320
-		if($this->logger instanceof IFileBased) {
321
-			return $this->logger->getLogFilePath();
322
-		}
323
-		throw new \RuntimeException('Log implementation has no path');
324
-	}
58
+    /** @var IWriter */
59
+    private $logger;
60
+
61
+    /** @var SystemConfig */
62
+    private $config;
63
+
64
+    /** @var boolean|null cache the result of the log condition check for the request */
65
+    private $logConditionSatisfied = null;
66
+
67
+    /** @var Normalizer */
68
+    private $normalizer;
69
+
70
+    /** @var IRegistry */
71
+    private $crashReporters;
72
+
73
+    /**
74
+     * @param IWriter $logger The logger that should be used
75
+     * @param SystemConfig $config the system config object
76
+     * @param Normalizer|null $normalizer
77
+     * @param IRegistry|null $registry
78
+     */
79
+    public function __construct(IWriter $logger, SystemConfig $config = null, $normalizer = null, IRegistry $registry = null) {
80
+        // FIXME: Add this for backwards compatibility, should be fixed at some point probably
81
+        if ($config === null) {
82
+            $config = \OC::$server->getSystemConfig();
83
+        }
84
+
85
+        $this->config = $config;
86
+        $this->logger = $logger;
87
+        if ($normalizer === null) {
88
+            $this->normalizer = new Normalizer();
89
+        } else {
90
+            $this->normalizer = $normalizer;
91
+        }
92
+        $this->crashReporters = $registry;
93
+    }
94
+
95
+    /**
96
+     * System is unusable.
97
+     *
98
+     * @param string $message
99
+     * @param array $context
100
+     * @return void
101
+     */
102
+    public function emergency(string $message, array $context = []) {
103
+        $this->log(ILogger::FATAL, $message, $context);
104
+    }
105
+
106
+    /**
107
+     * Action must be taken immediately.
108
+     *
109
+     * Example: Entire website down, database unavailable, etc. This should
110
+     * trigger the SMS alerts and wake you up.
111
+     *
112
+     * @param string $message
113
+     * @param array $context
114
+     * @return void
115
+     */
116
+    public function alert(string $message, array $context = []) {
117
+        $this->log(ILogger::ERROR, $message, $context);
118
+    }
119
+
120
+    /**
121
+     * Critical conditions.
122
+     *
123
+     * Example: Application component unavailable, unexpected exception.
124
+     *
125
+     * @param string $message
126
+     * @param array $context
127
+     * @return void
128
+     */
129
+    public function critical(string $message, array $context = []) {
130
+        $this->log(ILogger::ERROR, $message, $context);
131
+    }
132
+
133
+    /**
134
+     * Runtime errors that do not require immediate action but should typically
135
+     * be logged and monitored.
136
+     *
137
+     * @param string $message
138
+     * @param array $context
139
+     * @return void
140
+     */
141
+    public function error(string $message, array $context = []) {
142
+        $this->log(ILogger::ERROR, $message, $context);
143
+    }
144
+
145
+    /**
146
+     * Exceptional occurrences that are not errors.
147
+     *
148
+     * Example: Use of deprecated APIs, poor use of an API, undesirable things
149
+     * that are not necessarily wrong.
150
+     *
151
+     * @param string $message
152
+     * @param array $context
153
+     * @return void
154
+     */
155
+    public function warning(string $message, array $context = []) {
156
+        $this->log(ILogger::WARN, $message, $context);
157
+    }
158
+
159
+    /**
160
+     * Normal but significant events.
161
+     *
162
+     * @param string $message
163
+     * @param array $context
164
+     * @return void
165
+     */
166
+    public function notice(string $message, array $context = []) {
167
+        $this->log(ILogger::INFO, $message, $context);
168
+    }
169
+
170
+    /**
171
+     * Interesting events.
172
+     *
173
+     * Example: User logs in, SQL logs.
174
+     *
175
+     * @param string $message
176
+     * @param array $context
177
+     * @return void
178
+     */
179
+    public function info(string $message, array $context = []) {
180
+        $this->log(ILogger::INFO, $message, $context);
181
+    }
182
+
183
+    /**
184
+     * Detailed debug information.
185
+     *
186
+     * @param string $message
187
+     * @param array $context
188
+     * @return void
189
+     */
190
+    public function debug(string $message, array $context = []) {
191
+        $this->log(ILogger::DEBUG, $message, $context);
192
+    }
193
+
194
+
195
+    /**
196
+     * Logs with an arbitrary level.
197
+     *
198
+     * @param int $level
199
+     * @param string $message
200
+     * @param array $context
201
+     * @return void
202
+     */
203
+    public function log(int $level, string $message, array $context = []) {
204
+        $minLevel = $this->getLogLevel($context);
205
+
206
+        array_walk($context, [$this->normalizer, 'format']);
207
+
208
+        $app = $context['app'] ?? 'no app in context';
209
+
210
+        // interpolate $message as defined in PSR-3
211
+        $replace = [];
212
+        foreach ($context as $key => $val) {
213
+            $replace['{' . $key . '}'] = $val;
214
+        }
215
+        $message = strtr($message, $replace);
216
+
217
+        if ($level >= $minLevel) {
218
+            $this->writeLog($app, $message, $level);
219
+        }
220
+    }
221
+
222
+    private function getLogLevel($context) {
223
+        /**
224
+         * check for a special log condition - this enables an increased log on
225
+         * a per request/user base
226
+         */
227
+        if ($this->logConditionSatisfied === null) {
228
+            // default to false to just process this once per request
229
+            $this->logConditionSatisfied = false;
230
+            if (!empty($logCondition)) {
231
+
232
+                // check for secret token in the request
233
+                if (isset($logCondition['shared_secret'])) {
234
+                    $request = \OC::$server->getRequest();
235
+
236
+                    // if token is found in the request change set the log condition to satisfied
237
+                    if ($request && hash_equals($logCondition['shared_secret'], $request->getParam('log_secret', ''))) {
238
+                        $this->logConditionSatisfied = true;
239
+                    }
240
+                }
241
+
242
+                // check for user
243
+                if (isset($logCondition['users'])) {
244
+                    $user = \OC::$server->getUserSession()->getUser();
245
+
246
+                    // if the user matches set the log condition to satisfied
247
+                    if ($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
248
+                        $this->logConditionSatisfied = true;
249
+                    }
250
+                }
251
+            }
252
+        }
253
+
254
+        // if log condition is satisfied change the required log level to DEBUG
255
+        if ($this->logConditionSatisfied) {
256
+            return ILogger::DEBUG;
257
+        }
258
+
259
+        if (isset($context['app'])) {
260
+            $logCondition = $this->config->getValue('log.condition', []);
261
+            $app = $context['app'];
262
+
263
+            /**
264
+             * check log condition based on the context of each log message
265
+             * once this is met -> change the required log level to debug
266
+             */
267
+            if (!empty($logCondition)
268
+                && isset($logCondition['apps'])
269
+                && in_array($app, $logCondition['apps'], true)) {
270
+                return ILogger::DEBUG;
271
+            }
272
+        }
273
+
274
+        return min($this->config->getValue('loglevel', ILogger::WARN), ILogger::FATAL);
275
+    }
276
+
277
+    /**
278
+     * Logs an exception very detailed
279
+     *
280
+     * @param \Exception|\Throwable $exception
281
+     * @param array $context
282
+     * @return void
283
+     * @since 8.2.0
284
+     */
285
+    public function logException(\Throwable $exception, array $context = []) {
286
+        $app = $context['app'] ?? 'no app in context';
287
+        $level = $context['level'] ?? ILogger::ERROR;
288
+
289
+        $serializer = new ExceptionSerializer();
290
+        $data = $serializer->serializeException($exception);
291
+        $data['CustomMessage'] = $context['message'] ?? '--';
292
+
293
+        $minLevel = $this->getLogLevel($context);
294
+
295
+        array_walk($context, [$this->normalizer, 'format']);
296
+
297
+        if ($level >= $minLevel) {
298
+            if (!$this->logger instanceof IFileBased) {
299
+                $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);
300
+            }
301
+            $this->writeLog($app, $data, $level);
302
+        }
303
+
304
+        $context['level'] = $level;
305
+        if (!is_null($this->crashReporters)) {
306
+            $this->crashReporters->delegateReport($exception, $context);
307
+        }
308
+    }
309
+
310
+    /**
311
+     * @param string $app
312
+     * @param string|array $entry
313
+     * @param int $level
314
+     */
315
+    protected function writeLog(string $app, $entry, int $level) {
316
+        $this->logger->write($app, $entry, $level);
317
+    }
318
+
319
+    public function getLogPath():string {
320
+        if($this->logger instanceof IFileBased) {
321
+            return $this->logger->getLogFilePath();
322
+        }
323
+        throw new \RuntimeException('Log implementation has no path');
324
+    }
325 325
 }
Please login to merge, or discard this patch.
lib/private/DateTimeZone.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -30,100 +30,100 @@
 block discarded – undo
30 30
 use OCP\ISession;
31 31
 
32 32
 class DateTimeZone implements IDateTimeZone {
33
-	/** @var IConfig */
34
-	protected $config;
33
+    /** @var IConfig */
34
+    protected $config;
35 35
 
36
-	/** @var ISession */
37
-	protected $session;
36
+    /** @var ISession */
37
+    protected $session;
38 38
 
39
-	/**
40
-	 * Constructor
41
-	 *
42
-	 * @param IConfig $config
43
-	 * @param ISession $session
44
-	 */
45
-	public function __construct(IConfig $config, ISession $session) {
46
-		$this->config = $config;
47
-		$this->session = $session;
48
-	}
39
+    /**
40
+     * Constructor
41
+     *
42
+     * @param IConfig $config
43
+     * @param ISession $session
44
+     */
45
+    public function __construct(IConfig $config, ISession $session) {
46
+        $this->config = $config;
47
+        $this->session = $session;
48
+    }
49 49
 
50
-	/**
51
-	 * Get the timezone of the current user, based on his session information and config data
52
-	 *
53
-	 * @param bool|int $timestamp
54
-	 * @return \DateTimeZone
55
-	 */
56
-	public function getTimeZone($timestamp = false) {
57
-		$timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null);
58
-		if ($timeZone === null) {
59
-			if ($this->session->exists('timezone')) {
60
-				return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp);
61
-			}
62
-			$timeZone = $this->getDefaultTimeZone();
63
-		}
50
+    /**
51
+     * Get the timezone of the current user, based on his session information and config data
52
+     *
53
+     * @param bool|int $timestamp
54
+     * @return \DateTimeZone
55
+     */
56
+    public function getTimeZone($timestamp = false) {
57
+        $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null);
58
+        if ($timeZone === null) {
59
+            if ($this->session->exists('timezone')) {
60
+                return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp);
61
+            }
62
+            $timeZone = $this->getDefaultTimeZone();
63
+        }
64 64
 
65
-		try {
66
-			return new \DateTimeZone($timeZone);
67
-		} catch (\Exception $e) {
68
-			\OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", ILogger::DEBUG);
69
-			return new \DateTimeZone($this->getDefaultTimeZone());
70
-		}
71
-	}
65
+        try {
66
+            return new \DateTimeZone($timeZone);
67
+        } catch (\Exception $e) {
68
+            \OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", ILogger::DEBUG);
69
+            return new \DateTimeZone($this->getDefaultTimeZone());
70
+        }
71
+    }
72 72
 
73
-	/**
74
-	 * Guess the DateTimeZone for a given offset
75
-	 *
76
-	 * We first try to find a Etc/GMT* timezone, if that does not exist,
77
-	 * we try to find it manually, before falling back to UTC.
78
-	 *
79
-	 * @param mixed $offset
80
-	 * @param bool|int $timestamp
81
-	 * @return \DateTimeZone
82
-	 */
83
-	protected function guessTimeZoneFromOffset($offset, $timestamp) {
84
-		try {
85
-			// Note: the timeZone name is the inverse to the offset,
86
-			// so a positive offset means negative timeZone
87
-			// and the other way around.
88
-			if ($offset > 0) {
89
-				$timeZone = 'Etc/GMT-' . $offset;
90
-			} else {
91
-				$timeZone = 'Etc/GMT+' . abs($offset);
92
-			}
73
+    /**
74
+     * Guess the DateTimeZone for a given offset
75
+     *
76
+     * We first try to find a Etc/GMT* timezone, if that does not exist,
77
+     * we try to find it manually, before falling back to UTC.
78
+     *
79
+     * @param mixed $offset
80
+     * @param bool|int $timestamp
81
+     * @return \DateTimeZone
82
+     */
83
+    protected function guessTimeZoneFromOffset($offset, $timestamp) {
84
+        try {
85
+            // Note: the timeZone name is the inverse to the offset,
86
+            // so a positive offset means negative timeZone
87
+            // and the other way around.
88
+            if ($offset > 0) {
89
+                $timeZone = 'Etc/GMT-' . $offset;
90
+            } else {
91
+                $timeZone = 'Etc/GMT+' . abs($offset);
92
+            }
93 93
 
94
-			return new \DateTimeZone($timeZone);
95
-		} catch (\Exception $e) {
96
-			// If the offset has no Etc/GMT* timezone,
97
-			// we try to guess one timezone that has the same offset
98
-			foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
99
-				$dtz = new \DateTimeZone($timeZone);
100
-				$dateTime = new \DateTime();
94
+            return new \DateTimeZone($timeZone);
95
+        } catch (\Exception $e) {
96
+            // If the offset has no Etc/GMT* timezone,
97
+            // we try to guess one timezone that has the same offset
98
+            foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
99
+                $dtz = new \DateTimeZone($timeZone);
100
+                $dateTime = new \DateTime();
101 101
 
102
-				if ($timestamp !== false) {
103
-					$dateTime->setTimestamp($timestamp);
104
-				}
102
+                if ($timestamp !== false) {
103
+                    $dateTime->setTimestamp($timestamp);
104
+                }
105 105
 
106
-				$dtOffset = $dtz->getOffset($dateTime);
107
-				if ($dtOffset == 3600 * $offset) {
108
-					return $dtz;
109
-				}
110
-			}
106
+                $dtOffset = $dtz->getOffset($dateTime);
107
+                if ($dtOffset == 3600 * $offset) {
108
+                    return $dtz;
109
+                }
110
+            }
111 111
 
112
-			// No timezone found, fallback to UTC
113
-			\OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", ILogger::DEBUG);
114
-			return new \DateTimeZone($this->getDefaultTimeZone());
115
-		}
116
-	}
112
+            // No timezone found, fallback to UTC
113
+            \OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", ILogger::DEBUG);
114
+            return new \DateTimeZone($this->getDefaultTimeZone());
115
+        }
116
+    }
117 117
 
118
-	/**
119
-	 * Get the default timezone of the server
120
-	 *
121
-	 * Falls back to UTC if it is not yet set.
122
-	 * 
123
-	 * @return string
124
-	 */
125
-	protected function getDefaultTimeZone() {
126
-		$serverTimeZone = date_default_timezone_get();
127
-		return $serverTimeZone ?: 'UTC';
128
-	}
118
+    /**
119
+     * Get the default timezone of the server
120
+     *
121
+     * Falls back to UTC if it is not yet set.
122
+     * 
123
+     * @return string
124
+     */
125
+    protected function getDefaultTimeZone() {
126
+        $serverTimeZone = date_default_timezone_get();
127
+        return $serverTimeZone ?: 'UTC';
128
+    }
129 129
 }
Please login to merge, or discard this patch.
lib/private/Tags.php 1 patch
Indentation   +803 added lines, -803 removed lines patch added patch discarded remove patch
@@ -51,807 +51,807 @@
 block discarded – undo
51 51
 
52 52
 class Tags implements \OCP\ITags {
53 53
 
54
-	/**
55
-	 * Tags
56
-	 *
57
-	 * @var array
58
-	 */
59
-	private $tags = array();
60
-
61
-	/**
62
-	 * Used for storing objectid/categoryname pairs while rescanning.
63
-	 *
64
-	 * @var array
65
-	 */
66
-	private static $relations = array();
67
-
68
-	/**
69
-	 * Type
70
-	 *
71
-	 * @var string
72
-	 */
73
-	private $type;
74
-
75
-	/**
76
-	 * User
77
-	 *
78
-	 * @var string
79
-	 */
80
-	private $user;
81
-
82
-	/**
83
-	 * Are we including tags for shared items?
84
-	 *
85
-	 * @var bool
86
-	 */
87
-	private $includeShared = false;
88
-
89
-	/**
90
-	 * The current user, plus any owners of the items shared with the current
91
-	 * user, if $this->includeShared === true.
92
-	 *
93
-	 * @var array
94
-	 */
95
-	private $owners = array();
96
-
97
-	/**
98
-	 * The Mapper we're using to communicate our Tag objects to the database.
99
-	 *
100
-	 * @var TagMapper
101
-	 */
102
-	private $mapper;
103
-
104
-	/**
105
-	 * The sharing backend for objects of $this->type. Required if
106
-	 * $this->includeShared === true to determine ownership of items.
107
-	 *
108
-	 * @var \OCP\Share_Backend
109
-	 */
110
-	private $backend;
111
-
112
-	const TAG_TABLE = '*PREFIX*vcategory';
113
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
-
115
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
116
-
117
-	/**
118
-	* Constructor.
119
-	*
120
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
-	* @param string $user The user whose data the object will operate on.
122
-	* @param string $type The type of items for which tags will be loaded.
123
-	* @param array $defaultTags Tags that should be created at construction.
124
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
-	*/
126
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
-		$this->mapper = $mapper;
128
-		$this->user = $user;
129
-		$this->type = $type;
130
-		$this->includeShared = $includeShared;
131
-		$this->owners = array($this->user);
132
-		if ($this->includeShared) {
133
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
-			$this->backend = \OC\Share\Share::getBackend($this->type);
135
-		}
136
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
-
138
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
-			$this->addMultiple($defaultTags, true);
140
-		}
141
-	}
142
-
143
-	/**
144
-	* Check if any tags are saved for this type and user.
145
-	*
146
-	* @return boolean
147
-	*/
148
-	public function isEmpty() {
149
-		return count($this->tags) === 0;
150
-	}
151
-
152
-	/**
153
-	* Returns an array mapping a given tag's properties to its values:
154
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
-	*
156
-	* @param string $id The ID of the tag that is going to be mapped
157
-	* @return array|false
158
-	*/
159
-	public function getTag($id) {
160
-		$key = $this->getTagById($id);
161
-		if ($key !== false) {
162
-			return $this->tagMap($this->tags[$key]);
163
-		}
164
-		return false;
165
-	}
166
-
167
-	/**
168
-	* Get the tags for a specific user.
169
-	*
170
-	* This returns an array with maps containing each tag's properties:
171
-	* [
172
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
-	* ]
175
-	*
176
-	* @return array
177
-	*/
178
-	public function getTags() {
179
-		if(!count($this->tags)) {
180
-			return array();
181
-		}
182
-
183
-		usort($this->tags, function($a, $b) {
184
-			return strnatcasecmp($a->getName(), $b->getName());
185
-		});
186
-		$tagMap = array();
187
-
188
-		foreach($this->tags as $tag) {
189
-			if($tag->getName() !== self::TAG_FAVORITE) {
190
-				$tagMap[] = $this->tagMap($tag);
191
-			}
192
-		}
193
-		return $tagMap;
194
-
195
-	}
196
-
197
-	/**
198
-	* Return only the tags owned by the given user, omitting any tags shared
199
-	* by other users.
200
-	*
201
-	* @param string $user The user whose tags are to be checked.
202
-	* @return array An array of Tag objects.
203
-	*/
204
-	public function getTagsForUser($user) {
205
-		return array_filter($this->tags,
206
-			function($tag) use($user) {
207
-				return $tag->getOwner() === $user;
208
-			}
209
-		);
210
-	}
211
-
212
-	/**
213
-	 * Get the list of tags for the given ids.
214
-	 *
215
-	 * @param array $objIds array of object ids
216
-	 * @return array|boolean of tags id as key to array of tag names
217
-	 * or false if an error occurred
218
-	 */
219
-	public function getTagsForObjects(array $objIds) {
220
-		$entries = array();
221
-
222
-		try {
223
-			$conn = \OC::$server->getDatabaseConnection();
224
-			$chunks = array_chunk($objIds, 900, false);
225
-			foreach ($chunks as $chunk) {
226
-				$result = $conn->executeQuery(
227
-					'SELECT `category`, `categoryid`, `objid` ' .
228
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
-					array($this->user, $this->type, $chunk),
231
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
-				);
233
-				while ($row = $result->fetch()) {
234
-					$objId = (int)$row['objid'];
235
-					if (!isset($entries[$objId])) {
236
-						$entries[$objId] = array();
237
-					}
238
-					$entries[$objId][] = $row['category'];
239
-				}
240
-				if ($result === null) {
241
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
-					return false;
243
-				}
244
-			}
245
-		} catch(\Exception $e) {
246
-			\OC::$server->getLogger()->logException($e, [
247
-				'message' => __METHOD__,
248
-				'level' => ILogger::ERROR,
249
-				'app' => 'core',
250
-			]);
251
-			return false;
252
-		}
253
-
254
-		return $entries;
255
-	}
256
-
257
-	/**
258
-	* Get the a list if items tagged with $tag.
259
-	*
260
-	* Throws an exception if the tag could not be found.
261
-	*
262
-	* @param string $tag Tag id or name.
263
-	* @return array|false An array of object ids or false on error.
264
-	* @throws \Exception
265
-	*/
266
-	public function getIdsForTag($tag) {
267
-		$result = null;
268
-		$tagId = false;
269
-		if(is_numeric($tag)) {
270
-			$tagId = $tag;
271
-		} elseif(is_string($tag)) {
272
-			$tag = trim($tag);
273
-			if($tag === '') {
274
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
-				return false;
276
-			}
277
-			$tagId = $this->getTagId($tag);
278
-		}
279
-
280
-		if($tagId === false) {
281
-			$l10n = \OC::$server->getL10N('core');
282
-			throw new \Exception(
283
-				$l10n->t('Could not find category "%s"', [$tag])
284
-			);
285
-		}
286
-
287
-		$ids = array();
288
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
-			. '` WHERE `categoryid` = ?';
290
-
291
-		try {
292
-			$stmt = \OC_DB::prepare($sql);
293
-			$result = $stmt->execute(array($tagId));
294
-			if ($result === null) {
295
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
-				return false;
297
-			}
298
-		} catch(\Exception $e) {
299
-			\OC::$server->getLogger()->logException($e, [
300
-				'message' => __METHOD__,
301
-				'level' => ILogger::ERROR,
302
-				'app' => 'core',
303
-			]);
304
-			return false;
305
-		}
306
-
307
-		if(!is_null($result)) {
308
-			while( $row = $result->fetchRow()) {
309
-				$id = (int)$row['objid'];
310
-
311
-				if ($this->includeShared) {
312
-					// We have to check if we are really allowed to access the
313
-					// items that are tagged with $tag. To that end, we ask the
314
-					// corresponding sharing backend if the item identified by $id
315
-					// is owned by any of $this->owners.
316
-					foreach ($this->owners as $owner) {
317
-						if ($this->backend->isValidSource($id, $owner)) {
318
-							$ids[] = $id;
319
-							break;
320
-						}
321
-					}
322
-				} else {
323
-					$ids[] = $id;
324
-				}
325
-			}
326
-		}
327
-
328
-		return $ids;
329
-	}
330
-
331
-	/**
332
-	* Checks whether a tag is saved for the given user,
333
-	* disregarding the ones shared with him or her.
334
-	*
335
-	* @param string $name The tag name to check for.
336
-	* @param string $user The user whose tags are to be checked.
337
-	* @return bool
338
-	*/
339
-	public function userHasTag($name, $user) {
340
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
341
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
342
-	}
343
-
344
-	/**
345
-	* Checks whether a tag is saved for or shared with the current user.
346
-	*
347
-	* @param string $name The tag name to check for.
348
-	* @return bool
349
-	*/
350
-	public function hasTag($name) {
351
-		return $this->getTagId($name) !== false;
352
-	}
353
-
354
-	/**
355
-	* Add a new tag.
356
-	*
357
-	* @param string $name A string with a name of the tag
358
-	* @return false|int the id of the added tag or false on error.
359
-	*/
360
-	public function add($name) {
361
-		$name = trim($name);
362
-
363
-		if($name === '') {
364
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
-			return false;
366
-		}
367
-		if($this->userHasTag($name, $this->user)) {
368
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
-			return false;
370
-		}
371
-		try {
372
-			$tag = new Tag($this->user, $this->type, $name);
373
-			$tag = $this->mapper->insert($tag);
374
-			$this->tags[] = $tag;
375
-		} catch(\Exception $e) {
376
-			\OC::$server->getLogger()->logException($e, [
377
-				'message' => __METHOD__,
378
-				'level' => ILogger::ERROR,
379
-				'app' => 'core',
380
-			]);
381
-			return false;
382
-		}
383
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
-		return $tag->getId();
385
-	}
386
-
387
-	/**
388
-	* Rename tag.
389
-	*
390
-	* @param string|integer $from The name or ID of the existing tag
391
-	* @param string $to The new name of the tag.
392
-	* @return bool
393
-	*/
394
-	public function rename($from, $to) {
395
-		$from = trim($from);
396
-		$to = trim($to);
397
-
398
-		if($to === '' || $from === '') {
399
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
-			return false;
401
-		}
402
-
403
-		if (is_numeric($from)) {
404
-			$key = $this->getTagById($from);
405
-		} else {
406
-			$key = $this->getTagByName($from);
407
-		}
408
-		if($key === false) {
409
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
-			return false;
411
-		}
412
-		$tag = $this->tags[$key];
413
-
414
-		if($this->userHasTag($to, $tag->getOwner())) {
415
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
-			return false;
417
-		}
418
-
419
-		try {
420
-			$tag->setName($to);
421
-			$this->tags[$key] = $this->mapper->update($tag);
422
-		} catch(\Exception $e) {
423
-			\OC::$server->getLogger()->logException($e, [
424
-				'message' => __METHOD__,
425
-				'level' => ILogger::ERROR,
426
-				'app' => 'core',
427
-			]);
428
-			return false;
429
-		}
430
-		return true;
431
-	}
432
-
433
-	/**
434
-	* Add a list of new tags.
435
-	*
436
-	* @param string[] $names A string with a name or an array of strings containing
437
-	* the name(s) of the tag(s) to add.
438
-	* @param bool $sync When true, save the tags
439
-	* @param int|null $id int Optional object id to add to this|these tag(s)
440
-	* @return bool Returns false on error.
441
-	*/
442
-	public function addMultiple($names, $sync=false, $id = null) {
443
-		if(!is_array($names)) {
444
-			$names = array($names);
445
-		}
446
-		$names = array_map('trim', $names);
447
-		array_filter($names);
448
-
449
-		$newones = array();
450
-		foreach($names as $name) {
451
-			if(!$this->hasTag($name) && $name !== '') {
452
-				$newones[] = new Tag($this->user, $this->type, $name);
453
-			}
454
-			if(!is_null($id) ) {
455
-				// Insert $objectid, $categoryid  pairs if not exist.
456
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
457
-			}
458
-		}
459
-		$this->tags = array_merge($this->tags, $newones);
460
-		if($sync === true) {
461
-			$this->save();
462
-		}
463
-
464
-		return true;
465
-	}
466
-
467
-	/**
468
-	 * Save the list of tags and their object relations
469
-	 */
470
-	protected function save() {
471
-		if(is_array($this->tags)) {
472
-			foreach($this->tags as $tag) {
473
-				try {
474
-					if (!$this->mapper->tagExists($tag)) {
475
-						$this->mapper->insert($tag);
476
-					}
477
-				} catch(\Exception $e) {
478
-					\OC::$server->getLogger()->logException($e, [
479
-						'message' => __METHOD__,
480
-						'level' => ILogger::ERROR,
481
-						'app' => 'core',
482
-					]);
483
-				}
484
-			}
485
-
486
-			// reload tags to get the proper ids.
487
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
-				ILogger::DEBUG);
490
-			// Loop through temporarily cached objectid/tagname pairs
491
-			// and save relations.
492
-			$tags = $this->tags;
493
-			// For some reason this is needed or array_search(i) will return 0..?
494
-			ksort($tags);
495
-			$dbConnection = \OC::$server->getDatabaseConnection();
496
-			foreach(self::$relations as $relation) {
497
-				$tagId = $this->getTagId($relation['tag']);
498
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
-				if($tagId) {
500
-					try {
501
-						$dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
-							array(
503
-								'objid' => $relation['objid'],
504
-								'categoryid' => $tagId,
505
-								'type' => $this->type,
506
-								));
507
-					} catch(\Exception $e) {
508
-						\OC::$server->getLogger()->logException($e, [
509
-							'message' => __METHOD__,
510
-							'level' => ILogger::ERROR,
511
-							'app' => 'core',
512
-						]);
513
-					}
514
-				}
515
-			}
516
-			self::$relations = array(); // reset
517
-		} else {
518
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
-				. print_r($this->tags, true), ILogger::ERROR);
520
-		}
521
-	}
522
-
523
-	/**
524
-	* Delete tags and tag/object relations for a user.
525
-	*
526
-	* For hooking up on post_deleteUser
527
-	*
528
-	* @param array $arguments
529
-	*/
530
-	public static function post_deleteUser($arguments) {
531
-		// Find all objectid/tagId pairs.
532
-		$result = null;
533
-		try {
534
-			$stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
-				. 'WHERE `uid` = ?');
536
-			$result = $stmt->execute(array($arguments['uid']));
537
-			if ($result === null) {
538
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
-			}
540
-		} catch(\Exception $e) {
541
-			\OC::$server->getLogger()->logException($e, [
542
-				'message' => __METHOD__,
543
-				'level' => ILogger::ERROR,
544
-				'app' => 'core',
545
-			]);
546
-		}
547
-
548
-		if(!is_null($result)) {
549
-			try {
550
-				$stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
-					. 'WHERE `categoryid` = ?');
552
-				while( $row = $result->fetchRow()) {
553
-					try {
554
-						$stmt->execute(array($row['id']));
555
-					} catch(\Exception $e) {
556
-						\OC::$server->getLogger()->logException($e, [
557
-							'message' => __METHOD__,
558
-							'level' => ILogger::ERROR,
559
-							'app' => 'core',
560
-						]);
561
-					}
562
-				}
563
-			} catch(\Exception $e) {
564
-				\OC::$server->getLogger()->logException($e, [
565
-					'message' => __METHOD__,
566
-					'level' => ILogger::ERROR,
567
-					'app' => 'core',
568
-				]);
569
-			}
570
-		}
571
-		try {
572
-			$stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
-				. 'WHERE `uid` = ?');
574
-			$result = $stmt->execute(array($arguments['uid']));
575
-			if ($result === null) {
576
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
-			}
578
-		} catch(\Exception $e) {
579
-			\OC::$server->getLogger()->logException($e, [
580
-				'message' => __METHOD__,
581
-				'level' => ILogger::ERROR,
582
-				'app' => 'core',
583
-			]);
584
-		}
585
-	}
586
-
587
-	/**
588
-	* Delete tag/object relations from the db
589
-	*
590
-	* @param array $ids The ids of the objects
591
-	* @return boolean Returns false on error.
592
-	*/
593
-	public function purgeObjects(array $ids) {
594
-		if(count($ids) === 0) {
595
-			// job done ;)
596
-			return true;
597
-		}
598
-		$updates = $ids;
599
-		try {
600
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
-			$query .= 'AND `type`= ?';
603
-			$updates[] = $this->type;
604
-			$stmt = \OC_DB::prepare($query);
605
-			$result = $stmt->execute($updates);
606
-			if ($result === null) {
607
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
-				return false;
609
-			}
610
-		} catch(\Exception $e) {
611
-			\OC::$server->getLogger()->logException($e, [
612
-				'message' => __METHOD__,
613
-				'level' => ILogger::ERROR,
614
-				'app' => 'core',
615
-			]);
616
-			return false;
617
-		}
618
-		return true;
619
-	}
620
-
621
-	/**
622
-	* Get favorites for an object type
623
-	*
624
-	* @return array|false An array of object ids.
625
-	*/
626
-	public function getFavorites() {
627
-		try {
628
-			return $this->getIdsForTag(self::TAG_FAVORITE);
629
-		} catch(\Exception $e) {
630
-			\OC::$server->getLogger()->logException($e, [
631
-				'message' => __METHOD__,
632
-				'level' => ILogger::ERROR,
633
-				'app' => 'core',
634
-			]);
635
-			return array();
636
-		}
637
-	}
638
-
639
-	/**
640
-	* Add an object to favorites
641
-	*
642
-	* @param int $objid The id of the object
643
-	* @return boolean
644
-	*/
645
-	public function addToFavorites($objid) {
646
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
-			$this->add(self::TAG_FAVORITE);
648
-		}
649
-		return $this->tagAs($objid, self::TAG_FAVORITE);
650
-	}
651
-
652
-	/**
653
-	* Remove an object from favorites
654
-	*
655
-	* @param int $objid The id of the object
656
-	* @return boolean
657
-	*/
658
-	public function removeFromFavorites($objid) {
659
-		return $this->unTag($objid, self::TAG_FAVORITE);
660
-	}
661
-
662
-	/**
663
-	* Creates a tag/object relation.
664
-	*
665
-	* @param int $objid The id of the object
666
-	* @param string $tag The id or name of the tag
667
-	* @return boolean Returns false on error.
668
-	*/
669
-	public function tagAs($objid, $tag) {
670
-		if(is_string($tag) && !is_numeric($tag)) {
671
-			$tag = trim($tag);
672
-			if($tag === '') {
673
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
-				return false;
675
-			}
676
-			if(!$this->hasTag($tag)) {
677
-				$this->add($tag);
678
-			}
679
-			$tagId =  $this->getTagId($tag);
680
-		} else {
681
-			$tagId = $tag;
682
-		}
683
-		try {
684
-			\OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
-				array(
686
-					'objid' => $objid,
687
-					'categoryid' => $tagId,
688
-					'type' => $this->type,
689
-				));
690
-		} catch(\Exception $e) {
691
-			\OC::$server->getLogger()->logException($e, [
692
-				'message' => __METHOD__,
693
-				'level' => ILogger::ERROR,
694
-				'app' => 'core',
695
-			]);
696
-			return false;
697
-		}
698
-		return true;
699
-	}
700
-
701
-	/**
702
-	* Delete single tag/object relation from the db
703
-	*
704
-	* @param int $objid The id of the object
705
-	* @param string $tag The id or name of the tag
706
-	* @return boolean
707
-	*/
708
-	public function unTag($objid, $tag) {
709
-		if(is_string($tag) && !is_numeric($tag)) {
710
-			$tag = trim($tag);
711
-			if($tag === '') {
712
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
-				return false;
714
-			}
715
-			$tagId =  $this->getTagId($tag);
716
-		} else {
717
-			$tagId = $tag;
718
-		}
719
-
720
-		try {
721
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
-			$stmt = \OC_DB::prepare($sql);
724
-			$stmt->execute(array($objid, $tagId, $this->type));
725
-		} catch(\Exception $e) {
726
-			\OC::$server->getLogger()->logException($e, [
727
-				'message' => __METHOD__,
728
-				'level' => ILogger::ERROR,
729
-				'app' => 'core',
730
-			]);
731
-			return false;
732
-		}
733
-		return true;
734
-	}
735
-
736
-	/**
737
-	* Delete tags from the database.
738
-	*
739
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
-	* @return bool Returns false on error
741
-	*/
742
-	public function delete($names) {
743
-		if(!is_array($names)) {
744
-			$names = array($names);
745
-		}
746
-
747
-		$names = array_map('trim', $names);
748
-		array_filter($names);
749
-
750
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
-			. print_r($this->tags, true), ILogger::DEBUG);
752
-		foreach($names as $name) {
753
-			$id = null;
754
-
755
-			if (is_numeric($name)) {
756
-				$key = $this->getTagById($name);
757
-			} else {
758
-				$key = $this->getTagByName($name);
759
-			}
760
-			if ($key !== false) {
761
-				$tag = $this->tags[$key];
762
-				$id = $tag->getId();
763
-				unset($this->tags[$key]);
764
-				$this->mapper->delete($tag);
765
-			} else {
766
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
-					. ': not found.', ILogger::ERROR);
768
-			}
769
-			if(!is_null($id) && $id !== false) {
770
-				try {
771
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
-							. 'WHERE `categoryid` = ?';
773
-					$stmt = \OC_DB::prepare($sql);
774
-					$result = $stmt->execute(array($id));
775
-					if ($result === null) {
776
-						\OCP\Util::writeLog('core',
777
-							__METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
-							ILogger::ERROR);
779
-						return false;
780
-					}
781
-				} catch(\Exception $e) {
782
-					\OC::$server->getLogger()->logException($e, [
783
-						'message' => __METHOD__,
784
-						'level' => ILogger::ERROR,
785
-						'app' => 'core',
786
-					]);
787
-					return false;
788
-				}
789
-			}
790
-		}
791
-		return true;
792
-	}
793
-
794
-	// case-insensitive array_search
795
-	protected function array_searchi($needle, $haystack, $mem='getName') {
796
-		if(!is_array($haystack)) {
797
-			return false;
798
-		}
799
-		return array_search(strtolower($needle), array_map(
800
-			function($tag) use($mem) {
801
-				return strtolower(call_user_func(array($tag, $mem)));
802
-			}, $haystack)
803
-		);
804
-	}
805
-
806
-	/**
807
-	* Get a tag's ID.
808
-	*
809
-	* @param string $name The tag name to look for.
810
-	* @return string|bool The tag's id or false if no matching tag is found.
811
-	*/
812
-	private function getTagId($name) {
813
-		$key = $this->array_searchi($name, $this->tags);
814
-		if ($key !== false) {
815
-			return $this->tags[$key]->getId();
816
-		}
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	* Get a tag by its name.
822
-	*
823
-	* @param string $name The tag name.
824
-	* @return integer|bool The tag object's offset within the $this->tags
825
-	*                      array or false if it doesn't exist.
826
-	*/
827
-	private function getTagByName($name) {
828
-		return $this->array_searchi($name, $this->tags, 'getName');
829
-	}
830
-
831
-	/**
832
-	* Get a tag by its ID.
833
-	*
834
-	* @param string $id The tag ID to look for.
835
-	* @return integer|bool The tag object's offset within the $this->tags
836
-	*                      array or false if it doesn't exist.
837
-	*/
838
-	private function getTagById($id) {
839
-		return $this->array_searchi($id, $this->tags, 'getId');
840
-	}
841
-
842
-	/**
843
-	* Returns an array mapping a given tag's properties to its values:
844
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
-	*
846
-	* @param Tag $tag The tag that is going to be mapped
847
-	* @return array
848
-	*/
849
-	private function tagMap(Tag $tag) {
850
-		return array(
851
-			'id'    => $tag->getId(),
852
-			'name'  => $tag->getName(),
853
-			'owner' => $tag->getOwner(),
854
-			'type'  => $tag->getType()
855
-		);
856
-	}
54
+    /**
55
+     * Tags
56
+     *
57
+     * @var array
58
+     */
59
+    private $tags = array();
60
+
61
+    /**
62
+     * Used for storing objectid/categoryname pairs while rescanning.
63
+     *
64
+     * @var array
65
+     */
66
+    private static $relations = array();
67
+
68
+    /**
69
+     * Type
70
+     *
71
+     * @var string
72
+     */
73
+    private $type;
74
+
75
+    /**
76
+     * User
77
+     *
78
+     * @var string
79
+     */
80
+    private $user;
81
+
82
+    /**
83
+     * Are we including tags for shared items?
84
+     *
85
+     * @var bool
86
+     */
87
+    private $includeShared = false;
88
+
89
+    /**
90
+     * The current user, plus any owners of the items shared with the current
91
+     * user, if $this->includeShared === true.
92
+     *
93
+     * @var array
94
+     */
95
+    private $owners = array();
96
+
97
+    /**
98
+     * The Mapper we're using to communicate our Tag objects to the database.
99
+     *
100
+     * @var TagMapper
101
+     */
102
+    private $mapper;
103
+
104
+    /**
105
+     * The sharing backend for objects of $this->type. Required if
106
+     * $this->includeShared === true to determine ownership of items.
107
+     *
108
+     * @var \OCP\Share_Backend
109
+     */
110
+    private $backend;
111
+
112
+    const TAG_TABLE = '*PREFIX*vcategory';
113
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
+
115
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
116
+
117
+    /**
118
+     * Constructor.
119
+     *
120
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
+     * @param string $user The user whose data the object will operate on.
122
+     * @param string $type The type of items for which tags will be loaded.
123
+     * @param array $defaultTags Tags that should be created at construction.
124
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
+     */
126
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
+        $this->mapper = $mapper;
128
+        $this->user = $user;
129
+        $this->type = $type;
130
+        $this->includeShared = $includeShared;
131
+        $this->owners = array($this->user);
132
+        if ($this->includeShared) {
133
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
+            $this->backend = \OC\Share\Share::getBackend($this->type);
135
+        }
136
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
+
138
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
+            $this->addMultiple($defaultTags, true);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * Check if any tags are saved for this type and user.
145
+     *
146
+     * @return boolean
147
+     */
148
+    public function isEmpty() {
149
+        return count($this->tags) === 0;
150
+    }
151
+
152
+    /**
153
+     * Returns an array mapping a given tag's properties to its values:
154
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
+     *
156
+     * @param string $id The ID of the tag that is going to be mapped
157
+     * @return array|false
158
+     */
159
+    public function getTag($id) {
160
+        $key = $this->getTagById($id);
161
+        if ($key !== false) {
162
+            return $this->tagMap($this->tags[$key]);
163
+        }
164
+        return false;
165
+    }
166
+
167
+    /**
168
+     * Get the tags for a specific user.
169
+     *
170
+     * This returns an array with maps containing each tag's properties:
171
+     * [
172
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
+     * ]
175
+     *
176
+     * @return array
177
+     */
178
+    public function getTags() {
179
+        if(!count($this->tags)) {
180
+            return array();
181
+        }
182
+
183
+        usort($this->tags, function($a, $b) {
184
+            return strnatcasecmp($a->getName(), $b->getName());
185
+        });
186
+        $tagMap = array();
187
+
188
+        foreach($this->tags as $tag) {
189
+            if($tag->getName() !== self::TAG_FAVORITE) {
190
+                $tagMap[] = $this->tagMap($tag);
191
+            }
192
+        }
193
+        return $tagMap;
194
+
195
+    }
196
+
197
+    /**
198
+     * Return only the tags owned by the given user, omitting any tags shared
199
+     * by other users.
200
+     *
201
+     * @param string $user The user whose tags are to be checked.
202
+     * @return array An array of Tag objects.
203
+     */
204
+    public function getTagsForUser($user) {
205
+        return array_filter($this->tags,
206
+            function($tag) use($user) {
207
+                return $tag->getOwner() === $user;
208
+            }
209
+        );
210
+    }
211
+
212
+    /**
213
+     * Get the list of tags for the given ids.
214
+     *
215
+     * @param array $objIds array of object ids
216
+     * @return array|boolean of tags id as key to array of tag names
217
+     * or false if an error occurred
218
+     */
219
+    public function getTagsForObjects(array $objIds) {
220
+        $entries = array();
221
+
222
+        try {
223
+            $conn = \OC::$server->getDatabaseConnection();
224
+            $chunks = array_chunk($objIds, 900, false);
225
+            foreach ($chunks as $chunk) {
226
+                $result = $conn->executeQuery(
227
+                    'SELECT `category`, `categoryid`, `objid` ' .
228
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
+                    array($this->user, $this->type, $chunk),
231
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
+                );
233
+                while ($row = $result->fetch()) {
234
+                    $objId = (int)$row['objid'];
235
+                    if (!isset($entries[$objId])) {
236
+                        $entries[$objId] = array();
237
+                    }
238
+                    $entries[$objId][] = $row['category'];
239
+                }
240
+                if ($result === null) {
241
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
+                    return false;
243
+                }
244
+            }
245
+        } catch(\Exception $e) {
246
+            \OC::$server->getLogger()->logException($e, [
247
+                'message' => __METHOD__,
248
+                'level' => ILogger::ERROR,
249
+                'app' => 'core',
250
+            ]);
251
+            return false;
252
+        }
253
+
254
+        return $entries;
255
+    }
256
+
257
+    /**
258
+     * Get the a list if items tagged with $tag.
259
+     *
260
+     * Throws an exception if the tag could not be found.
261
+     *
262
+     * @param string $tag Tag id or name.
263
+     * @return array|false An array of object ids or false on error.
264
+     * @throws \Exception
265
+     */
266
+    public function getIdsForTag($tag) {
267
+        $result = null;
268
+        $tagId = false;
269
+        if(is_numeric($tag)) {
270
+            $tagId = $tag;
271
+        } elseif(is_string($tag)) {
272
+            $tag = trim($tag);
273
+            if($tag === '') {
274
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
+                return false;
276
+            }
277
+            $tagId = $this->getTagId($tag);
278
+        }
279
+
280
+        if($tagId === false) {
281
+            $l10n = \OC::$server->getL10N('core');
282
+            throw new \Exception(
283
+                $l10n->t('Could not find category "%s"', [$tag])
284
+            );
285
+        }
286
+
287
+        $ids = array();
288
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
+            . '` WHERE `categoryid` = ?';
290
+
291
+        try {
292
+            $stmt = \OC_DB::prepare($sql);
293
+            $result = $stmt->execute(array($tagId));
294
+            if ($result === null) {
295
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
+                return false;
297
+            }
298
+        } catch(\Exception $e) {
299
+            \OC::$server->getLogger()->logException($e, [
300
+                'message' => __METHOD__,
301
+                'level' => ILogger::ERROR,
302
+                'app' => 'core',
303
+            ]);
304
+            return false;
305
+        }
306
+
307
+        if(!is_null($result)) {
308
+            while( $row = $result->fetchRow()) {
309
+                $id = (int)$row['objid'];
310
+
311
+                if ($this->includeShared) {
312
+                    // We have to check if we are really allowed to access the
313
+                    // items that are tagged with $tag. To that end, we ask the
314
+                    // corresponding sharing backend if the item identified by $id
315
+                    // is owned by any of $this->owners.
316
+                    foreach ($this->owners as $owner) {
317
+                        if ($this->backend->isValidSource($id, $owner)) {
318
+                            $ids[] = $id;
319
+                            break;
320
+                        }
321
+                    }
322
+                } else {
323
+                    $ids[] = $id;
324
+                }
325
+            }
326
+        }
327
+
328
+        return $ids;
329
+    }
330
+
331
+    /**
332
+     * Checks whether a tag is saved for the given user,
333
+     * disregarding the ones shared with him or her.
334
+     *
335
+     * @param string $name The tag name to check for.
336
+     * @param string $user The user whose tags are to be checked.
337
+     * @return bool
338
+     */
339
+    public function userHasTag($name, $user) {
340
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
341
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
342
+    }
343
+
344
+    /**
345
+     * Checks whether a tag is saved for or shared with the current user.
346
+     *
347
+     * @param string $name The tag name to check for.
348
+     * @return bool
349
+     */
350
+    public function hasTag($name) {
351
+        return $this->getTagId($name) !== false;
352
+    }
353
+
354
+    /**
355
+     * Add a new tag.
356
+     *
357
+     * @param string $name A string with a name of the tag
358
+     * @return false|int the id of the added tag or false on error.
359
+     */
360
+    public function add($name) {
361
+        $name = trim($name);
362
+
363
+        if($name === '') {
364
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
+            return false;
366
+        }
367
+        if($this->userHasTag($name, $this->user)) {
368
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
+            return false;
370
+        }
371
+        try {
372
+            $tag = new Tag($this->user, $this->type, $name);
373
+            $tag = $this->mapper->insert($tag);
374
+            $this->tags[] = $tag;
375
+        } catch(\Exception $e) {
376
+            \OC::$server->getLogger()->logException($e, [
377
+                'message' => __METHOD__,
378
+                'level' => ILogger::ERROR,
379
+                'app' => 'core',
380
+            ]);
381
+            return false;
382
+        }
383
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
+        return $tag->getId();
385
+    }
386
+
387
+    /**
388
+     * Rename tag.
389
+     *
390
+     * @param string|integer $from The name or ID of the existing tag
391
+     * @param string $to The new name of the tag.
392
+     * @return bool
393
+     */
394
+    public function rename($from, $to) {
395
+        $from = trim($from);
396
+        $to = trim($to);
397
+
398
+        if($to === '' || $from === '') {
399
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
+            return false;
401
+        }
402
+
403
+        if (is_numeric($from)) {
404
+            $key = $this->getTagById($from);
405
+        } else {
406
+            $key = $this->getTagByName($from);
407
+        }
408
+        if($key === false) {
409
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
+            return false;
411
+        }
412
+        $tag = $this->tags[$key];
413
+
414
+        if($this->userHasTag($to, $tag->getOwner())) {
415
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
+            return false;
417
+        }
418
+
419
+        try {
420
+            $tag->setName($to);
421
+            $this->tags[$key] = $this->mapper->update($tag);
422
+        } catch(\Exception $e) {
423
+            \OC::$server->getLogger()->logException($e, [
424
+                'message' => __METHOD__,
425
+                'level' => ILogger::ERROR,
426
+                'app' => 'core',
427
+            ]);
428
+            return false;
429
+        }
430
+        return true;
431
+    }
432
+
433
+    /**
434
+     * Add a list of new tags.
435
+     *
436
+     * @param string[] $names A string with a name or an array of strings containing
437
+     * the name(s) of the tag(s) to add.
438
+     * @param bool $sync When true, save the tags
439
+     * @param int|null $id int Optional object id to add to this|these tag(s)
440
+     * @return bool Returns false on error.
441
+     */
442
+    public function addMultiple($names, $sync=false, $id = null) {
443
+        if(!is_array($names)) {
444
+            $names = array($names);
445
+        }
446
+        $names = array_map('trim', $names);
447
+        array_filter($names);
448
+
449
+        $newones = array();
450
+        foreach($names as $name) {
451
+            if(!$this->hasTag($name) && $name !== '') {
452
+                $newones[] = new Tag($this->user, $this->type, $name);
453
+            }
454
+            if(!is_null($id) ) {
455
+                // Insert $objectid, $categoryid  pairs if not exist.
456
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
457
+            }
458
+        }
459
+        $this->tags = array_merge($this->tags, $newones);
460
+        if($sync === true) {
461
+            $this->save();
462
+        }
463
+
464
+        return true;
465
+    }
466
+
467
+    /**
468
+     * Save the list of tags and their object relations
469
+     */
470
+    protected function save() {
471
+        if(is_array($this->tags)) {
472
+            foreach($this->tags as $tag) {
473
+                try {
474
+                    if (!$this->mapper->tagExists($tag)) {
475
+                        $this->mapper->insert($tag);
476
+                    }
477
+                } catch(\Exception $e) {
478
+                    \OC::$server->getLogger()->logException($e, [
479
+                        'message' => __METHOD__,
480
+                        'level' => ILogger::ERROR,
481
+                        'app' => 'core',
482
+                    ]);
483
+                }
484
+            }
485
+
486
+            // reload tags to get the proper ids.
487
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
+                ILogger::DEBUG);
490
+            // Loop through temporarily cached objectid/tagname pairs
491
+            // and save relations.
492
+            $tags = $this->tags;
493
+            // For some reason this is needed or array_search(i) will return 0..?
494
+            ksort($tags);
495
+            $dbConnection = \OC::$server->getDatabaseConnection();
496
+            foreach(self::$relations as $relation) {
497
+                $tagId = $this->getTagId($relation['tag']);
498
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
+                if($tagId) {
500
+                    try {
501
+                        $dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
+                            array(
503
+                                'objid' => $relation['objid'],
504
+                                'categoryid' => $tagId,
505
+                                'type' => $this->type,
506
+                                ));
507
+                    } catch(\Exception $e) {
508
+                        \OC::$server->getLogger()->logException($e, [
509
+                            'message' => __METHOD__,
510
+                            'level' => ILogger::ERROR,
511
+                            'app' => 'core',
512
+                        ]);
513
+                    }
514
+                }
515
+            }
516
+            self::$relations = array(); // reset
517
+        } else {
518
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
+                . print_r($this->tags, true), ILogger::ERROR);
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Delete tags and tag/object relations for a user.
525
+     *
526
+     * For hooking up on post_deleteUser
527
+     *
528
+     * @param array $arguments
529
+     */
530
+    public static function post_deleteUser($arguments) {
531
+        // Find all objectid/tagId pairs.
532
+        $result = null;
533
+        try {
534
+            $stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
+                . 'WHERE `uid` = ?');
536
+            $result = $stmt->execute(array($arguments['uid']));
537
+            if ($result === null) {
538
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
+            }
540
+        } catch(\Exception $e) {
541
+            \OC::$server->getLogger()->logException($e, [
542
+                'message' => __METHOD__,
543
+                'level' => ILogger::ERROR,
544
+                'app' => 'core',
545
+            ]);
546
+        }
547
+
548
+        if(!is_null($result)) {
549
+            try {
550
+                $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
+                    . 'WHERE `categoryid` = ?');
552
+                while( $row = $result->fetchRow()) {
553
+                    try {
554
+                        $stmt->execute(array($row['id']));
555
+                    } catch(\Exception $e) {
556
+                        \OC::$server->getLogger()->logException($e, [
557
+                            'message' => __METHOD__,
558
+                            'level' => ILogger::ERROR,
559
+                            'app' => 'core',
560
+                        ]);
561
+                    }
562
+                }
563
+            } catch(\Exception $e) {
564
+                \OC::$server->getLogger()->logException($e, [
565
+                    'message' => __METHOD__,
566
+                    'level' => ILogger::ERROR,
567
+                    'app' => 'core',
568
+                ]);
569
+            }
570
+        }
571
+        try {
572
+            $stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
+                . 'WHERE `uid` = ?');
574
+            $result = $stmt->execute(array($arguments['uid']));
575
+            if ($result === null) {
576
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
+            }
578
+        } catch(\Exception $e) {
579
+            \OC::$server->getLogger()->logException($e, [
580
+                'message' => __METHOD__,
581
+                'level' => ILogger::ERROR,
582
+                'app' => 'core',
583
+            ]);
584
+        }
585
+    }
586
+
587
+    /**
588
+     * Delete tag/object relations from the db
589
+     *
590
+     * @param array $ids The ids of the objects
591
+     * @return boolean Returns false on error.
592
+     */
593
+    public function purgeObjects(array $ids) {
594
+        if(count($ids) === 0) {
595
+            // job done ;)
596
+            return true;
597
+        }
598
+        $updates = $ids;
599
+        try {
600
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
+            $query .= 'AND `type`= ?';
603
+            $updates[] = $this->type;
604
+            $stmt = \OC_DB::prepare($query);
605
+            $result = $stmt->execute($updates);
606
+            if ($result === null) {
607
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
+                return false;
609
+            }
610
+        } catch(\Exception $e) {
611
+            \OC::$server->getLogger()->logException($e, [
612
+                'message' => __METHOD__,
613
+                'level' => ILogger::ERROR,
614
+                'app' => 'core',
615
+            ]);
616
+            return false;
617
+        }
618
+        return true;
619
+    }
620
+
621
+    /**
622
+     * Get favorites for an object type
623
+     *
624
+     * @return array|false An array of object ids.
625
+     */
626
+    public function getFavorites() {
627
+        try {
628
+            return $this->getIdsForTag(self::TAG_FAVORITE);
629
+        } catch(\Exception $e) {
630
+            \OC::$server->getLogger()->logException($e, [
631
+                'message' => __METHOD__,
632
+                'level' => ILogger::ERROR,
633
+                'app' => 'core',
634
+            ]);
635
+            return array();
636
+        }
637
+    }
638
+
639
+    /**
640
+     * Add an object to favorites
641
+     *
642
+     * @param int $objid The id of the object
643
+     * @return boolean
644
+     */
645
+    public function addToFavorites($objid) {
646
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
+            $this->add(self::TAG_FAVORITE);
648
+        }
649
+        return $this->tagAs($objid, self::TAG_FAVORITE);
650
+    }
651
+
652
+    /**
653
+     * Remove an object from favorites
654
+     *
655
+     * @param int $objid The id of the object
656
+     * @return boolean
657
+     */
658
+    public function removeFromFavorites($objid) {
659
+        return $this->unTag($objid, self::TAG_FAVORITE);
660
+    }
661
+
662
+    /**
663
+     * Creates a tag/object relation.
664
+     *
665
+     * @param int $objid The id of the object
666
+     * @param string $tag The id or name of the tag
667
+     * @return boolean Returns false on error.
668
+     */
669
+    public function tagAs($objid, $tag) {
670
+        if(is_string($tag) && !is_numeric($tag)) {
671
+            $tag = trim($tag);
672
+            if($tag === '') {
673
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
+                return false;
675
+            }
676
+            if(!$this->hasTag($tag)) {
677
+                $this->add($tag);
678
+            }
679
+            $tagId =  $this->getTagId($tag);
680
+        } else {
681
+            $tagId = $tag;
682
+        }
683
+        try {
684
+            \OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
+                array(
686
+                    'objid' => $objid,
687
+                    'categoryid' => $tagId,
688
+                    'type' => $this->type,
689
+                ));
690
+        } catch(\Exception $e) {
691
+            \OC::$server->getLogger()->logException($e, [
692
+                'message' => __METHOD__,
693
+                'level' => ILogger::ERROR,
694
+                'app' => 'core',
695
+            ]);
696
+            return false;
697
+        }
698
+        return true;
699
+    }
700
+
701
+    /**
702
+     * Delete single tag/object relation from the db
703
+     *
704
+     * @param int $objid The id of the object
705
+     * @param string $tag The id or name of the tag
706
+     * @return boolean
707
+     */
708
+    public function unTag($objid, $tag) {
709
+        if(is_string($tag) && !is_numeric($tag)) {
710
+            $tag = trim($tag);
711
+            if($tag === '') {
712
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
+                return false;
714
+            }
715
+            $tagId =  $this->getTagId($tag);
716
+        } else {
717
+            $tagId = $tag;
718
+        }
719
+
720
+        try {
721
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
+            $stmt = \OC_DB::prepare($sql);
724
+            $stmt->execute(array($objid, $tagId, $this->type));
725
+        } catch(\Exception $e) {
726
+            \OC::$server->getLogger()->logException($e, [
727
+                'message' => __METHOD__,
728
+                'level' => ILogger::ERROR,
729
+                'app' => 'core',
730
+            ]);
731
+            return false;
732
+        }
733
+        return true;
734
+    }
735
+
736
+    /**
737
+     * Delete tags from the database.
738
+     *
739
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
+     * @return bool Returns false on error
741
+     */
742
+    public function delete($names) {
743
+        if(!is_array($names)) {
744
+            $names = array($names);
745
+        }
746
+
747
+        $names = array_map('trim', $names);
748
+        array_filter($names);
749
+
750
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
+            . print_r($this->tags, true), ILogger::DEBUG);
752
+        foreach($names as $name) {
753
+            $id = null;
754
+
755
+            if (is_numeric($name)) {
756
+                $key = $this->getTagById($name);
757
+            } else {
758
+                $key = $this->getTagByName($name);
759
+            }
760
+            if ($key !== false) {
761
+                $tag = $this->tags[$key];
762
+                $id = $tag->getId();
763
+                unset($this->tags[$key]);
764
+                $this->mapper->delete($tag);
765
+            } else {
766
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
+                    . ': not found.', ILogger::ERROR);
768
+            }
769
+            if(!is_null($id) && $id !== false) {
770
+                try {
771
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
+                            . 'WHERE `categoryid` = ?';
773
+                    $stmt = \OC_DB::prepare($sql);
774
+                    $result = $stmt->execute(array($id));
775
+                    if ($result === null) {
776
+                        \OCP\Util::writeLog('core',
777
+                            __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
+                            ILogger::ERROR);
779
+                        return false;
780
+                    }
781
+                } catch(\Exception $e) {
782
+                    \OC::$server->getLogger()->logException($e, [
783
+                        'message' => __METHOD__,
784
+                        'level' => ILogger::ERROR,
785
+                        'app' => 'core',
786
+                    ]);
787
+                    return false;
788
+                }
789
+            }
790
+        }
791
+        return true;
792
+    }
793
+
794
+    // case-insensitive array_search
795
+    protected function array_searchi($needle, $haystack, $mem='getName') {
796
+        if(!is_array($haystack)) {
797
+            return false;
798
+        }
799
+        return array_search(strtolower($needle), array_map(
800
+            function($tag) use($mem) {
801
+                return strtolower(call_user_func(array($tag, $mem)));
802
+            }, $haystack)
803
+        );
804
+    }
805
+
806
+    /**
807
+     * Get a tag's ID.
808
+     *
809
+     * @param string $name The tag name to look for.
810
+     * @return string|bool The tag's id or false if no matching tag is found.
811
+     */
812
+    private function getTagId($name) {
813
+        $key = $this->array_searchi($name, $this->tags);
814
+        if ($key !== false) {
815
+            return $this->tags[$key]->getId();
816
+        }
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Get a tag by its name.
822
+     *
823
+     * @param string $name The tag name.
824
+     * @return integer|bool The tag object's offset within the $this->tags
825
+     *                      array or false if it doesn't exist.
826
+     */
827
+    private function getTagByName($name) {
828
+        return $this->array_searchi($name, $this->tags, 'getName');
829
+    }
830
+
831
+    /**
832
+     * Get a tag by its ID.
833
+     *
834
+     * @param string $id The tag ID to look for.
835
+     * @return integer|bool The tag object's offset within the $this->tags
836
+     *                      array or false if it doesn't exist.
837
+     */
838
+    private function getTagById($id) {
839
+        return $this->array_searchi($id, $this->tags, 'getId');
840
+    }
841
+
842
+    /**
843
+     * Returns an array mapping a given tag's properties to its values:
844
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
+     *
846
+     * @param Tag $tag The tag that is going to be mapped
847
+     * @return array
848
+     */
849
+    private function tagMap(Tag $tag) {
850
+        return array(
851
+            'id'    => $tag->getId(),
852
+            'name'  => $tag->getName(),
853
+            'owner' => $tag->getOwner(),
854
+            'type'  => $tag->getType()
855
+        );
856
+    }
857 857
 }
Please login to merge, or discard this patch.
lib/private/Setup/MySQL.php 1 patch
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -34,143 +34,143 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class MySQL extends AbstractDatabase {
37
-	public $dbprettyname = 'MySQL/MariaDB';
38
-
39
-	public function setupDatabase($username) {
40
-		//check if the database user has admin right
41
-		$connection = $this->connect(['dbname' => null]);
42
-
43
-		// detect mb4
44
-		$tools = new MySqlTools();
45
-		if ($tools->supports4ByteCharset($connection)) {
46
-			$this->config->setValue('mysql.utf8mb4', true);
47
-			$connection = $this->connect(['dbname' => null]);
48
-		}
49
-
50
-		$this->createSpecificUser($username, $connection);
51
-
52
-		//create the database
53
-		$this->createDatabase($connection);
54
-
55
-		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
-	}
59
-
60
-	/**
61
-	 * @param \OC\DB\Connection $connection
62
-	 */
63
-	private function createDatabase($connection) {
64
-		try{
65
-			$name = $this->dbName;
66
-			$user = $this->dbUser;
67
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
68
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
-			$connection->executeUpdate($query);
71
-		} catch (\Exception $ex) {
72
-			$this->logger->logException($ex, [
73
-				'message' => 'Database creation failed.',
74
-				'level' => ILogger::ERROR,
75
-				'app' => 'mysql.setup',
76
-			]);
77
-			return;
78
-		}
79
-
80
-		try {
81
-			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
-			$connection->executeUpdate($query);
84
-		} catch (\Exception $ex) {
85
-			$this->logger->logException($ex, [
86
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
-				'level' => ILogger::DEBUG,
88
-				'app' => 'mysql.setup',
89
-			]);
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * @param IDBConnection $connection
95
-	 * @throws \OC\DatabaseSetupException
96
-	 */
97
-	private function createDBUser($connection) {
98
-		try{
99
-			$name = $this->dbUser;
100
-			$password = $this->dbPassword;
101
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
-			// the anonymous user would take precedence when there is one.
103
-			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
-			$connection->executeUpdate($query);
105
-			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
-			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
109
-			$this->logger->logException($ex, [
110
-				'message' => 'Database user creation failed.',
111
-				'level' => ILogger::ERROR,
112
-				'app' => 'mysql.setup',
113
-			]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * @param $username
119
-	 * @param IDBConnection $connection
120
-	 * @return array
121
-	 */
122
-	private function createSpecificUser($username, $connection) {
123
-		try {
124
-			//user already specified in config
125
-			$oldUser = $this->config->getValue('dbuser', false);
126
-
127
-			//we don't have a dbuser specified in config
128
-			if ($this->dbUser !== $oldUser) {
129
-				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
131
-
132
-				$i = 1;
133
-				while (true) {
134
-					//this should be enough to check for admin rights in mysql
135
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
136
-					$result = $connection->executeQuery($query, [$adminUser]);
137
-
138
-					//current dbuser has admin rights
139
-					if ($result) {
140
-						$data = $result->fetchAll();
141
-						//new dbuser does not exist
142
-						if (count($data) === 0) {
143
-							//use the admin login data for the new database user
144
-							$this->dbUser = $adminUser;
145
-
146
-							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
148
-
149
-							$this->createDBUser($connection);
150
-
151
-							break;
152
-						} else {
153
-							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
-							$i++;
157
-						}
158
-					} else {
159
-						break;
160
-					}
161
-				}
162
-			}
163
-		} catch (\Exception $ex) {
164
-			$this->logger->logException($ex, [
165
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
-				'level' => ILogger::INFO,
167
-				'app' => 'mysql.setup',
168
-			]);
169
-		}
170
-
171
-		$this->config->setValues([
172
-			'dbuser' => $this->dbUser,
173
-			'dbpassword' => $this->dbPassword,
174
-		]);
175
-	}
37
+    public $dbprettyname = 'MySQL/MariaDB';
38
+
39
+    public function setupDatabase($username) {
40
+        //check if the database user has admin right
41
+        $connection = $this->connect(['dbname' => null]);
42
+
43
+        // detect mb4
44
+        $tools = new MySqlTools();
45
+        if ($tools->supports4ByteCharset($connection)) {
46
+            $this->config->setValue('mysql.utf8mb4', true);
47
+            $connection = $this->connect(['dbname' => null]);
48
+        }
49
+
50
+        $this->createSpecificUser($username, $connection);
51
+
52
+        //create the database
53
+        $this->createDatabase($connection);
54
+
55
+        //fill the database if needed
56
+        $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
+    }
59
+
60
+    /**
61
+     * @param \OC\DB\Connection $connection
62
+     */
63
+    private function createDatabase($connection) {
64
+        try{
65
+            $name = $this->dbName;
66
+            $user = $this->dbUser;
67
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
68
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
+            $connection->executeUpdate($query);
71
+        } catch (\Exception $ex) {
72
+            $this->logger->logException($ex, [
73
+                'message' => 'Database creation failed.',
74
+                'level' => ILogger::ERROR,
75
+                'app' => 'mysql.setup',
76
+            ]);
77
+            return;
78
+        }
79
+
80
+        try {
81
+            //this query will fail if there aren't the right permissions, ignore the error
82
+            $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
+            $connection->executeUpdate($query);
84
+        } catch (\Exception $ex) {
85
+            $this->logger->logException($ex, [
86
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
+                'level' => ILogger::DEBUG,
88
+                'app' => 'mysql.setup',
89
+            ]);
90
+        }
91
+    }
92
+
93
+    /**
94
+     * @param IDBConnection $connection
95
+     * @throws \OC\DatabaseSetupException
96
+     */
97
+    private function createDBUser($connection) {
98
+        try{
99
+            $name = $this->dbUser;
100
+            $password = $this->dbPassword;
101
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
+            // the anonymous user would take precedence when there is one.
103
+            $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
+            $connection->executeUpdate($query);
105
+            $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
+            $connection->executeUpdate($query);
107
+        }
108
+        catch (\Exception $ex){
109
+            $this->logger->logException($ex, [
110
+                'message' => 'Database user creation failed.',
111
+                'level' => ILogger::ERROR,
112
+                'app' => 'mysql.setup',
113
+            ]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * @param $username
119
+     * @param IDBConnection $connection
120
+     * @return array
121
+     */
122
+    private function createSpecificUser($username, $connection) {
123
+        try {
124
+            //user already specified in config
125
+            $oldUser = $this->config->getValue('dbuser', false);
126
+
127
+            //we don't have a dbuser specified in config
128
+            if ($this->dbUser !== $oldUser) {
129
+                //add prefix to the admin username to prevent collisions
130
+                $adminUser = substr('oc_' . $username, 0, 16);
131
+
132
+                $i = 1;
133
+                while (true) {
134
+                    //this should be enough to check for admin rights in mysql
135
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
136
+                    $result = $connection->executeQuery($query, [$adminUser]);
137
+
138
+                    //current dbuser has admin rights
139
+                    if ($result) {
140
+                        $data = $result->fetchAll();
141
+                        //new dbuser does not exist
142
+                        if (count($data) === 0) {
143
+                            //use the admin login data for the new database user
144
+                            $this->dbUser = $adminUser;
145
+
146
+                            //create a random password so we don't need to store the admin password in the config file
147
+                            $this->dbPassword =  $this->random->generate(30);
148
+
149
+                            $this->createDBUser($connection);
150
+
151
+                            break;
152
+                        } else {
153
+                            //repeat with different username
154
+                            $length = strlen((string)$i);
155
+                            $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
+                            $i++;
157
+                        }
158
+                    } else {
159
+                        break;
160
+                    }
161
+                }
162
+            }
163
+        } catch (\Exception $ex) {
164
+            $this->logger->logException($ex, [
165
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
+                'level' => ILogger::INFO,
167
+                'app' => 'mysql.setup',
168
+            ]);
169
+        }
170
+
171
+        $this->config->setValues([
172
+            'dbuser' => $this->dbUser,
173
+            'dbpassword' => $this->dbPassword,
174
+        ]);
175
+    }
176 176
 }
Please login to merge, or discard this patch.
lib/private/Preview/Bitmap.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -35,86 +35,86 @@
 block discarded – undo
35 35
  */
36 36
 abstract class Bitmap extends Provider {
37 37
 
38
-	/**
39
-	 * {@inheritDoc}
40
-	 */
41
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
-
43
-		$tmpPath = $fileview->toTmpFile($path);
44
-		if (!$tmpPath) {
45
-			return false;
46
-		}
47
-
48
-		// Creates \Imagick object from bitmap or vector file
49
-		try {
50
-			$bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
-		} catch (\Exception $e) {
52
-			\OC::$server->getLogger()->logException($e, [
53
-				'message' => 'Imagick says:',
54
-				'level' => ILogger::ERROR,
55
-				'app' => 'core',
56
-			]);
57
-			return false;
58
-		}
59
-
60
-		unlink($tmpPath);
61
-
62
-		//new bitmap image object
63
-		$image = new \OC_Image();
64
-		$image->loadFromData($bp);
65
-		//check if image object is valid
66
-		return $image->valid() ? $image : false;
67
-	}
68
-
69
-	/**
70
-	 * Returns a preview of maxX times maxY dimensions in PNG format
71
-	 *
72
-	 *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
-	 *    * It's possible to have proper colour conversion using profileimage().
74
-	 *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
-	 *    * It's possible to Gamma-correct an image via gammaImage()
76
-	 *
77
-	 * @param string $tmpPath the location of the file to convert
78
-	 * @param int $maxX
79
-	 * @param int $maxY
80
-	 *
81
-	 * @return \Imagick
82
-	 */
83
-	private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
-		$bp = new Imagick();
85
-
86
-		// Layer 0 contains either the bitmap or a flat representation of all vector layers
87
-		$bp->readImage($tmpPath . '[0]');
88
-
89
-		$bp = $this->resize($bp, $maxX, $maxY);
90
-
91
-		$bp->setImageFormat('png');
92
-
93
-		return $bp;
94
-	}
95
-
96
-	/**
97
-	 * Returns a resized \Imagick object
98
-	 *
99
-	 * If you want to know more on the various methods available to resize an
100
-	 * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
-	 *
102
-	 * @param \Imagick $bp
103
-	 * @param int $maxX
104
-	 * @param int $maxY
105
-	 *
106
-	 * @return \Imagick
107
-	 */
108
-	private function resize($bp, $maxX, $maxY) {
109
-		list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
-
111
-		// We only need to resize a preview which doesn't fit in the maximum dimensions
112
-		if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
-			// TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
-			$bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
-		}
116
-
117
-		return $bp;
118
-	}
38
+    /**
39
+     * {@inheritDoc}
40
+     */
41
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
+
43
+        $tmpPath = $fileview->toTmpFile($path);
44
+        if (!$tmpPath) {
45
+            return false;
46
+        }
47
+
48
+        // Creates \Imagick object from bitmap or vector file
49
+        try {
50
+            $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
+        } catch (\Exception $e) {
52
+            \OC::$server->getLogger()->logException($e, [
53
+                'message' => 'Imagick says:',
54
+                'level' => ILogger::ERROR,
55
+                'app' => 'core',
56
+            ]);
57
+            return false;
58
+        }
59
+
60
+        unlink($tmpPath);
61
+
62
+        //new bitmap image object
63
+        $image = new \OC_Image();
64
+        $image->loadFromData($bp);
65
+        //check if image object is valid
66
+        return $image->valid() ? $image : false;
67
+    }
68
+
69
+    /**
70
+     * Returns a preview of maxX times maxY dimensions in PNG format
71
+     *
72
+     *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
+     *    * It's possible to have proper colour conversion using profileimage().
74
+     *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
+     *    * It's possible to Gamma-correct an image via gammaImage()
76
+     *
77
+     * @param string $tmpPath the location of the file to convert
78
+     * @param int $maxX
79
+     * @param int $maxY
80
+     *
81
+     * @return \Imagick
82
+     */
83
+    private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
+        $bp = new Imagick();
85
+
86
+        // Layer 0 contains either the bitmap or a flat representation of all vector layers
87
+        $bp->readImage($tmpPath . '[0]');
88
+
89
+        $bp = $this->resize($bp, $maxX, $maxY);
90
+
91
+        $bp->setImageFormat('png');
92
+
93
+        return $bp;
94
+    }
95
+
96
+    /**
97
+     * Returns a resized \Imagick object
98
+     *
99
+     * If you want to know more on the various methods available to resize an
100
+     * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
+     *
102
+     * @param \Imagick $bp
103
+     * @param int $maxX
104
+     * @param int $maxY
105
+     *
106
+     * @return \Imagick
107
+     */
108
+    private function resize($bp, $maxX, $maxY) {
109
+        list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
+
111
+        // We only need to resize a preview which doesn't fit in the maximum dimensions
112
+        if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
+            // TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
+            $bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
+        }
116
+
117
+        return $bp;
118
+    }
119 119
 
120 120
 }
Please login to merge, or discard this patch.
lib/private/Preview/SVG.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -27,50 +27,50 @@
 block discarded – undo
27 27
 use OCP\ILogger;
28 28
 
29 29
 class SVG extends Provider {
30
-	/**
31
-	 * {@inheritDoc}
32
-	 */
33
-	public function getMimeType() {
34
-		return '/image\/svg\+xml/';
35
-	}
30
+    /**
31
+     * {@inheritDoc}
32
+     */
33
+    public function getMimeType() {
34
+        return '/image\/svg\+xml/';
35
+    }
36 36
 
37
-	/**
38
-	 * {@inheritDoc}
39
-	 */
40
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
-		try {
42
-			$svg = new \Imagick();
43
-			$svg->setBackgroundColor(new \ImagickPixel('transparent'));
37
+    /**
38
+     * {@inheritDoc}
39
+     */
40
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
+        try {
42
+            $svg = new \Imagick();
43
+            $svg->setBackgroundColor(new \ImagickPixel('transparent'));
44 44
 
45
-			$content = stream_get_contents($fileview->fopen($path, 'r'));
46
-			if (substr($content, 0, 5) !== '<?xml') {
47
-				$content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
-			}
45
+            $content = stream_get_contents($fileview->fopen($path, 'r'));
46
+            if (substr($content, 0, 5) !== '<?xml') {
47
+                $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
+            }
49 49
 
50
-			// Do not parse SVG files with references
51
-			if (stripos($content, 'xlink:href') !== false) {
52
-				return false;
53
-			}
50
+            // Do not parse SVG files with references
51
+            if (stripos($content, 'xlink:href') !== false) {
52
+                return false;
53
+            }
54 54
 
55
-			$svg->readImageBlob($content);
56
-			$svg->setImageFormat('png32');
57
-		} catch (\Exception $e) {
58
-			\OC::$server->getLogger()->logException($e, [
59
-				'level' => ILogger::ERROR,
60
-				'app' => 'core',
61
-			]);
62
-			return false;
63
-		}
55
+            $svg->readImageBlob($content);
56
+            $svg->setImageFormat('png32');
57
+        } catch (\Exception $e) {
58
+            \OC::$server->getLogger()->logException($e, [
59
+                'level' => ILogger::ERROR,
60
+                'app' => 'core',
61
+            ]);
62
+            return false;
63
+        }
64 64
 
65
-		//new image object
66
-		$image = new \OC_Image();
67
-		$image->loadFromData($svg);
68
-		//check if image object is valid
69
-		if ($image->valid()) {
70
-			$image->scaleDownToFit($maxX, $maxY);
65
+        //new image object
66
+        $image = new \OC_Image();
67
+        $image->loadFromData($svg);
68
+        //check if image object is valid
69
+        if ($image->valid()) {
70
+            $image->scaleDownToFit($maxX, $maxY);
71 71
 
72
-			return $image;
73
-		}
74
-		return false;
75
-	}
72
+            return $image;
73
+        }
74
+        return false;
75
+    }
76 76
 }
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -28,83 +28,83 @@
 block discarded – undo
28 28
 use OCP\ILogger;
29 29
 
30 30
 abstract class Office extends Provider {
31
-	private $cmd;
31
+    private $cmd;
32 32
 
33
-	/**
34
-	 * {@inheritDoc}
35
-	 */
36
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
-		$this->initCmd();
38
-		if (is_null($this->cmd)) {
39
-			return false;
40
-		}
33
+    /**
34
+     * {@inheritDoc}
35
+     */
36
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
+        $this->initCmd();
38
+        if (is_null($this->cmd)) {
39
+            return false;
40
+        }
41 41
 
42
-		$absPath = $fileview->toTmpFile($path);
42
+        $absPath = $fileview->toTmpFile($path);
43 43
 
44
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
44
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
45 45
 
46
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
46
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
48 48
 
49
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
49
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
50 50
 
51
-		shell_exec($exec);
51
+        shell_exec($exec);
52 52
 
53
-		//create imagick object from pdf
54
-		$pdfPreview = null;
55
-		try {
56
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
-			$pdfPreview = $dirname . '/' . $filename . '.pdf';
53
+        //create imagick object from pdf
54
+        $pdfPreview = null;
55
+        try {
56
+            list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
+            $pdfPreview = $dirname . '/' . $filename . '.pdf';
58 58
 
59
-			$pdf = new \imagick($pdfPreview . '[0]');
60
-			$pdf->setImageFormat('jpg');
61
-		} catch (\Exception $e) {
62
-			unlink($absPath);
63
-			unlink($pdfPreview);
64
-			\OC::$server->getLogger()->logException($e, [
65
-				'level' => ILogger::ERROR,
66
-				'app' => 'core',
67
-			]);
68
-			return false;
69
-		}
59
+            $pdf = new \imagick($pdfPreview . '[0]');
60
+            $pdf->setImageFormat('jpg');
61
+        } catch (\Exception $e) {
62
+            unlink($absPath);
63
+            unlink($pdfPreview);
64
+            \OC::$server->getLogger()->logException($e, [
65
+                'level' => ILogger::ERROR,
66
+                'app' => 'core',
67
+            ]);
68
+            return false;
69
+        }
70 70
 
71
-		$image = new \OC_Image();
72
-		$image->loadFromData($pdf);
71
+        $image = new \OC_Image();
72
+        $image->loadFromData($pdf);
73 73
 
74
-		unlink($absPath);
75
-		unlink($pdfPreview);
74
+        unlink($absPath);
75
+        unlink($pdfPreview);
76 76
 
77
-		if ($image->valid()) {
78
-			$image->scaleDownToFit($maxX, $maxY);
77
+        if ($image->valid()) {
78
+            $image->scaleDownToFit($maxX, $maxY);
79 79
 
80
-			return $image;
81
-		}
82
-		return false;
80
+            return $image;
81
+        }
82
+        return false;
83 83
 
84
-	}
84
+    }
85 85
 
86
-	private function initCmd() {
87
-		$cmd = '';
86
+    private function initCmd() {
87
+        $cmd = '';
88 88
 
89
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
-		if (is_string($libreOfficePath)) {
91
-			$cmd = $libreOfficePath;
92
-		}
89
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
+        if (is_string($libreOfficePath)) {
91
+            $cmd = $libreOfficePath;
92
+        }
93 93
 
94
-		$whichLibreOffice = shell_exec('command -v libreoffice');
95
-		if ($cmd === '' && !empty($whichLibreOffice)) {
96
-			$cmd = 'libreoffice';
97
-		}
94
+        $whichLibreOffice = shell_exec('command -v libreoffice');
95
+        if ($cmd === '' && !empty($whichLibreOffice)) {
96
+            $cmd = 'libreoffice';
97
+        }
98 98
 
99
-		$whichOpenOffice = shell_exec('command -v openoffice');
100
-		if ($cmd === '' && !empty($whichOpenOffice)) {
101
-			$cmd = 'openoffice';
102
-		}
99
+        $whichOpenOffice = shell_exec('command -v openoffice');
100
+        if ($cmd === '' && !empty($whichOpenOffice)) {
101
+            $cmd = 'openoffice';
102
+        }
103 103
 
104
-		if ($cmd === '') {
105
-			$cmd = null;
106
-		}
104
+        if ($cmd === '') {
105
+            $cmd = null;
106
+        }
107 107
 
108
-		$this->cmd = $cmd;
109
-	}
108
+        $this->cmd = $cmd;
109
+    }
110 110
 }
Please login to merge, or discard this patch.