Passed
Push — master ( 9e1ec0...fd8eec )
by Morris
10:54
created
lib/base.php 1 patch
Indentation   +995 added lines, -995 removed lines patch added patch discarded remove patch
@@ -68,1001 +68,1001 @@
 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 $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
-				echo "\n";
254
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
-				exit;
257
-			} else {
258
-				OC_Template::printErrorPage(
259
-					$l->t('Cannot write into "config" directory!'),
260
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
-					[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
264
-					503
265
-				);
266
-			}
267
-		}
268
-	}
269
-
270
-	public static function checkInstalled() {
271
-		if (defined('OC_CONSOLE')) {
272
-			return;
273
-		}
274
-		// Redirect to installer if not installed
275
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
-			if (OC::$CLI) {
277
-				throw new Exception('Not installed');
278
-			} else {
279
-				$url = OC::$WEBROOT . '/index.php';
280
-				header('Location: ' . $url);
281
-			}
282
-			exit();
283
-		}
284
-	}
285
-
286
-	public static function checkMaintenanceMode() {
287
-		// Allow ajax update script to execute without being stopped
288
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
289
-			// send http status 503
290
-			http_response_code(503);
291
-			header('Retry-After: 120');
292
-
293
-			// render error page
294
-			$template = new OC_Template('', 'update.user', 'guest');
295
-			OC_Util::addScript('maintenance-check');
296
-			OC_Util::addStyle('core', 'guest');
297
-			$template->printPage();
298
-			die();
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * Prints the upgrade page
304
-	 *
305
-	 * @param \OC\SystemConfig $systemConfig
306
-	 */
307
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
308
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
309
-		$tooBig = false;
310
-		if (!$disableWebUpdater) {
311
-			$apps = \OC::$server->getAppManager();
312
-			if ($apps->isInstalled('user_ldap')) {
313
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
314
-
315
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
316
-					->from('ldap_user_mapping')
317
-					->execute();
318
-				$row = $result->fetch();
319
-				$result->closeCursor();
320
-
321
-				$tooBig = ($row['user_count'] > 50);
322
-			}
323
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
324
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
325
-
326
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
327
-					->from('user_saml_users')
328
-					->execute();
329
-				$row = $result->fetch();
330
-				$result->closeCursor();
331
-
332
-				$tooBig = ($row['user_count'] > 50);
333
-			}
334
-			if (!$tooBig) {
335
-				// count users
336
-				$stats = \OC::$server->getUserManager()->countUsers();
337
-				$totalUsers = array_sum($stats);
338
-				$tooBig = ($totalUsers > 50);
339
-			}
340
-		}
341
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
342
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
343
-
344
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
345
-			// send http status 503
346
-			http_response_code(503);
347
-			header('Retry-After: 120');
348
-
349
-			// render error page
350
-			$template = new OC_Template('', 'update.use-cli', 'guest');
351
-			$template->assign('productName', 'nextcloud'); // for now
352
-			$template->assign('version', OC_Util::getVersionString());
353
-			$template->assign('tooBig', $tooBig);
354
-
355
-			$template->printPage();
356
-			die();
357
-		}
358
-
359
-		// check whether this is a core update or apps update
360
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
361
-		$currentVersion = implode('.', \OCP\Util::getVersion());
362
-
363
-		// if not a core upgrade, then it's apps upgrade
364
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
365
-
366
-		$oldTheme = $systemConfig->getValue('theme');
367
-		$systemConfig->setValue('theme', '');
368
-		OC_Util::addScript('config'); // needed for web root
369
-		OC_Util::addScript('update');
370
-
371
-		/** @var \OC\App\AppManager $appManager */
372
-		$appManager = \OC::$server->getAppManager();
373
-
374
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
375
-		$tmpl->assign('version', OC_Util::getVersionString());
376
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
377
-
378
-		// get third party apps
379
-		$ocVersion = \OCP\Util::getVersion();
380
-		$ocVersion = implode('.', $ocVersion);
381
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
382
-		$incompatibleShippedApps = [];
383
-		foreach ($incompatibleApps as $appInfo) {
384
-			if ($appManager->isShipped($appInfo['id'])) {
385
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
386
-			}
387
-		}
388
-
389
-		if (!empty($incompatibleShippedApps)) {
390
-			$l = \OC::$server->getL10N('core');
391
-			$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)]);
392
-			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);
393
-		}
394
-
395
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
396
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
397
-		$tmpl->assign('productName', 'Nextcloud'); // for now
398
-		$tmpl->assign('oldTheme', $oldTheme);
399
-		$tmpl->printPage();
400
-	}
401
-
402
-	public static function initSession() {
403
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
404
-			ini_set('session.cookie_secure', true);
405
-		}
406
-
407
-		// prevents javascript from accessing php session cookies
408
-		ini_set('session.cookie_httponly', 'true');
409
-
410
-		// set the cookie path to the Nextcloud directory
411
-		$cookie_path = OC::$WEBROOT ? : '/';
412
-		ini_set('session.cookie_path', $cookie_path);
413
-
414
-		// Let the session name be changed in the initSession Hook
415
-		$sessionName = OC_Util::getInstanceId();
416
-
417
-		try {
418
-			// Allow session apps to create a custom session object
419
-			$useCustomSession = false;
420
-			$session = self::$server->getSession();
421
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
422
-			if (!$useCustomSession) {
423
-				// set the session name to the instance id - which is unique
424
-				$session = new \OC\Session\Internal($sessionName);
425
-			}
426
-
427
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
-			$session = $cryptoWrapper->wrapSession($session);
429
-			self::$server->setSession($session);
430
-
431
-			// if session can't be started break with http 500 error
432
-		} catch (Exception $e) {
433
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
-			//show the user a detailed error page
435
-			OC_Template::printExceptionErrorPage($e, 500);
436
-			die();
437
-		}
438
-
439
-		$sessionLifeTime = self::getSessionLifeTime();
440
-
441
-		// session timeout
442
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
-			if (isset($_COOKIE[session_name()])) {
444
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
-			}
446
-			\OC::$server->getUserSession()->logout();
447
-		}
448
-
449
-		$session->set('LAST_ACTIVITY', time());
450
-	}
451
-
452
-	/**
453
-	 * @return string
454
-	 */
455
-	private static function getSessionLifeTime() {
456
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
-	}
458
-
459
-	public static function loadAppClassPaths() {
460
-		foreach (OC_App::getEnabledApps() as $app) {
461
-			$appPath = OC_App::getAppPath($app);
462
-			if ($appPath === false) {
463
-				continue;
464
-			}
465
-
466
-			$file = $appPath . '/appinfo/classpath.php';
467
-			if (file_exists($file)) {
468
-				require_once $file;
469
-			}
470
-		}
471
-	}
472
-
473
-	/**
474
-	 * Try to set some values to the required Nextcloud default
475
-	 */
476
-	public static function setRequiredIniValues() {
477
-		@ini_set('default_charset', 'UTF-8');
478
-		@ini_set('gd.jpeg_ignore_warning', '1');
479
-	}
480
-
481
-	/**
482
-	 * Send the same site cookies
483
-	 */
484
-	private static function sendSameSiteCookies() {
485
-		$cookieParams = session_get_cookie_params();
486
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
487
-		$policies = [
488
-			'lax',
489
-			'strict',
490
-		];
491
-
492
-		// Append __Host to the cookie if it meets the requirements
493
-		$cookiePrefix = '';
494
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
495
-			$cookiePrefix = '__Host-';
496
-		}
497
-
498
-		foreach($policies as $policy) {
499
-			header(
500
-				sprintf(
501
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
502
-					$cookiePrefix,
503
-					$policy,
504
-					$cookieParams['path'],
505
-					$policy
506
-				),
507
-				false
508
-			);
509
-		}
510
-	}
511
-
512
-	/**
513
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
514
-	 * be set in every request if cookies are sent to add a second level of
515
-	 * defense against CSRF.
516
-	 *
517
-	 * If the cookie is not sent this will set the cookie and reload the page.
518
-	 * We use an additional cookie since we want to protect logout CSRF and
519
-	 * also we can't directly interfere with PHP's session mechanism.
520
-	 */
521
-	private static function performSameSiteCookieProtection() {
522
-		$request = \OC::$server->getRequest();
523
-
524
-		// Some user agents are notorious and don't really properly follow HTTP
525
-		// specifications. For those, have an automated opt-out. Since the protection
526
-		// for remote.php is applied in base.php as starting point we need to opt out
527
-		// here.
528
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
529
-
530
-		// Fallback, if csrf.optout is unset
531
-		if (!is_array($incompatibleUserAgents)) {
532
-			$incompatibleUserAgents = [
533
-				// OS X Finder
534
-				'/^WebDAVFS/',
535
-				// Windows webdav drive
536
-				'/^Microsoft-WebDAV-MiniRedir/',
537
-			];
538
-		}
539
-
540
-		if($request->isUserAgent($incompatibleUserAgents)) {
541
-			return;
542
-		}
543
-
544
-		if(count($_COOKIE) > 0) {
545
-			$requestUri = $request->getScriptName();
546
-			$processingScript = explode('/', $requestUri);
547
-			$processingScript = $processingScript[count($processingScript)-1];
548
-
549
-			// index.php routes are handled in the middleware
550
-			if($processingScript === 'index.php') {
551
-				return;
552
-			}
553
-
554
-			// All other endpoints require the lax and the strict cookie
555
-			if(!$request->passesStrictCookieCheck()) {
556
-				self::sendSameSiteCookies();
557
-				// Debug mode gets access to the resources without strict cookie
558
-				// due to the fact that the SabreDAV browser also lives there.
559
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
560
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
561
-					exit();
562
-				}
563
-			}
564
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
565
-			self::sendSameSiteCookies();
566
-		}
567
-	}
568
-
569
-	public static function init() {
570
-		// calculate the root directories
571
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
572
-
573
-		// register autoloader
574
-		$loaderStart = microtime(true);
575
-		require_once __DIR__ . '/autoloader.php';
576
-		self::$loader = new \OC\Autoloader([
577
-			OC::$SERVERROOT . '/lib/private/legacy',
578
-		]);
579
-		if (defined('PHPUNIT_RUN')) {
580
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
581
-		}
582
-		spl_autoload_register(array(self::$loader, 'load'));
583
-		$loaderEnd = microtime(true);
584
-
585
-		self::$CLI = (php_sapi_name() == 'cli');
586
-
587
-		// Add default composer PSR-4 autoloader
588
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
589
-
590
-		try {
591
-			self::initPaths();
592
-			// setup 3rdparty autoloader
593
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
594
-			if (!file_exists($vendorAutoLoad)) {
595
-				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".');
596
-			}
597
-			require_once $vendorAutoLoad;
598
-
599
-		} catch (\RuntimeException $e) {
600
-			if (!self::$CLI) {
601
-				http_response_code(503);
602
-			}
603
-			// we can't use the template error page here, because this needs the
604
-			// DI container which isn't available yet
605
-			print($e->getMessage());
606
-			exit();
607
-		}
608
-
609
-		// setup the basic server
610
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
611
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
612
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
613
-
614
-		// Don't display errors and log them
615
-		error_reporting(E_ALL | E_STRICT);
616
-		@ini_set('display_errors', '0');
617
-		@ini_set('log_errors', '1');
618
-
619
-		if(!date_default_timezone_set('UTC')) {
620
-			throw new \RuntimeException('Could not set timezone to UTC');
621
-		}
622
-
623
-		//try to configure php to enable big file uploads.
624
-		//this doesn´t work always depending on the webserver and php configuration.
625
-		//Let´s try to overwrite some defaults anyway
626
-
627
-		//try to set the maximum execution time to 60min
628
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
629
-			@set_time_limit(3600);
630
-		}
631
-		@ini_set('max_execution_time', '3600');
632
-		@ini_set('max_input_time', '3600');
633
-
634
-		//try to set the maximum filesize to 10G
635
-		@ini_set('upload_max_filesize', '10G');
636
-		@ini_set('post_max_size', '10G');
637
-		@ini_set('file_uploads', '50');
638
-
639
-		self::setRequiredIniValues();
640
-		self::handleAuthHeaders();
641
-		self::registerAutoloaderCache();
642
-
643
-		// initialize intl fallback is necessary
644
-		\Patchwork\Utf8\Bootup::initIntl();
645
-		OC_Util::isSetLocaleWorking();
646
-
647
-		if (!defined('PHPUNIT_RUN')) {
648
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
649
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
650
-			OC\Log\ErrorHandler::register($debug);
651
-		}
652
-
653
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
654
-		OC_App::loadApps(array('session'));
655
-		if (!self::$CLI) {
656
-			self::initSession();
657
-		}
658
-		\OC::$server->getEventLogger()->end('init_session');
659
-		self::checkConfig();
660
-		self::checkInstalled();
661
-
662
-		OC_Response::addSecurityHeaders();
663
-
664
-		self::performSameSiteCookieProtection();
665
-
666
-		if (!defined('OC_CONSOLE')) {
667
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
668
-			if (count($errors) > 0) {
669
-				if (self::$CLI) {
670
-					// Convert l10n string into regular string for usage in database
671
-					$staticErrors = [];
672
-					foreach ($errors as $error) {
673
-						echo $error['error'] . "\n";
674
-						echo $error['hint'] . "\n\n";
675
-						$staticErrors[] = [
676
-							'error' => (string)$error['error'],
677
-							'hint' => (string)$error['hint'],
678
-						];
679
-					}
680
-
681
-					try {
682
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
683
-					} catch (\Exception $e) {
684
-						echo('Writing to database failed');
685
-					}
686
-					exit(1);
687
-				} else {
688
-					http_response_code(503);
689
-					OC_Util::addStyle('guest');
690
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
691
-					exit;
692
-				}
693
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
-			}
696
-		}
697
-		//try to set the session lifetime
698
-		$sessionLifeTime = self::getSessionLifeTime();
699
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
-
701
-		$systemConfig = \OC::$server->getSystemConfig();
702
-
703
-		// User and Groups
704
-		if (!$systemConfig->getValue("installed", false)) {
705
-			self::$server->getSession()->set('user_id', '');
706
-		}
707
-
708
-		OC_User::useBackend(new \OC\User\Database());
709
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
-
711
-		// Subscribe to the hook
712
-		\OCP\Util::connectHook(
713
-			'\OCA\Files_Sharing\API\Server2Server',
714
-			'preLoginNameUsedAsUserName',
715
-			'\OC\User\Database',
716
-			'preLoginNameUsedAsUserName'
717
-		);
718
-
719
-		//setup extra user backends
720
-		if (!\OCP\Util::needUpgrade()) {
721
-			OC_User::setupBackends();
722
-		} else {
723
-			// Run upgrades in incognito mode
724
-			OC_User::setIncognitoMode(true);
725
-		}
726
-
727
-		self::registerCleanupHooks();
728
-		self::registerFilesystemHooks();
729
-		self::registerShareHooks();
730
-		self::registerEncryptionWrapper();
731
-		self::registerEncryptionHooks();
732
-		self::registerAccountHooks();
733
-
734
-		// Make sure that the application class is not loaded before the database is setup
735
-		if ($systemConfig->getValue("installed", false)) {
736
-			$settings = new \OC\Settings\Application();
737
-			$settings->register();
738
-		}
739
-
740
-		//make sure temporary files are cleaned up
741
-		$tmpManager = \OC::$server->getTempManager();
742
-		register_shutdown_function(array($tmpManager, 'clean'));
743
-		$lockProvider = \OC::$server->getLockingProvider();
744
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
745
-
746
-		// Check whether the sample configuration has been copied
747
-		if($systemConfig->getValue('copied_sample_config', false)) {
748
-			$l = \OC::$server->getL10N('lib');
749
-			OC_Template::printErrorPage(
750
-				$l->t('Sample configuration detected'),
751
-				$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'),
752
-				503
753
-			);
754
-			return;
755
-		}
756
-
757
-		$request = \OC::$server->getRequest();
758
-		$host = $request->getInsecureServerHost();
759
-		/**
760
-		 * if the host passed in headers isn't trusted
761
-		 * FIXME: Should not be in here at all :see_no_evil:
762
-		 */
763
-		if (!OC::$CLI
764
-			// overwritehost is always trusted, workaround to not have to make
765
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
766
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
767
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
-			&& self::$server->getConfig()->getSystemValue('installed', false)
769
-		) {
770
-			// Allow access to CSS resources
771
-			$isScssRequest = false;
772
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
773
-				$isScssRequest = true;
774
-			}
775
-
776
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
777
-				http_response_code(400);
778
-				header('Content-Type: application/json');
779
-				echo '{"error": "Trusted domain error.", "code": 15}';
780
-				exit();
781
-			}
782
-
783
-			if (!$isScssRequest) {
784
-				http_response_code(400);
785
-
786
-				\OC::$server->getLogger()->info(
787
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
-					[
789
-						'app' => 'core',
790
-						'remoteAddress' => $request->getRemoteAddress(),
791
-						'host' => $host,
792
-					]
793
-				);
794
-
795
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
-				$tmpl->printPage();
798
-
799
-				exit();
800
-			}
801
-		}
802
-		\OC::$server->getEventLogger()->end('boot');
803
-	}
804
-
805
-	/**
806
-	 * register hooks for the cleanup of cache and bruteforce protection
807
-	 */
808
-	public static function registerCleanupHooks() {
809
-		//don't try to do this before we are properly setup
810
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
-
812
-			// NOTE: This will be replaced to use OCP
813
-			$userSession = self::$server->getUserSession();
814
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
-				if (!defined('PHPUNIT_RUN')) {
816
-					// reset brute force delay for this IP address and username
817
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
818
-					$request = \OC::$server->getRequest();
819
-					$throttler = \OC::$server->getBruteForceThrottler();
820
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
-				}
822
-
823
-				try {
824
-					$cache = new \OC\Cache\File();
825
-					$cache->gc();
826
-				} catch (\OC\ServerNotAvailableException $e) {
827
-					// not a GC exception, pass it on
828
-					throw $e;
829
-				} catch (\OC\ForbiddenException $e) {
830
-					// filesystem blocked for this request, ignore
831
-				} catch (\Exception $e) {
832
-					// a GC exception should not prevent users from using OC,
833
-					// so log the exception
834
-					\OC::$server->getLogger()->logException($e, [
835
-						'message' => 'Exception when running cache gc.',
836
-						'level' => ILogger::WARN,
837
-						'app' => 'core',
838
-					]);
839
-				}
840
-			});
841
-		}
842
-	}
843
-
844
-	private static function registerEncryptionWrapper() {
845
-		$manager = self::$server->getEncryptionManager();
846
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
-	}
848
-
849
-	private static function registerEncryptionHooks() {
850
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
851
-		if ($enabled) {
852
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
-		}
857
-	}
858
-
859
-	private static function registerAccountHooks() {
860
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
-	}
863
-
864
-	/**
865
-	 * register hooks for the filesystem
866
-	 */
867
-	public static function registerFilesystemHooks() {
868
-		// Check for blacklisted files
869
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
870
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
871
-	}
872
-
873
-	/**
874
-	 * register hooks for sharing
875
-	 */
876
-	public static function registerShareHooks() {
877
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
878
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
879
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
880
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
881
-		}
882
-	}
883
-
884
-	protected static function registerAutoloaderCache() {
885
-		// The class loader takes an optional low-latency cache, which MUST be
886
-		// namespaced. The instanceid is used for namespacing, but might be
887
-		// unavailable at this point. Furthermore, it might not be possible to
888
-		// generate an instanceid via \OC_Util::getInstanceId() because the
889
-		// config file may not be writable. As such, we only register a class
890
-		// loader cache if instanceid is available without trying to create one.
891
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
892
-		if ($instanceId) {
893
-			try {
894
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
895
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
896
-			} catch (\Exception $ex) {
897
-			}
898
-		}
899
-	}
900
-
901
-	/**
902
-	 * Handle the request
903
-	 */
904
-	public static function handleRequest() {
905
-
906
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
907
-		$systemConfig = \OC::$server->getSystemConfig();
908
-		// load all the classpaths from the enabled apps so they are available
909
-		// in the routing files of each app
910
-		OC::loadAppClassPaths();
911
-
912
-		// Check if Nextcloud is installed or in maintenance (update) mode
913
-		if (!$systemConfig->getValue('installed', false)) {
914
-			\OC::$server->getSession()->clear();
915
-			$setupHelper = new OC\Setup(
916
-				$systemConfig,
917
-				\OC::$server->getIniWrapper(),
918
-				\OC::$server->getL10N('lib'),
919
-				\OC::$server->query(\OCP\Defaults::class),
920
-				\OC::$server->getLogger(),
921
-				\OC::$server->getSecureRandom(),
922
-				\OC::$server->query(\OC\Installer::class)
923
-			);
924
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
925
-			$controller->run($_POST);
926
-			exit();
927
-		}
928
-
929
-		$request = \OC::$server->getRequest();
930
-		$requestPath = $request->getRawPathInfo();
931
-		if ($requestPath === '/heartbeat') {
932
-			return;
933
-		}
934
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
935
-			self::checkMaintenanceMode();
936
-
937
-			if (\OCP\Util::needUpgrade()) {
938
-				if (function_exists('opcache_reset')) {
939
-					opcache_reset();
940
-				}
941
-				if (!$systemConfig->getValue('maintenance', false)) {
942
-					self::printUpgradePage($systemConfig);
943
-					exit();
944
-				}
945
-			}
946
-		}
947
-
948
-		// emergency app disabling
949
-		if ($requestPath === '/disableapp'
950
-			&& $request->getMethod() === 'POST'
951
-			&& ((array)$request->getParam('appid')) !== ''
952
-		) {
953
-			\OC_JSON::callCheck();
954
-			\OC_JSON::checkAdminUser();
955
-			$appIds = (array)$request->getParam('appid');
956
-			foreach($appIds as $appId) {
957
-				$appId = \OC_App::cleanAppId($appId);
958
-				\OC::$server->getAppManager()->disableApp($appId);
959
-			}
960
-			\OC_JSON::success();
961
-			exit();
962
-		}
963
-
964
-		// Always load authentication apps
965
-		OC_App::loadApps(['authentication']);
966
-
967
-		// Load minimum set of apps
968
-		if (!\OCP\Util::needUpgrade()
969
-			&& !$systemConfig->getValue('maintenance', false)) {
970
-			// For logged-in users: Load everything
971
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
972
-				OC_App::loadApps();
973
-			} else {
974
-				// For guests: Load only filesystem and logging
975
-				OC_App::loadApps(array('filesystem', 'logging'));
976
-				self::handleLogin($request);
977
-			}
978
-		}
979
-
980
-		if (!self::$CLI) {
981
-			try {
982
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
983
-					OC_App::loadApps(array('filesystem', 'logging'));
984
-					OC_App::loadApps();
985
-				}
986
-				OC_Util::setupFS();
987
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
988
-				return;
989
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
990
-				//header('HTTP/1.0 404 Not Found');
991
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
992
-				http_response_code(405);
993
-				return;
994
-			}
995
-		}
996
-
997
-		// Handle WebDAV
998
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
999
-			// not allowed any more to prevent people
1000
-			// mounting this root directly.
1001
-			// Users need to mount remote.php/webdav instead.
1002
-			http_response_code(405);
1003
-			return;
1004
-		}
1005
-
1006
-		// Someone is logged in
1007
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1008
-			OC_App::loadApps();
1009
-			OC_User::setupBackends();
1010
-			OC_Util::setupFS();
1011
-			// FIXME
1012
-			// Redirect to default application
1013
-			OC_Util::redirectToDefaultPage();
1014
-		} else {
1015
-			// Not handled and not logged in
1016
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1017
-		}
1018
-	}
1019
-
1020
-	/**
1021
-	 * Check login: apache auth, auth token, basic auth
1022
-	 *
1023
-	 * @param OCP\IRequest $request
1024
-	 * @return boolean
1025
-	 */
1026
-	static function handleLogin(OCP\IRequest $request) {
1027
-		$userSession = self::$server->getUserSession();
1028
-		if (OC_User::handleApacheAuth()) {
1029
-			return true;
1030
-		}
1031
-		if ($userSession->tryTokenLogin($request)) {
1032
-			return true;
1033
-		}
1034
-		if (isset($_COOKIE['nc_username'])
1035
-			&& isset($_COOKIE['nc_token'])
1036
-			&& isset($_COOKIE['nc_session_id'])
1037
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1038
-			return true;
1039
-		}
1040
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1041
-			return true;
1042
-		}
1043
-		return false;
1044
-	}
1045
-
1046
-	protected static function handleAuthHeaders() {
1047
-		//copy http auth headers for apache+php-fcgid work around
1048
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1049
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1050
-		}
1051
-
1052
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1053
-		$vars = array(
1054
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1055
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1056
-		);
1057
-		foreach ($vars as $var) {
1058
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1059
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1060
-				$_SERVER['PHP_AUTH_USER'] = $name;
1061
-				$_SERVER['PHP_AUTH_PW'] = $password;
1062
-				break;
1063
-			}
1064
-		}
1065
-	}
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 $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
+                echo "\n";
254
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
+                exit;
257
+            } else {
258
+                OC_Template::printErrorPage(
259
+                    $l->t('Cannot write into "config" directory!'),
260
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
+                    [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
+                    [ $urlGenerator->linkToDocs('admin-config') ] ),
264
+                    503
265
+                );
266
+            }
267
+        }
268
+    }
269
+
270
+    public static function checkInstalled() {
271
+        if (defined('OC_CONSOLE')) {
272
+            return;
273
+        }
274
+        // Redirect to installer if not installed
275
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
+            if (OC::$CLI) {
277
+                throw new Exception('Not installed');
278
+            } else {
279
+                $url = OC::$WEBROOT . '/index.php';
280
+                header('Location: ' . $url);
281
+            }
282
+            exit();
283
+        }
284
+    }
285
+
286
+    public static function checkMaintenanceMode() {
287
+        // Allow ajax update script to execute without being stopped
288
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
289
+            // send http status 503
290
+            http_response_code(503);
291
+            header('Retry-After: 120');
292
+
293
+            // render error page
294
+            $template = new OC_Template('', 'update.user', 'guest');
295
+            OC_Util::addScript('maintenance-check');
296
+            OC_Util::addStyle('core', 'guest');
297
+            $template->printPage();
298
+            die();
299
+        }
300
+    }
301
+
302
+    /**
303
+     * Prints the upgrade page
304
+     *
305
+     * @param \OC\SystemConfig $systemConfig
306
+     */
307
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
308
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
309
+        $tooBig = false;
310
+        if (!$disableWebUpdater) {
311
+            $apps = \OC::$server->getAppManager();
312
+            if ($apps->isInstalled('user_ldap')) {
313
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
314
+
315
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
316
+                    ->from('ldap_user_mapping')
317
+                    ->execute();
318
+                $row = $result->fetch();
319
+                $result->closeCursor();
320
+
321
+                $tooBig = ($row['user_count'] > 50);
322
+            }
323
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
324
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
325
+
326
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
327
+                    ->from('user_saml_users')
328
+                    ->execute();
329
+                $row = $result->fetch();
330
+                $result->closeCursor();
331
+
332
+                $tooBig = ($row['user_count'] > 50);
333
+            }
334
+            if (!$tooBig) {
335
+                // count users
336
+                $stats = \OC::$server->getUserManager()->countUsers();
337
+                $totalUsers = array_sum($stats);
338
+                $tooBig = ($totalUsers > 50);
339
+            }
340
+        }
341
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
342
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
343
+
344
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
345
+            // send http status 503
346
+            http_response_code(503);
347
+            header('Retry-After: 120');
348
+
349
+            // render error page
350
+            $template = new OC_Template('', 'update.use-cli', 'guest');
351
+            $template->assign('productName', 'nextcloud'); // for now
352
+            $template->assign('version', OC_Util::getVersionString());
353
+            $template->assign('tooBig', $tooBig);
354
+
355
+            $template->printPage();
356
+            die();
357
+        }
358
+
359
+        // check whether this is a core update or apps update
360
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
361
+        $currentVersion = implode('.', \OCP\Util::getVersion());
362
+
363
+        // if not a core upgrade, then it's apps upgrade
364
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
365
+
366
+        $oldTheme = $systemConfig->getValue('theme');
367
+        $systemConfig->setValue('theme', '');
368
+        OC_Util::addScript('config'); // needed for web root
369
+        OC_Util::addScript('update');
370
+
371
+        /** @var \OC\App\AppManager $appManager */
372
+        $appManager = \OC::$server->getAppManager();
373
+
374
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
375
+        $tmpl->assign('version', OC_Util::getVersionString());
376
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
377
+
378
+        // get third party apps
379
+        $ocVersion = \OCP\Util::getVersion();
380
+        $ocVersion = implode('.', $ocVersion);
381
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
382
+        $incompatibleShippedApps = [];
383
+        foreach ($incompatibleApps as $appInfo) {
384
+            if ($appManager->isShipped($appInfo['id'])) {
385
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
386
+            }
387
+        }
388
+
389
+        if (!empty($incompatibleShippedApps)) {
390
+            $l = \OC::$server->getL10N('core');
391
+            $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)]);
392
+            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);
393
+        }
394
+
395
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
396
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
397
+        $tmpl->assign('productName', 'Nextcloud'); // for now
398
+        $tmpl->assign('oldTheme', $oldTheme);
399
+        $tmpl->printPage();
400
+    }
401
+
402
+    public static function initSession() {
403
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
404
+            ini_set('session.cookie_secure', true);
405
+        }
406
+
407
+        // prevents javascript from accessing php session cookies
408
+        ini_set('session.cookie_httponly', 'true');
409
+
410
+        // set the cookie path to the Nextcloud directory
411
+        $cookie_path = OC::$WEBROOT ? : '/';
412
+        ini_set('session.cookie_path', $cookie_path);
413
+
414
+        // Let the session name be changed in the initSession Hook
415
+        $sessionName = OC_Util::getInstanceId();
416
+
417
+        try {
418
+            // Allow session apps to create a custom session object
419
+            $useCustomSession = false;
420
+            $session = self::$server->getSession();
421
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
422
+            if (!$useCustomSession) {
423
+                // set the session name to the instance id - which is unique
424
+                $session = new \OC\Session\Internal($sessionName);
425
+            }
426
+
427
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
+            $session = $cryptoWrapper->wrapSession($session);
429
+            self::$server->setSession($session);
430
+
431
+            // if session can't be started break with http 500 error
432
+        } catch (Exception $e) {
433
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
+            //show the user a detailed error page
435
+            OC_Template::printExceptionErrorPage($e, 500);
436
+            die();
437
+        }
438
+
439
+        $sessionLifeTime = self::getSessionLifeTime();
440
+
441
+        // session timeout
442
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
+            if (isset($_COOKIE[session_name()])) {
444
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
+            }
446
+            \OC::$server->getUserSession()->logout();
447
+        }
448
+
449
+        $session->set('LAST_ACTIVITY', time());
450
+    }
451
+
452
+    /**
453
+     * @return string
454
+     */
455
+    private static function getSessionLifeTime() {
456
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
+    }
458
+
459
+    public static function loadAppClassPaths() {
460
+        foreach (OC_App::getEnabledApps() as $app) {
461
+            $appPath = OC_App::getAppPath($app);
462
+            if ($appPath === false) {
463
+                continue;
464
+            }
465
+
466
+            $file = $appPath . '/appinfo/classpath.php';
467
+            if (file_exists($file)) {
468
+                require_once $file;
469
+            }
470
+        }
471
+    }
472
+
473
+    /**
474
+     * Try to set some values to the required Nextcloud default
475
+     */
476
+    public static function setRequiredIniValues() {
477
+        @ini_set('default_charset', 'UTF-8');
478
+        @ini_set('gd.jpeg_ignore_warning', '1');
479
+    }
480
+
481
+    /**
482
+     * Send the same site cookies
483
+     */
484
+    private static function sendSameSiteCookies() {
485
+        $cookieParams = session_get_cookie_params();
486
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
487
+        $policies = [
488
+            'lax',
489
+            'strict',
490
+        ];
491
+
492
+        // Append __Host to the cookie if it meets the requirements
493
+        $cookiePrefix = '';
494
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
495
+            $cookiePrefix = '__Host-';
496
+        }
497
+
498
+        foreach($policies as $policy) {
499
+            header(
500
+                sprintf(
501
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
502
+                    $cookiePrefix,
503
+                    $policy,
504
+                    $cookieParams['path'],
505
+                    $policy
506
+                ),
507
+                false
508
+            );
509
+        }
510
+    }
511
+
512
+    /**
513
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
514
+     * be set in every request if cookies are sent to add a second level of
515
+     * defense against CSRF.
516
+     *
517
+     * If the cookie is not sent this will set the cookie and reload the page.
518
+     * We use an additional cookie since we want to protect logout CSRF and
519
+     * also we can't directly interfere with PHP's session mechanism.
520
+     */
521
+    private static function performSameSiteCookieProtection() {
522
+        $request = \OC::$server->getRequest();
523
+
524
+        // Some user agents are notorious and don't really properly follow HTTP
525
+        // specifications. For those, have an automated opt-out. Since the protection
526
+        // for remote.php is applied in base.php as starting point we need to opt out
527
+        // here.
528
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
529
+
530
+        // Fallback, if csrf.optout is unset
531
+        if (!is_array($incompatibleUserAgents)) {
532
+            $incompatibleUserAgents = [
533
+                // OS X Finder
534
+                '/^WebDAVFS/',
535
+                // Windows webdav drive
536
+                '/^Microsoft-WebDAV-MiniRedir/',
537
+            ];
538
+        }
539
+
540
+        if($request->isUserAgent($incompatibleUserAgents)) {
541
+            return;
542
+        }
543
+
544
+        if(count($_COOKIE) > 0) {
545
+            $requestUri = $request->getScriptName();
546
+            $processingScript = explode('/', $requestUri);
547
+            $processingScript = $processingScript[count($processingScript)-1];
548
+
549
+            // index.php routes are handled in the middleware
550
+            if($processingScript === 'index.php') {
551
+                return;
552
+            }
553
+
554
+            // All other endpoints require the lax and the strict cookie
555
+            if(!$request->passesStrictCookieCheck()) {
556
+                self::sendSameSiteCookies();
557
+                // Debug mode gets access to the resources without strict cookie
558
+                // due to the fact that the SabreDAV browser also lives there.
559
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
560
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
561
+                    exit();
562
+                }
563
+            }
564
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
565
+            self::sendSameSiteCookies();
566
+        }
567
+    }
568
+
569
+    public static function init() {
570
+        // calculate the root directories
571
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
572
+
573
+        // register autoloader
574
+        $loaderStart = microtime(true);
575
+        require_once __DIR__ . '/autoloader.php';
576
+        self::$loader = new \OC\Autoloader([
577
+            OC::$SERVERROOT . '/lib/private/legacy',
578
+        ]);
579
+        if (defined('PHPUNIT_RUN')) {
580
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
581
+        }
582
+        spl_autoload_register(array(self::$loader, 'load'));
583
+        $loaderEnd = microtime(true);
584
+
585
+        self::$CLI = (php_sapi_name() == 'cli');
586
+
587
+        // Add default composer PSR-4 autoloader
588
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
589
+
590
+        try {
591
+            self::initPaths();
592
+            // setup 3rdparty autoloader
593
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
594
+            if (!file_exists($vendorAutoLoad)) {
595
+                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".');
596
+            }
597
+            require_once $vendorAutoLoad;
598
+
599
+        } catch (\RuntimeException $e) {
600
+            if (!self::$CLI) {
601
+                http_response_code(503);
602
+            }
603
+            // we can't use the template error page here, because this needs the
604
+            // DI container which isn't available yet
605
+            print($e->getMessage());
606
+            exit();
607
+        }
608
+
609
+        // setup the basic server
610
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
611
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
612
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
613
+
614
+        // Don't display errors and log them
615
+        error_reporting(E_ALL | E_STRICT);
616
+        @ini_set('display_errors', '0');
617
+        @ini_set('log_errors', '1');
618
+
619
+        if(!date_default_timezone_set('UTC')) {
620
+            throw new \RuntimeException('Could not set timezone to UTC');
621
+        }
622
+
623
+        //try to configure php to enable big file uploads.
624
+        //this doesn´t work always depending on the webserver and php configuration.
625
+        //Let´s try to overwrite some defaults anyway
626
+
627
+        //try to set the maximum execution time to 60min
628
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
629
+            @set_time_limit(3600);
630
+        }
631
+        @ini_set('max_execution_time', '3600');
632
+        @ini_set('max_input_time', '3600');
633
+
634
+        //try to set the maximum filesize to 10G
635
+        @ini_set('upload_max_filesize', '10G');
636
+        @ini_set('post_max_size', '10G');
637
+        @ini_set('file_uploads', '50');
638
+
639
+        self::setRequiredIniValues();
640
+        self::handleAuthHeaders();
641
+        self::registerAutoloaderCache();
642
+
643
+        // initialize intl fallback is necessary
644
+        \Patchwork\Utf8\Bootup::initIntl();
645
+        OC_Util::isSetLocaleWorking();
646
+
647
+        if (!defined('PHPUNIT_RUN')) {
648
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
649
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
650
+            OC\Log\ErrorHandler::register($debug);
651
+        }
652
+
653
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
654
+        OC_App::loadApps(array('session'));
655
+        if (!self::$CLI) {
656
+            self::initSession();
657
+        }
658
+        \OC::$server->getEventLogger()->end('init_session');
659
+        self::checkConfig();
660
+        self::checkInstalled();
661
+
662
+        OC_Response::addSecurityHeaders();
663
+
664
+        self::performSameSiteCookieProtection();
665
+
666
+        if (!defined('OC_CONSOLE')) {
667
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
668
+            if (count($errors) > 0) {
669
+                if (self::$CLI) {
670
+                    // Convert l10n string into regular string for usage in database
671
+                    $staticErrors = [];
672
+                    foreach ($errors as $error) {
673
+                        echo $error['error'] . "\n";
674
+                        echo $error['hint'] . "\n\n";
675
+                        $staticErrors[] = [
676
+                            'error' => (string)$error['error'],
677
+                            'hint' => (string)$error['hint'],
678
+                        ];
679
+                    }
680
+
681
+                    try {
682
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
683
+                    } catch (\Exception $e) {
684
+                        echo('Writing to database failed');
685
+                    }
686
+                    exit(1);
687
+                } else {
688
+                    http_response_code(503);
689
+                    OC_Util::addStyle('guest');
690
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
691
+                    exit;
692
+                }
693
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
+            }
696
+        }
697
+        //try to set the session lifetime
698
+        $sessionLifeTime = self::getSessionLifeTime();
699
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
+
701
+        $systemConfig = \OC::$server->getSystemConfig();
702
+
703
+        // User and Groups
704
+        if (!$systemConfig->getValue("installed", false)) {
705
+            self::$server->getSession()->set('user_id', '');
706
+        }
707
+
708
+        OC_User::useBackend(new \OC\User\Database());
709
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
+
711
+        // Subscribe to the hook
712
+        \OCP\Util::connectHook(
713
+            '\OCA\Files_Sharing\API\Server2Server',
714
+            'preLoginNameUsedAsUserName',
715
+            '\OC\User\Database',
716
+            'preLoginNameUsedAsUserName'
717
+        );
718
+
719
+        //setup extra user backends
720
+        if (!\OCP\Util::needUpgrade()) {
721
+            OC_User::setupBackends();
722
+        } else {
723
+            // Run upgrades in incognito mode
724
+            OC_User::setIncognitoMode(true);
725
+        }
726
+
727
+        self::registerCleanupHooks();
728
+        self::registerFilesystemHooks();
729
+        self::registerShareHooks();
730
+        self::registerEncryptionWrapper();
731
+        self::registerEncryptionHooks();
732
+        self::registerAccountHooks();
733
+
734
+        // Make sure that the application class is not loaded before the database is setup
735
+        if ($systemConfig->getValue("installed", false)) {
736
+            $settings = new \OC\Settings\Application();
737
+            $settings->register();
738
+        }
739
+
740
+        //make sure temporary files are cleaned up
741
+        $tmpManager = \OC::$server->getTempManager();
742
+        register_shutdown_function(array($tmpManager, 'clean'));
743
+        $lockProvider = \OC::$server->getLockingProvider();
744
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
745
+
746
+        // Check whether the sample configuration has been copied
747
+        if($systemConfig->getValue('copied_sample_config', false)) {
748
+            $l = \OC::$server->getL10N('lib');
749
+            OC_Template::printErrorPage(
750
+                $l->t('Sample configuration detected'),
751
+                $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'),
752
+                503
753
+            );
754
+            return;
755
+        }
756
+
757
+        $request = \OC::$server->getRequest();
758
+        $host = $request->getInsecureServerHost();
759
+        /**
760
+         * if the host passed in headers isn't trusted
761
+         * FIXME: Should not be in here at all :see_no_evil:
762
+         */
763
+        if (!OC::$CLI
764
+            // overwritehost is always trusted, workaround to not have to make
765
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
766
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
767
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
+            && self::$server->getConfig()->getSystemValue('installed', false)
769
+        ) {
770
+            // Allow access to CSS resources
771
+            $isScssRequest = false;
772
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
773
+                $isScssRequest = true;
774
+            }
775
+
776
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
777
+                http_response_code(400);
778
+                header('Content-Type: application/json');
779
+                echo '{"error": "Trusted domain error.", "code": 15}';
780
+                exit();
781
+            }
782
+
783
+            if (!$isScssRequest) {
784
+                http_response_code(400);
785
+
786
+                \OC::$server->getLogger()->info(
787
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
+                    [
789
+                        'app' => 'core',
790
+                        'remoteAddress' => $request->getRemoteAddress(),
791
+                        'host' => $host,
792
+                    ]
793
+                );
794
+
795
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
+                $tmpl->printPage();
798
+
799
+                exit();
800
+            }
801
+        }
802
+        \OC::$server->getEventLogger()->end('boot');
803
+    }
804
+
805
+    /**
806
+     * register hooks for the cleanup of cache and bruteforce protection
807
+     */
808
+    public static function registerCleanupHooks() {
809
+        //don't try to do this before we are properly setup
810
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
+
812
+            // NOTE: This will be replaced to use OCP
813
+            $userSession = self::$server->getUserSession();
814
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
+                if (!defined('PHPUNIT_RUN')) {
816
+                    // reset brute force delay for this IP address and username
817
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
818
+                    $request = \OC::$server->getRequest();
819
+                    $throttler = \OC::$server->getBruteForceThrottler();
820
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
+                }
822
+
823
+                try {
824
+                    $cache = new \OC\Cache\File();
825
+                    $cache->gc();
826
+                } catch (\OC\ServerNotAvailableException $e) {
827
+                    // not a GC exception, pass it on
828
+                    throw $e;
829
+                } catch (\OC\ForbiddenException $e) {
830
+                    // filesystem blocked for this request, ignore
831
+                } catch (\Exception $e) {
832
+                    // a GC exception should not prevent users from using OC,
833
+                    // so log the exception
834
+                    \OC::$server->getLogger()->logException($e, [
835
+                        'message' => 'Exception when running cache gc.',
836
+                        'level' => ILogger::WARN,
837
+                        'app' => 'core',
838
+                    ]);
839
+                }
840
+            });
841
+        }
842
+    }
843
+
844
+    private static function registerEncryptionWrapper() {
845
+        $manager = self::$server->getEncryptionManager();
846
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
+    }
848
+
849
+    private static function registerEncryptionHooks() {
850
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
851
+        if ($enabled) {
852
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
+        }
857
+    }
858
+
859
+    private static function registerAccountHooks() {
860
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
+    }
863
+
864
+    /**
865
+     * register hooks for the filesystem
866
+     */
867
+    public static function registerFilesystemHooks() {
868
+        // Check for blacklisted files
869
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
870
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
871
+    }
872
+
873
+    /**
874
+     * register hooks for sharing
875
+     */
876
+    public static function registerShareHooks() {
877
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
878
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
879
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
880
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
881
+        }
882
+    }
883
+
884
+    protected static function registerAutoloaderCache() {
885
+        // The class loader takes an optional low-latency cache, which MUST be
886
+        // namespaced. The instanceid is used for namespacing, but might be
887
+        // unavailable at this point. Furthermore, it might not be possible to
888
+        // generate an instanceid via \OC_Util::getInstanceId() because the
889
+        // config file may not be writable. As such, we only register a class
890
+        // loader cache if instanceid is available without trying to create one.
891
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
892
+        if ($instanceId) {
893
+            try {
894
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
895
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
896
+            } catch (\Exception $ex) {
897
+            }
898
+        }
899
+    }
900
+
901
+    /**
902
+     * Handle the request
903
+     */
904
+    public static function handleRequest() {
905
+
906
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
907
+        $systemConfig = \OC::$server->getSystemConfig();
908
+        // load all the classpaths from the enabled apps so they are available
909
+        // in the routing files of each app
910
+        OC::loadAppClassPaths();
911
+
912
+        // Check if Nextcloud is installed or in maintenance (update) mode
913
+        if (!$systemConfig->getValue('installed', false)) {
914
+            \OC::$server->getSession()->clear();
915
+            $setupHelper = new OC\Setup(
916
+                $systemConfig,
917
+                \OC::$server->getIniWrapper(),
918
+                \OC::$server->getL10N('lib'),
919
+                \OC::$server->query(\OCP\Defaults::class),
920
+                \OC::$server->getLogger(),
921
+                \OC::$server->getSecureRandom(),
922
+                \OC::$server->query(\OC\Installer::class)
923
+            );
924
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
925
+            $controller->run($_POST);
926
+            exit();
927
+        }
928
+
929
+        $request = \OC::$server->getRequest();
930
+        $requestPath = $request->getRawPathInfo();
931
+        if ($requestPath === '/heartbeat') {
932
+            return;
933
+        }
934
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
935
+            self::checkMaintenanceMode();
936
+
937
+            if (\OCP\Util::needUpgrade()) {
938
+                if (function_exists('opcache_reset')) {
939
+                    opcache_reset();
940
+                }
941
+                if (!$systemConfig->getValue('maintenance', false)) {
942
+                    self::printUpgradePage($systemConfig);
943
+                    exit();
944
+                }
945
+            }
946
+        }
947
+
948
+        // emergency app disabling
949
+        if ($requestPath === '/disableapp'
950
+            && $request->getMethod() === 'POST'
951
+            && ((array)$request->getParam('appid')) !== ''
952
+        ) {
953
+            \OC_JSON::callCheck();
954
+            \OC_JSON::checkAdminUser();
955
+            $appIds = (array)$request->getParam('appid');
956
+            foreach($appIds as $appId) {
957
+                $appId = \OC_App::cleanAppId($appId);
958
+                \OC::$server->getAppManager()->disableApp($appId);
959
+            }
960
+            \OC_JSON::success();
961
+            exit();
962
+        }
963
+
964
+        // Always load authentication apps
965
+        OC_App::loadApps(['authentication']);
966
+
967
+        // Load minimum set of apps
968
+        if (!\OCP\Util::needUpgrade()
969
+            && !$systemConfig->getValue('maintenance', false)) {
970
+            // For logged-in users: Load everything
971
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
972
+                OC_App::loadApps();
973
+            } else {
974
+                // For guests: Load only filesystem and logging
975
+                OC_App::loadApps(array('filesystem', 'logging'));
976
+                self::handleLogin($request);
977
+            }
978
+        }
979
+
980
+        if (!self::$CLI) {
981
+            try {
982
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
983
+                    OC_App::loadApps(array('filesystem', 'logging'));
984
+                    OC_App::loadApps();
985
+                }
986
+                OC_Util::setupFS();
987
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
988
+                return;
989
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
990
+                //header('HTTP/1.0 404 Not Found');
991
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
992
+                http_response_code(405);
993
+                return;
994
+            }
995
+        }
996
+
997
+        // Handle WebDAV
998
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
999
+            // not allowed any more to prevent people
1000
+            // mounting this root directly.
1001
+            // Users need to mount remote.php/webdav instead.
1002
+            http_response_code(405);
1003
+            return;
1004
+        }
1005
+
1006
+        // Someone is logged in
1007
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1008
+            OC_App::loadApps();
1009
+            OC_User::setupBackends();
1010
+            OC_Util::setupFS();
1011
+            // FIXME
1012
+            // Redirect to default application
1013
+            OC_Util::redirectToDefaultPage();
1014
+        } else {
1015
+            // Not handled and not logged in
1016
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1017
+        }
1018
+    }
1019
+
1020
+    /**
1021
+     * Check login: apache auth, auth token, basic auth
1022
+     *
1023
+     * @param OCP\IRequest $request
1024
+     * @return boolean
1025
+     */
1026
+    static function handleLogin(OCP\IRequest $request) {
1027
+        $userSession = self::$server->getUserSession();
1028
+        if (OC_User::handleApacheAuth()) {
1029
+            return true;
1030
+        }
1031
+        if ($userSession->tryTokenLogin($request)) {
1032
+            return true;
1033
+        }
1034
+        if (isset($_COOKIE['nc_username'])
1035
+            && isset($_COOKIE['nc_token'])
1036
+            && isset($_COOKIE['nc_session_id'])
1037
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1038
+            return true;
1039
+        }
1040
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1041
+            return true;
1042
+        }
1043
+        return false;
1044
+    }
1045
+
1046
+    protected static function handleAuthHeaders() {
1047
+        //copy http auth headers for apache+php-fcgid work around
1048
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1049
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1050
+        }
1051
+
1052
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1053
+        $vars = array(
1054
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1055
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1056
+        );
1057
+        foreach ($vars as $var) {
1058
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1059
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1060
+                $_SERVER['PHP_AUTH_USER'] = $name;
1061
+                $_SERVER['PHP_AUTH_PW'] = $password;
1062
+                break;
1063
+            }
1064
+        }
1065
+    }
1066 1066
 }
1067 1067
 
1068 1068
 OC::init();
Please login to merge, or discard this patch.
lib/private/Files/Cache/Propagator.php 1 patch
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -31,161 +31,161 @@
 block discarded – undo
31 31
  * Propagate etags and mtimes within the storage
32 32
  */
33 33
 class Propagator implements IPropagator {
34
-	private $inBatch = false;
35
-
36
-	private $batch = [];
37
-
38
-	/**
39
-	 * @var \OC\Files\Storage\Storage
40
-	 */
41
-	protected $storage;
42
-
43
-	/**
44
-	 * @var IDBConnection
45
-	 */
46
-	private $connection;
47
-
48
-	/**
49
-	 * @param \OC\Files\Storage\Storage $storage
50
-	 * @param IDBConnection $connection
51
-	 */
52
-	public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $connection) {
53
-		$this->storage = $storage;
54
-		$this->connection = $connection;
55
-	}
56
-
57
-
58
-	/**
59
-	 * @param string $internalPath
60
-	 * @param int $time
61
-	 * @param int $sizeDifference number of bytes the file has grown
62
-	 * @suppress SqlInjectionChecker
63
-	 */
64
-	public function propagateChange($internalPath, $time, $sizeDifference = 0) {
65
-		$storageId = (int)$this->storage->getStorageCache()->getNumericId();
66
-
67
-		$parents = $this->getParents($internalPath);
68
-
69
-		if ($this->inBatch) {
70
-			foreach ($parents as $parent) {
71
-				$this->addToBatch($parent, $time, $sizeDifference);
72
-			}
73
-			return;
74
-		}
75
-
76
-		$parentHashes = array_map('md5', $parents);
77
-		$etag = uniqid(); // since we give all folders the same etag we don't ask the storage for the etag
78
-
79
-		$builder = $this->connection->getQueryBuilder();
80
-		$hashParams = array_map(function ($hash) use ($builder) {
81
-			return $builder->expr()->literal($hash);
82
-		}, $parentHashes);
83
-
84
-		$builder->update('filecache')
85
-			->set('mtime', $builder->createFunction('GREATEST(' . $builder->getColumnName('mtime') . ', ' . $builder->createNamedParameter((int)$time, IQueryBuilder::PARAM_INT) . ')'))
86
-			->set('etag', $builder->createNamedParameter($etag, IQueryBuilder::PARAM_STR))
87
-			->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
88
-			->andWhere($builder->expr()->in('path_hash', $hashParams));
89
-
90
-		$builder->execute();
91
-
92
-		if ($sizeDifference !== 0) {
93
-			// we need to do size separably so we can ignore entries with uncalculated size
94
-			$builder = $this->connection->getQueryBuilder();
95
-			$builder->update('filecache')
96
-				->set('size', $builder->func()->add('size', $builder->createNamedParameter($sizeDifference)))
97
-				->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
98
-				->andWhere($builder->expr()->in('path_hash', $hashParams))
99
-				->andWhere($builder->expr()->gt('size', $builder->expr()->literal(-1, IQueryBuilder::PARAM_INT)));
100
-		}
101
-
102
-		$builder->execute();
103
-	}
104
-
105
-	protected function getParents($path) {
106
-		$parts = explode('/', $path);
107
-		$parent = '';
108
-		$parents = [];
109
-		foreach ($parts as $part) {
110
-			$parents[] = $parent;
111
-			$parent = trim($parent . '/' . $part, '/');
112
-		}
113
-		return $parents;
114
-	}
115
-
116
-	/**
117
-	 * Mark the beginning of a propagation batch
118
-	 *
119
-	 * Note that not all cache setups support propagation in which case this will be a noop
120
-	 *
121
-	 * Batching for cache setups that do support it has to be explicit since the cache state is not fully consistent
122
-	 * before the batch is committed.
123
-	 */
124
-	public function beginBatch() {
125
-		$this->inBatch = true;
126
-	}
127
-
128
-	private function addToBatch($internalPath, $time, $sizeDifference) {
129
-		if (!isset($this->batch[$internalPath])) {
130
-			$this->batch[$internalPath] = [
131
-				'hash' => md5($internalPath),
132
-				'time' => $time,
133
-				'size' => $sizeDifference
134
-			];
135
-		} else {
136
-			$this->batch[$internalPath]['size'] += $sizeDifference;
137
-			if ($time > $this->batch[$internalPath]['time']) {
138
-				$this->batch[$internalPath]['time'] = $time;
139
-			}
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * Commit the active propagation batch
145
-	 * @suppress SqlInjectionChecker
146
-	 */
147
-	public function commitBatch() {
148
-		if (!$this->inBatch) {
149
-			throw new \BadMethodCallException('Not in batch');
150
-		}
151
-		$this->inBatch = false;
152
-
153
-		$this->connection->beginTransaction();
154
-
155
-		$query = $this->connection->getQueryBuilder();
156
-		$storageId = (int)$this->storage->getStorageCache()->getNumericId();
157
-
158
-		$query->update('filecache')
159
-			->set('mtime', $query->createFunction('GREATEST(' . $query->getColumnName('mtime') . ', ' . $query->createParameter('time') . ')'))
160
-			->set('etag', $query->expr()->literal(uniqid()))
161
-			->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
162
-			->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')));
163
-
164
-		$sizeQuery = $this->connection->getQueryBuilder();
165
-		$sizeQuery->update('filecache')
166
-			->set('size', $sizeQuery->func()->add('size', $sizeQuery->createParameter('size')))
167
-			->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
168
-			->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')))
169
-			->andWhere($sizeQuery->expr()->gt('size', $sizeQuery->expr()->literal(-1, IQueryBuilder::PARAM_INT)));
170
-
171
-		foreach ($this->batch as $item) {
172
-			$query->setParameter('time', $item['time'], IQueryBuilder::PARAM_INT);
173
-			$query->setParameter('hash', $item['hash']);
174
-
175
-			$query->execute();
176
-
177
-			if ($item['size']) {
178
-				$sizeQuery->setParameter('size', $item['size'], IQueryBuilder::PARAM_INT);
179
-				$sizeQuery->setParameter('hash', $item['hash']);
180
-
181
-				$sizeQuery->execute();
182
-			}
183
-		}
184
-
185
-		$this->batch = [];
186
-
187
-		$this->connection->commit();
188
-	}
34
+    private $inBatch = false;
35
+
36
+    private $batch = [];
37
+
38
+    /**
39
+     * @var \OC\Files\Storage\Storage
40
+     */
41
+    protected $storage;
42
+
43
+    /**
44
+     * @var IDBConnection
45
+     */
46
+    private $connection;
47
+
48
+    /**
49
+     * @param \OC\Files\Storage\Storage $storage
50
+     * @param IDBConnection $connection
51
+     */
52
+    public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $connection) {
53
+        $this->storage = $storage;
54
+        $this->connection = $connection;
55
+    }
56
+
57
+
58
+    /**
59
+     * @param string $internalPath
60
+     * @param int $time
61
+     * @param int $sizeDifference number of bytes the file has grown
62
+     * @suppress SqlInjectionChecker
63
+     */
64
+    public function propagateChange($internalPath, $time, $sizeDifference = 0) {
65
+        $storageId = (int)$this->storage->getStorageCache()->getNumericId();
66
+
67
+        $parents = $this->getParents($internalPath);
68
+
69
+        if ($this->inBatch) {
70
+            foreach ($parents as $parent) {
71
+                $this->addToBatch($parent, $time, $sizeDifference);
72
+            }
73
+            return;
74
+        }
75
+
76
+        $parentHashes = array_map('md5', $parents);
77
+        $etag = uniqid(); // since we give all folders the same etag we don't ask the storage for the etag
78
+
79
+        $builder = $this->connection->getQueryBuilder();
80
+        $hashParams = array_map(function ($hash) use ($builder) {
81
+            return $builder->expr()->literal($hash);
82
+        }, $parentHashes);
83
+
84
+        $builder->update('filecache')
85
+            ->set('mtime', $builder->createFunction('GREATEST(' . $builder->getColumnName('mtime') . ', ' . $builder->createNamedParameter((int)$time, IQueryBuilder::PARAM_INT) . ')'))
86
+            ->set('etag', $builder->createNamedParameter($etag, IQueryBuilder::PARAM_STR))
87
+            ->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
88
+            ->andWhere($builder->expr()->in('path_hash', $hashParams));
89
+
90
+        $builder->execute();
91
+
92
+        if ($sizeDifference !== 0) {
93
+            // we need to do size separably so we can ignore entries with uncalculated size
94
+            $builder = $this->connection->getQueryBuilder();
95
+            $builder->update('filecache')
96
+                ->set('size', $builder->func()->add('size', $builder->createNamedParameter($sizeDifference)))
97
+                ->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
98
+                ->andWhere($builder->expr()->in('path_hash', $hashParams))
99
+                ->andWhere($builder->expr()->gt('size', $builder->expr()->literal(-1, IQueryBuilder::PARAM_INT)));
100
+        }
101
+
102
+        $builder->execute();
103
+    }
104
+
105
+    protected function getParents($path) {
106
+        $parts = explode('/', $path);
107
+        $parent = '';
108
+        $parents = [];
109
+        foreach ($parts as $part) {
110
+            $parents[] = $parent;
111
+            $parent = trim($parent . '/' . $part, '/');
112
+        }
113
+        return $parents;
114
+    }
115
+
116
+    /**
117
+     * Mark the beginning of a propagation batch
118
+     *
119
+     * Note that not all cache setups support propagation in which case this will be a noop
120
+     *
121
+     * Batching for cache setups that do support it has to be explicit since the cache state is not fully consistent
122
+     * before the batch is committed.
123
+     */
124
+    public function beginBatch() {
125
+        $this->inBatch = true;
126
+    }
127
+
128
+    private function addToBatch($internalPath, $time, $sizeDifference) {
129
+        if (!isset($this->batch[$internalPath])) {
130
+            $this->batch[$internalPath] = [
131
+                'hash' => md5($internalPath),
132
+                'time' => $time,
133
+                'size' => $sizeDifference
134
+            ];
135
+        } else {
136
+            $this->batch[$internalPath]['size'] += $sizeDifference;
137
+            if ($time > $this->batch[$internalPath]['time']) {
138
+                $this->batch[$internalPath]['time'] = $time;
139
+            }
140
+        }
141
+    }
142
+
143
+    /**
144
+     * Commit the active propagation batch
145
+     * @suppress SqlInjectionChecker
146
+     */
147
+    public function commitBatch() {
148
+        if (!$this->inBatch) {
149
+            throw new \BadMethodCallException('Not in batch');
150
+        }
151
+        $this->inBatch = false;
152
+
153
+        $this->connection->beginTransaction();
154
+
155
+        $query = $this->connection->getQueryBuilder();
156
+        $storageId = (int)$this->storage->getStorageCache()->getNumericId();
157
+
158
+        $query->update('filecache')
159
+            ->set('mtime', $query->createFunction('GREATEST(' . $query->getColumnName('mtime') . ', ' . $query->createParameter('time') . ')'))
160
+            ->set('etag', $query->expr()->literal(uniqid()))
161
+            ->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
162
+            ->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')));
163
+
164
+        $sizeQuery = $this->connection->getQueryBuilder();
165
+        $sizeQuery->update('filecache')
166
+            ->set('size', $sizeQuery->func()->add('size', $sizeQuery->createParameter('size')))
167
+            ->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
168
+            ->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')))
169
+            ->andWhere($sizeQuery->expr()->gt('size', $sizeQuery->expr()->literal(-1, IQueryBuilder::PARAM_INT)));
170
+
171
+        foreach ($this->batch as $item) {
172
+            $query->setParameter('time', $item['time'], IQueryBuilder::PARAM_INT);
173
+            $query->setParameter('hash', $item['hash']);
174
+
175
+            $query->execute();
176
+
177
+            if ($item['size']) {
178
+                $sizeQuery->setParameter('size', $item['size'], IQueryBuilder::PARAM_INT);
179
+                $sizeQuery->setParameter('hash', $item['hash']);
180
+
181
+                $sizeQuery->execute();
182
+            }
183
+        }
184
+
185
+        $this->batch = [];
186
+
187
+        $this->connection->commit();
188
+    }
189 189
 
190 190
 
191 191
 }
Please login to merge, or discard this patch.
lib/private/Files/Type/Loader.php 1 patch
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -36,143 +36,143 @@
 block discarded – undo
36 36
  */
37 37
 class Loader implements IMimeTypeLoader {
38 38
 
39
-	/** @var IDBConnection */
40
-	private $dbConnection;
41
-
42
-	/** @var array [id => mimetype] */
43
-	protected $mimetypes;
44
-
45
-	/** @var array [mimetype => id] */
46
-	protected $mimetypeIds;
47
-
48
-	/**
49
-	 * @param IDBConnection $dbConnection
50
-	 */
51
-	public function __construct(IDBConnection $dbConnection) {
52
-		$this->dbConnection = $dbConnection;
53
-		$this->mimetypes = [];
54
-		$this->mimetypeIds = [];
55
-	}
56
-
57
-	/**
58
-	 * Get a mimetype from its ID
59
-	 *
60
-	 * @param int $id
61
-	 * @return string|null
62
-	 */
63
-	public function getMimetypeById($id) {
64
-		if (!$this->mimetypes) {
65
-			$this->loadMimetypes();
66
-		}
67
-		if (isset($this->mimetypes[$id])) {
68
-			return $this->mimetypes[$id];
69
-		}
70
-		return null;
71
-	}
72
-
73
-	/**
74
-	 * Get a mimetype ID, adding the mimetype to the DB if it does not exist
75
-	 *
76
-	 * @param string $mimetype
77
-	 * @return int
78
-	 */
79
-	public function getId($mimetype) {
80
-		if (!$this->mimetypeIds) {
81
-			$this->loadMimetypes();
82
-		}
83
-		if (isset($this->mimetypeIds[$mimetype])) {
84
-			return $this->mimetypeIds[$mimetype];
85
-		}
86
-		return $this->store($mimetype);
87
-	}
88
-
89
-	/**
90
-	 * Test if a mimetype exists in the database
91
-	 *
92
-	 * @param string $mimetype
93
-	 * @return bool
94
-	 */
95
-	public function exists($mimetype) {
96
-		if (!$this->mimetypeIds) {
97
-			$this->loadMimetypes();
98
-		}
99
-		return isset($this->mimetypeIds[$mimetype]);
100
-	}
101
-
102
-	/**
103
-	 * Clear all loaded mimetypes, allow for re-loading
104
-	 */
105
-	public function reset() {
106
-		$this->mimetypes = [];
107
-		$this->mimetypeIds = [];
108
-	}
109
-
110
-	/**
111
-	 * Store a mimetype in the DB
112
-	 *
113
-	 * @param string $mimetype
114
-	 * @param int inserted ID
115
-	 */
116
-	protected function store($mimetype) {
117
-		$this->dbConnection->insertIfNotExist('*PREFIX*mimetypes', [
118
-			'mimetype' => $mimetype
119
-		]);
120
-
121
-		$fetch = $this->dbConnection->getQueryBuilder();
122
-		$fetch->select('id')
123
-			->from('mimetypes')
124
-			->where(
125
-				$fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
126
-			));
127
-		$row = $fetch->execute()->fetch();
128
-
129
-		if (!$row) {
130
-			throw new \Exception("Failed to get mimetype id for $mimetype after trying to store it");
131
-		}
132
-
133
-		$this->mimetypes[$row['id']] = $mimetype;
134
-		$this->mimetypeIds[$mimetype] = $row['id'];
135
-		return $row['id'];
136
-	}
137
-
138
-	/**
139
-	 * Load all mimetypes from DB
140
-	 */
141
-	private function loadMimetypes() {
142
-		$qb = $this->dbConnection->getQueryBuilder();
143
-		$qb->select('id', 'mimetype')
144
-			->from('mimetypes');
145
-		$results = $qb->execute()->fetchAll();
146
-
147
-		foreach ($results as $row) {
148
-			$this->mimetypes[$row['id']] = $row['mimetype'];
149
-			$this->mimetypeIds[$row['mimetype']] = $row['id'];
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * Update filecache mimetype based on file extension
155
-	 *
156
-	 * @param string $ext file extension
157
-	 * @param int $mimeTypeId
158
-	 * @return int number of changed rows
159
-	 */
160
-	public function updateFilecache($ext, $mimeTypeId) {
161
-		$folderMimeTypeId = $this->getId('httpd/unix-directory');
162
-		$update = $this->dbConnection->getQueryBuilder();
163
-		$update->update('filecache')
164
-			->set('mimetype', $update->createNamedParameter($mimeTypeId))
165
-			->where($update->expr()->neq(
166
-				'mimetype', $update->createNamedParameter($mimeTypeId)
167
-			))
168
-			->andWhere($update->expr()->neq(
169
-				'mimetype', $update->createNamedParameter($folderMimeTypeId)
170
-			))
171
-			->andWhere($update->expr()->like(
172
-				$update->func()->lower('name'),
173
-				$update->createNamedParameter('%' . $this->dbConnection->escapeLikeParameter('.' . $ext))
174
-			));
175
-		return $update->execute();
176
-	}
39
+    /** @var IDBConnection */
40
+    private $dbConnection;
41
+
42
+    /** @var array [id => mimetype] */
43
+    protected $mimetypes;
44
+
45
+    /** @var array [mimetype => id] */
46
+    protected $mimetypeIds;
47
+
48
+    /**
49
+     * @param IDBConnection $dbConnection
50
+     */
51
+    public function __construct(IDBConnection $dbConnection) {
52
+        $this->dbConnection = $dbConnection;
53
+        $this->mimetypes = [];
54
+        $this->mimetypeIds = [];
55
+    }
56
+
57
+    /**
58
+     * Get a mimetype from its ID
59
+     *
60
+     * @param int $id
61
+     * @return string|null
62
+     */
63
+    public function getMimetypeById($id) {
64
+        if (!$this->mimetypes) {
65
+            $this->loadMimetypes();
66
+        }
67
+        if (isset($this->mimetypes[$id])) {
68
+            return $this->mimetypes[$id];
69
+        }
70
+        return null;
71
+    }
72
+
73
+    /**
74
+     * Get a mimetype ID, adding the mimetype to the DB if it does not exist
75
+     *
76
+     * @param string $mimetype
77
+     * @return int
78
+     */
79
+    public function getId($mimetype) {
80
+        if (!$this->mimetypeIds) {
81
+            $this->loadMimetypes();
82
+        }
83
+        if (isset($this->mimetypeIds[$mimetype])) {
84
+            return $this->mimetypeIds[$mimetype];
85
+        }
86
+        return $this->store($mimetype);
87
+    }
88
+
89
+    /**
90
+     * Test if a mimetype exists in the database
91
+     *
92
+     * @param string $mimetype
93
+     * @return bool
94
+     */
95
+    public function exists($mimetype) {
96
+        if (!$this->mimetypeIds) {
97
+            $this->loadMimetypes();
98
+        }
99
+        return isset($this->mimetypeIds[$mimetype]);
100
+    }
101
+
102
+    /**
103
+     * Clear all loaded mimetypes, allow for re-loading
104
+     */
105
+    public function reset() {
106
+        $this->mimetypes = [];
107
+        $this->mimetypeIds = [];
108
+    }
109
+
110
+    /**
111
+     * Store a mimetype in the DB
112
+     *
113
+     * @param string $mimetype
114
+     * @param int inserted ID
115
+     */
116
+    protected function store($mimetype) {
117
+        $this->dbConnection->insertIfNotExist('*PREFIX*mimetypes', [
118
+            'mimetype' => $mimetype
119
+        ]);
120
+
121
+        $fetch = $this->dbConnection->getQueryBuilder();
122
+        $fetch->select('id')
123
+            ->from('mimetypes')
124
+            ->where(
125
+                $fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
126
+            ));
127
+        $row = $fetch->execute()->fetch();
128
+
129
+        if (!$row) {
130
+            throw new \Exception("Failed to get mimetype id for $mimetype after trying to store it");
131
+        }
132
+
133
+        $this->mimetypes[$row['id']] = $mimetype;
134
+        $this->mimetypeIds[$mimetype] = $row['id'];
135
+        return $row['id'];
136
+    }
137
+
138
+    /**
139
+     * Load all mimetypes from DB
140
+     */
141
+    private function loadMimetypes() {
142
+        $qb = $this->dbConnection->getQueryBuilder();
143
+        $qb->select('id', 'mimetype')
144
+            ->from('mimetypes');
145
+        $results = $qb->execute()->fetchAll();
146
+
147
+        foreach ($results as $row) {
148
+            $this->mimetypes[$row['id']] = $row['mimetype'];
149
+            $this->mimetypeIds[$row['mimetype']] = $row['id'];
150
+        }
151
+    }
152
+
153
+    /**
154
+     * Update filecache mimetype based on file extension
155
+     *
156
+     * @param string $ext file extension
157
+     * @param int $mimeTypeId
158
+     * @return int number of changed rows
159
+     */
160
+    public function updateFilecache($ext, $mimeTypeId) {
161
+        $folderMimeTypeId = $this->getId('httpd/unix-directory');
162
+        $update = $this->dbConnection->getQueryBuilder();
163
+        $update->update('filecache')
164
+            ->set('mimetype', $update->createNamedParameter($mimeTypeId))
165
+            ->where($update->expr()->neq(
166
+                'mimetype', $update->createNamedParameter($mimeTypeId)
167
+            ))
168
+            ->andWhere($update->expr()->neq(
169
+                'mimetype', $update->createNamedParameter($folderMimeTypeId)
170
+            ))
171
+            ->andWhere($update->expr()->like(
172
+                $update->func()->lower('name'),
173
+                $update->createNamedParameter('%' . $this->dbConnection->escapeLikeParameter('.' . $ext))
174
+            ));
175
+        return $update->execute();
176
+    }
177 177
 
178 178
 }
Please login to merge, or discard this patch.
lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -28,52 +28,52 @@
 block discarded – undo
28 28
 use OCP\DB\QueryBuilder\IFunctionBuilder;
29 29
 
30 30
 class FunctionBuilder implements IFunctionBuilder {
31
-	/** @var QuoteHelper */
32
-	protected $helper;
31
+    /** @var QuoteHelper */
32
+    protected $helper;
33 33
 
34
-	/**
35
-	 * ExpressionBuilder constructor.
36
-	 *
37
-	 * @param QuoteHelper $helper
38
-	 */
39
-	public function __construct(QuoteHelper $helper) {
40
-		$this->helper = $helper;
41
-	}
34
+    /**
35
+     * ExpressionBuilder constructor.
36
+     *
37
+     * @param QuoteHelper $helper
38
+     */
39
+    public function __construct(QuoteHelper $helper) {
40
+        $this->helper = $helper;
41
+    }
42 42
 
43
-	public function md5($input) {
44
-		return new QueryFunction('MD5(' . $this->helper->quoteColumnName($input) . ')');
45
-	}
43
+    public function md5($input) {
44
+        return new QueryFunction('MD5(' . $this->helper->quoteColumnName($input) . ')');
45
+    }
46 46
 
47
-	public function concat($x, $y) {
48
-		return new QueryFunction('CONCAT(' . $this->helper->quoteColumnName($x) . ', ' . $this->helper->quoteColumnName($y) . ')');
49
-	}
47
+    public function concat($x, $y) {
48
+        return new QueryFunction('CONCAT(' . $this->helper->quoteColumnName($x) . ', ' . $this->helper->quoteColumnName($y) . ')');
49
+    }
50 50
 
51
-	public function substring($input, $start, $length = null) {
52
-		if ($length) {
53
-			return new QueryFunction('SUBSTR(' . $this->helper->quoteColumnName($input) . ', ' . $this->helper->quoteColumnName($start) . ', ' . $this->helper->quoteColumnName($length) . ')');
54
-		} else {
55
-			return new QueryFunction('SUBSTR(' . $this->helper->quoteColumnName($input) . ', ' . $this->helper->quoteColumnName($start) . ')');
56
-		}
57
-	}
51
+    public function substring($input, $start, $length = null) {
52
+        if ($length) {
53
+            return new QueryFunction('SUBSTR(' . $this->helper->quoteColumnName($input) . ', ' . $this->helper->quoteColumnName($start) . ', ' . $this->helper->quoteColumnName($length) . ')');
54
+        } else {
55
+            return new QueryFunction('SUBSTR(' . $this->helper->quoteColumnName($input) . ', ' . $this->helper->quoteColumnName($start) . ')');
56
+        }
57
+    }
58 58
 
59
-	public function sum($field) {
60
-		return new QueryFunction('SUM(' . $this->helper->quoteColumnName($field) . ')');
61
-	}
59
+    public function sum($field) {
60
+        return new QueryFunction('SUM(' . $this->helper->quoteColumnName($field) . ')');
61
+    }
62 62
 
63
-	public function lower($field) {
64
-		return new QueryFunction('LOWER(' . $this->helper->quoteColumnName($field) . ')');
65
-	}
63
+    public function lower($field) {
64
+        return new QueryFunction('LOWER(' . $this->helper->quoteColumnName($field) . ')');
65
+    }
66 66
 
67
-	public function add($x, $y) {
68
-		return new QueryFunction($this->helper->quoteColumnName($x) . ' + ' . $this->helper->quoteColumnName($y));
69
-	}
67
+    public function add($x, $y) {
68
+        return new QueryFunction($this->helper->quoteColumnName($x) . ' + ' . $this->helper->quoteColumnName($y));
69
+    }
70 70
 
71
-	public function subtract($x, $y) {
72
-		return new QueryFunction($this->helper->quoteColumnName($x) . ' - ' . $this->helper->quoteColumnName($y));
73
-	}
71
+    public function subtract($x, $y) {
72
+        return new QueryFunction($this->helper->quoteColumnName($x) . ' - ' . $this->helper->quoteColumnName($y));
73
+    }
74 74
 
75
-	public function count($count, $alias = '') {
76
-		$alias = $alias ? (' AS ' . $this->helper->quoteColumnName($alias)) : '';
77
-		return new QueryFunction('COUNT(' . $this->helper->quoteColumnName($count) . ')' . $alias);
78
-	}
75
+    public function count($count, $alias = '') {
76
+        $alias = $alias ? (' AS ' . $this->helper->quoteColumnName($alias)) : '';
77
+        return new QueryFunction('COUNT(' . $this->helper->quoteColumnName($count) . ')' . $alias);
78
+    }
79 79
 }
Please login to merge, or discard this patch.
lib/private/Lock/DBLockingProvider.php 1 patch
Indentation   +258 added lines, -258 removed lines patch added patch discarded remove patch
@@ -39,286 +39,286 @@
 block discarded – undo
39 39
  * Locking provider that stores the locks in the database
40 40
  */
41 41
 class DBLockingProvider extends AbstractLockingProvider {
42
-	/**
43
-	 * @var \OCP\IDBConnection
44
-	 */
45
-	private $connection;
42
+    /**
43
+     * @var \OCP\IDBConnection
44
+     */
45
+    private $connection;
46 46
 
47
-	/**
48
-	 * @var \OCP\ILogger
49
-	 */
50
-	private $logger;
47
+    /**
48
+     * @var \OCP\ILogger
49
+     */
50
+    private $logger;
51 51
 
52
-	/**
53
-	 * @var \OCP\AppFramework\Utility\ITimeFactory
54
-	 */
55
-	private $timeFactory;
52
+    /**
53
+     * @var \OCP\AppFramework\Utility\ITimeFactory
54
+     */
55
+    private $timeFactory;
56 56
 
57
-	private $sharedLocks = [];
57
+    private $sharedLocks = [];
58 58
 
59
-	/**
60
-	 * @var bool
61
-	 */
62
-	private $cacheSharedLocks;
59
+    /**
60
+     * @var bool
61
+     */
62
+    private $cacheSharedLocks;
63 63
 
64
-	/**
65
-	 * Check if we have an open shared lock for a path
66
-	 *
67
-	 * @param string $path
68
-	 * @return bool
69
-	 */
70
-	protected function isLocallyLocked(string $path): bool {
71
-		return isset($this->sharedLocks[$path]) && $this->sharedLocks[$path];
72
-	}
64
+    /**
65
+     * Check if we have an open shared lock for a path
66
+     *
67
+     * @param string $path
68
+     * @return bool
69
+     */
70
+    protected function isLocallyLocked(string $path): bool {
71
+        return isset($this->sharedLocks[$path]) && $this->sharedLocks[$path];
72
+    }
73 73
 
74
-	/**
75
-	 * Mark a locally acquired lock
76
-	 *
77
-	 * @param string $path
78
-	 * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
79
-	 */
80
-	protected function markAcquire(string $path, int $type) {
81
-		parent::markAcquire($path, $type);
82
-		if ($this->cacheSharedLocks) {
83
-			if ($type === self::LOCK_SHARED) {
84
-				$this->sharedLocks[$path] = true;
85
-			}
86
-		}
87
-	}
74
+    /**
75
+     * Mark a locally acquired lock
76
+     *
77
+     * @param string $path
78
+     * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
79
+     */
80
+    protected function markAcquire(string $path, int $type) {
81
+        parent::markAcquire($path, $type);
82
+        if ($this->cacheSharedLocks) {
83
+            if ($type === self::LOCK_SHARED) {
84
+                $this->sharedLocks[$path] = true;
85
+            }
86
+        }
87
+    }
88 88
 
89
-	/**
90
-	 * Change the type of an existing tracked lock
91
-	 *
92
-	 * @param string $path
93
-	 * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
94
-	 */
95
-	protected function markChange(string $path, int $targetType) {
96
-		parent::markChange($path, $targetType);
97
-		if ($this->cacheSharedLocks) {
98
-			if ($targetType === self::LOCK_SHARED) {
99
-				$this->sharedLocks[$path] = true;
100
-			} else if ($targetType === self::LOCK_EXCLUSIVE) {
101
-				$this->sharedLocks[$path] = false;
102
-			}
103
-		}
104
-	}
89
+    /**
90
+     * Change the type of an existing tracked lock
91
+     *
92
+     * @param string $path
93
+     * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
94
+     */
95
+    protected function markChange(string $path, int $targetType) {
96
+        parent::markChange($path, $targetType);
97
+        if ($this->cacheSharedLocks) {
98
+            if ($targetType === self::LOCK_SHARED) {
99
+                $this->sharedLocks[$path] = true;
100
+            } else if ($targetType === self::LOCK_EXCLUSIVE) {
101
+                $this->sharedLocks[$path] = false;
102
+            }
103
+        }
104
+    }
105 105
 
106
-	/**
107
-	 * @param \OCP\IDBConnection $connection
108
-	 * @param \OCP\ILogger $logger
109
-	 * @param \OCP\AppFramework\Utility\ITimeFactory $timeFactory
110
-	 * @param int $ttl
111
-	 * @param bool $cacheSharedLocks
112
-	 */
113
-	public function __construct(
114
-		IDBConnection $connection,
115
-		ILogger $logger,
116
-		ITimeFactory $timeFactory,
117
-		int $ttl = 3600,
118
-		$cacheSharedLocks = true
119
-	) {
120
-		$this->connection = $connection;
121
-		$this->logger = $logger;
122
-		$this->timeFactory = $timeFactory;
123
-		$this->ttl = $ttl;
124
-		$this->cacheSharedLocks = $cacheSharedLocks;
125
-	}
106
+    /**
107
+     * @param \OCP\IDBConnection $connection
108
+     * @param \OCP\ILogger $logger
109
+     * @param \OCP\AppFramework\Utility\ITimeFactory $timeFactory
110
+     * @param int $ttl
111
+     * @param bool $cacheSharedLocks
112
+     */
113
+    public function __construct(
114
+        IDBConnection $connection,
115
+        ILogger $logger,
116
+        ITimeFactory $timeFactory,
117
+        int $ttl = 3600,
118
+        $cacheSharedLocks = true
119
+    ) {
120
+        $this->connection = $connection;
121
+        $this->logger = $logger;
122
+        $this->timeFactory = $timeFactory;
123
+        $this->ttl = $ttl;
124
+        $this->cacheSharedLocks = $cacheSharedLocks;
125
+    }
126 126
 
127
-	/**
128
-	 * Insert a file locking row if it does not exists.
129
-	 *
130
-	 * @param string $path
131
-	 * @param int $lock
132
-	 * @return int number of inserted rows
133
-	 */
127
+    /**
128
+     * Insert a file locking row if it does not exists.
129
+     *
130
+     * @param string $path
131
+     * @param int $lock
132
+     * @return int number of inserted rows
133
+     */
134 134
 
135
-	protected function initLockField(string $path, int $lock = 0): int {
136
-		$expire = $this->getExpireTime();
135
+    protected function initLockField(string $path, int $lock = 0): int {
136
+        $expire = $this->getExpireTime();
137 137
 
138
-		try {
139
-			$builder = $this->connection->getQueryBuilder();
140
-			return $builder->insert('file_locks')
141
-				->setValue('key', $builder->createNamedParameter($path))
142
-				->setValue('lock', $builder->createNamedParameter($lock))
143
-				->setValue('ttl', $builder->createNamedParameter($expire))
144
-				->execute();
145
-		} catch(UniqueConstraintViolationException $e) {
146
-			return 0;
147
-		}
148
-	}
138
+        try {
139
+            $builder = $this->connection->getQueryBuilder();
140
+            return $builder->insert('file_locks')
141
+                ->setValue('key', $builder->createNamedParameter($path))
142
+                ->setValue('lock', $builder->createNamedParameter($lock))
143
+                ->setValue('ttl', $builder->createNamedParameter($expire))
144
+                ->execute();
145
+        } catch(UniqueConstraintViolationException $e) {
146
+            return 0;
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return int
152
-	 */
153
-	protected function getExpireTime(): int {
154
-		return $this->timeFactory->getTime() + $this->ttl;
155
-	}
150
+    /**
151
+     * @return int
152
+     */
153
+    protected function getExpireTime(): int {
154
+        return $this->timeFactory->getTime() + $this->ttl;
155
+    }
156 156
 
157
-	/**
158
-	 * @param string $path
159
-	 * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
160
-	 * @return bool
161
-	 */
162
-	public function isLocked(string $path, int $type): bool {
163
-		if ($this->hasAcquiredLock($path, $type)) {
164
-			return true;
165
-		}
166
-		$query = $this->connection->prepare('SELECT `lock` from `*PREFIX*file_locks` WHERE `key` = ?');
167
-		$query->execute([$path]);
168
-		$lockValue = (int)$query->fetchColumn();
169
-		if ($type === self::LOCK_SHARED) {
170
-			if ($this->isLocallyLocked($path)) {
171
-				// if we have a shared lock we kept open locally but it's released we always have at least 1 shared lock in the db
172
-				return $lockValue > 1;
173
-			} else {
174
-				return $lockValue > 0;
175
-			}
176
-		} else if ($type === self::LOCK_EXCLUSIVE) {
177
-			return $lockValue === -1;
178
-		} else {
179
-			return false;
180
-		}
181
-	}
157
+    /**
158
+     * @param string $path
159
+     * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
160
+     * @return bool
161
+     */
162
+    public function isLocked(string $path, int $type): bool {
163
+        if ($this->hasAcquiredLock($path, $type)) {
164
+            return true;
165
+        }
166
+        $query = $this->connection->prepare('SELECT `lock` from `*PREFIX*file_locks` WHERE `key` = ?');
167
+        $query->execute([$path]);
168
+        $lockValue = (int)$query->fetchColumn();
169
+        if ($type === self::LOCK_SHARED) {
170
+            if ($this->isLocallyLocked($path)) {
171
+                // if we have a shared lock we kept open locally but it's released we always have at least 1 shared lock in the db
172
+                return $lockValue > 1;
173
+            } else {
174
+                return $lockValue > 0;
175
+            }
176
+        } else if ($type === self::LOCK_EXCLUSIVE) {
177
+            return $lockValue === -1;
178
+        } else {
179
+            return false;
180
+        }
181
+    }
182 182
 
183
-	/**
184
-	 * @param string $path
185
-	 * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
186
-	 * @throws \OCP\Lock\LockedException
187
-	 */
188
-	public function acquireLock(string $path, int $type) {
189
-		$expire = $this->getExpireTime();
190
-		if ($type === self::LOCK_SHARED) {
191
-			if (!$this->isLocallyLocked($path)) {
192
-				$result = $this->initLockField($path, 1);
193
-				if ($result <= 0) {
194
-					$result = $this->connection->executeUpdate(
195
-						'UPDATE `*PREFIX*file_locks` SET `lock` = `lock` + 1, `ttl` = ? WHERE `key` = ? AND `lock` >= 0',
196
-						[$expire, $path]
197
-					);
198
-				}
199
-			} else {
200
-				$result = 1;
201
-			}
202
-		} else {
203
-			$existing = 0;
204
-			if ($this->hasAcquiredLock($path, ILockingProvider::LOCK_SHARED) === false && $this->isLocallyLocked($path)) {
205
-				$existing = 1;
206
-			}
207
-			$result = $this->initLockField($path, -1);
208
-			if ($result <= 0) {
209
-				$result = $this->connection->executeUpdate(
210
-					'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = ?',
211
-					[$expire, $path, $existing]
212
-				);
213
-			}
214
-		}
215
-		if ($result !== 1) {
216
-			throw new LockedException($path);
217
-		}
218
-		$this->markAcquire($path, $type);
219
-	}
183
+    /**
184
+     * @param string $path
185
+     * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
186
+     * @throws \OCP\Lock\LockedException
187
+     */
188
+    public function acquireLock(string $path, int $type) {
189
+        $expire = $this->getExpireTime();
190
+        if ($type === self::LOCK_SHARED) {
191
+            if (!$this->isLocallyLocked($path)) {
192
+                $result = $this->initLockField($path, 1);
193
+                if ($result <= 0) {
194
+                    $result = $this->connection->executeUpdate(
195
+                        'UPDATE `*PREFIX*file_locks` SET `lock` = `lock` + 1, `ttl` = ? WHERE `key` = ? AND `lock` >= 0',
196
+                        [$expire, $path]
197
+                    );
198
+                }
199
+            } else {
200
+                $result = 1;
201
+            }
202
+        } else {
203
+            $existing = 0;
204
+            if ($this->hasAcquiredLock($path, ILockingProvider::LOCK_SHARED) === false && $this->isLocallyLocked($path)) {
205
+                $existing = 1;
206
+            }
207
+            $result = $this->initLockField($path, -1);
208
+            if ($result <= 0) {
209
+                $result = $this->connection->executeUpdate(
210
+                    'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = ?',
211
+                    [$expire, $path, $existing]
212
+                );
213
+            }
214
+        }
215
+        if ($result !== 1) {
216
+            throw new LockedException($path);
217
+        }
218
+        $this->markAcquire($path, $type);
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
224
-	 *
225
-	 * @suppress SqlInjectionChecker
226
-	 */
227
-	public function releaseLock(string $path, int $type) {
228
-		$this->markRelease($path, $type);
221
+    /**
222
+     * @param string $path
223
+     * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
224
+     *
225
+     * @suppress SqlInjectionChecker
226
+     */
227
+    public function releaseLock(string $path, int $type) {
228
+        $this->markRelease($path, $type);
229 229
 
230
-		// we keep shared locks till the end of the request so we can re-use them
231
-		if ($type === self::LOCK_EXCLUSIVE) {
232
-			$this->connection->executeUpdate(
233
-				'UPDATE `*PREFIX*file_locks` SET `lock` = 0 WHERE `key` = ? AND `lock` = -1',
234
-				[$path]
235
-			);
236
-		} else if (!$this->cacheSharedLocks) {
237
-			$query = $this->connection->getQueryBuilder();
238
-			$query->update('file_locks')
239
-				->set('lock', $query->func()->subtract('lock', $query->createNamedParameter(1)))
240
-				->where($query->expr()->eq('key', $query->createNamedParameter($path)))
241
-				->andWhere($query->expr()->gt('lock', $query->createNamedParameter(0)));
242
-			$query->execute();
243
-		}
244
-	}
230
+        // we keep shared locks till the end of the request so we can re-use them
231
+        if ($type === self::LOCK_EXCLUSIVE) {
232
+            $this->connection->executeUpdate(
233
+                'UPDATE `*PREFIX*file_locks` SET `lock` = 0 WHERE `key` = ? AND `lock` = -1',
234
+                [$path]
235
+            );
236
+        } else if (!$this->cacheSharedLocks) {
237
+            $query = $this->connection->getQueryBuilder();
238
+            $query->update('file_locks')
239
+                ->set('lock', $query->func()->subtract('lock', $query->createNamedParameter(1)))
240
+                ->where($query->expr()->eq('key', $query->createNamedParameter($path)))
241
+                ->andWhere($query->expr()->gt('lock', $query->createNamedParameter(0)));
242
+            $query->execute();
243
+        }
244
+    }
245 245
 
246
-	/**
247
-	 * Change the type of an existing lock
248
-	 *
249
-	 * @param string $path
250
-	 * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
251
-	 * @throws \OCP\Lock\LockedException
252
-	 */
253
-	public function changeLock(string $path, int $targetType) {
254
-		$expire = $this->getExpireTime();
255
-		if ($targetType === self::LOCK_SHARED) {
256
-			$result = $this->connection->executeUpdate(
257
-				'UPDATE `*PREFIX*file_locks` SET `lock` = 1, `ttl` = ? WHERE `key` = ? AND `lock` = -1',
258
-				[$expire, $path]
259
-			);
260
-		} else {
261
-			// since we only keep one shared lock in the db we need to check if we have more then one shared lock locally manually
262
-			if (isset($this->acquiredLocks['shared'][$path]) && $this->acquiredLocks['shared'][$path] > 1) {
263
-				throw new LockedException($path);
264
-			}
265
-			$result = $this->connection->executeUpdate(
266
-				'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = 1',
267
-				[$expire, $path]
268
-			);
269
-		}
270
-		if ($result !== 1) {
271
-			throw new LockedException($path);
272
-		}
273
-		$this->markChange($path, $targetType);
274
-	}
246
+    /**
247
+     * Change the type of an existing lock
248
+     *
249
+     * @param string $path
250
+     * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
251
+     * @throws \OCP\Lock\LockedException
252
+     */
253
+    public function changeLock(string $path, int $targetType) {
254
+        $expire = $this->getExpireTime();
255
+        if ($targetType === self::LOCK_SHARED) {
256
+            $result = $this->connection->executeUpdate(
257
+                'UPDATE `*PREFIX*file_locks` SET `lock` = 1, `ttl` = ? WHERE `key` = ? AND `lock` = -1',
258
+                [$expire, $path]
259
+            );
260
+        } else {
261
+            // since we only keep one shared lock in the db we need to check if we have more then one shared lock locally manually
262
+            if (isset($this->acquiredLocks['shared'][$path]) && $this->acquiredLocks['shared'][$path] > 1) {
263
+                throw new LockedException($path);
264
+            }
265
+            $result = $this->connection->executeUpdate(
266
+                'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = 1',
267
+                [$expire, $path]
268
+            );
269
+        }
270
+        if ($result !== 1) {
271
+            throw new LockedException($path);
272
+        }
273
+        $this->markChange($path, $targetType);
274
+    }
275 275
 
276
-	/**
277
-	 * cleanup empty locks
278
-	 */
279
-	public function cleanExpiredLocks() {
280
-		$expire = $this->timeFactory->getTime();
281
-		try {
282
-			$this->connection->executeUpdate(
283
-				'DELETE FROM `*PREFIX*file_locks` WHERE `ttl` < ?',
284
-				[$expire]
285
-			);
286
-		} catch (\Exception $e) {
287
-			// If the table is missing, the clean up was successful
288
-			if ($this->connection->tableExists('file_locks')) {
289
-				throw $e;
290
-			}
291
-		}
292
-	}
276
+    /**
277
+     * cleanup empty locks
278
+     */
279
+    public function cleanExpiredLocks() {
280
+        $expire = $this->timeFactory->getTime();
281
+        try {
282
+            $this->connection->executeUpdate(
283
+                'DELETE FROM `*PREFIX*file_locks` WHERE `ttl` < ?',
284
+                [$expire]
285
+            );
286
+        } catch (\Exception $e) {
287
+            // If the table is missing, the clean up was successful
288
+            if ($this->connection->tableExists('file_locks')) {
289
+                throw $e;
290
+            }
291
+        }
292
+    }
293 293
 
294
-	/**
295
-	 * release all lock acquired by this instance which were marked using the mark* methods
296
-	 *
297
-	 * @suppress SqlInjectionChecker
298
-	 */
299
-	public function releaseAll() {
300
-		parent::releaseAll();
294
+    /**
295
+     * release all lock acquired by this instance which were marked using the mark* methods
296
+     *
297
+     * @suppress SqlInjectionChecker
298
+     */
299
+    public function releaseAll() {
300
+        parent::releaseAll();
301 301
 
302
-		if (!$this->cacheSharedLocks) {
303
-			return;
304
-		}
305
-		// since we keep shared locks we need to manually clean those
306
-		$lockedPaths = array_keys($this->sharedLocks);
307
-		$lockedPaths = array_filter($lockedPaths, function ($path) {
308
-			return $this->sharedLocks[$path];
309
-		});
302
+        if (!$this->cacheSharedLocks) {
303
+            return;
304
+        }
305
+        // since we keep shared locks we need to manually clean those
306
+        $lockedPaths = array_keys($this->sharedLocks);
307
+        $lockedPaths = array_filter($lockedPaths, function ($path) {
308
+            return $this->sharedLocks[$path];
309
+        });
310 310
 
311
-		$chunkedPaths = array_chunk($lockedPaths, 100);
311
+        $chunkedPaths = array_chunk($lockedPaths, 100);
312 312
 
313
-		foreach ($chunkedPaths as $chunk) {
314
-			$builder = $this->connection->getQueryBuilder();
313
+        foreach ($chunkedPaths as $chunk) {
314
+            $builder = $this->connection->getQueryBuilder();
315 315
 
316
-			$query = $builder->update('file_locks')
317
-				->set('lock', $builder->func()->subtract('lock', $builder->expr()->literal(1)))
318
-				->where($builder->expr()->in('key', $builder->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)))
319
-				->andWhere($builder->expr()->gt('lock', new Literal(0)));
316
+            $query = $builder->update('file_locks')
317
+                ->set('lock', $builder->func()->subtract('lock', $builder->expr()->literal(1)))
318
+                ->where($builder->expr()->in('key', $builder->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)))
319
+                ->andWhere($builder->expr()->gt('lock', new Literal(0)));
320 320
 
321
-			$query->execute();
322
-		}
323
-	}
321
+            $query->execute();
322
+        }
323
+    }
324 324
 }
Please login to merge, or discard this patch.
lib/private/User/Manager.php 1 patch
Indentation   +537 added lines, -537 removed lines patch added patch discarded remove patch
@@ -58,545 +58,545 @@
 block discarded – undo
58 58
  * @package OC\User
59 59
  */
60 60
 class Manager extends PublicEmitter implements IUserManager {
61
-	/**
62
-	 * @var \OCP\UserInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\User[] $cachedUsers
68
-	 */
69
-	private $cachedUsers = array();
70
-
71
-	/**
72
-	 * @var \OCP\IConfig $config
73
-	 */
74
-	private $config;
75
-
76
-	/**
77
-	 * @param \OCP\IConfig $config
78
-	 */
79
-	public function __construct(IConfig $config) {
80
-		$this->config = $config;
81
-		$cachedUsers = &$this->cachedUsers;
82
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
-			/** @var \OC\User\User $user */
84
-			unset($cachedUsers[$user->getUID()]);
85
-		});
86
-	}
87
-
88
-	/**
89
-	 * Get the active backends
90
-	 * @return \OCP\UserInterface[]
91
-	 */
92
-	public function getBackends() {
93
-		return $this->backends;
94
-	}
95
-
96
-	/**
97
-	 * register a user backend
98
-	 *
99
-	 * @param \OCP\UserInterface $backend
100
-	 */
101
-	public function registerBackend($backend) {
102
-		$this->backends[] = $backend;
103
-	}
104
-
105
-	/**
106
-	 * remove a user backend
107
-	 *
108
-	 * @param \OCP\UserInterface $backend
109
-	 */
110
-	public function removeBackend($backend) {
111
-		$this->cachedUsers = array();
112
-		if (($i = array_search($backend, $this->backends)) !== false) {
113
-			unset($this->backends[$i]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * remove all user backends
119
-	 */
120
-	public function clearBackends() {
121
-		$this->cachedUsers = array();
122
-		$this->backends = array();
123
-	}
124
-
125
-	/**
126
-	 * get a user by user id
127
-	 *
128
-	 * @param string $uid
129
-	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
-	 */
131
-	public function get($uid) {
132
-		if (is_null($uid) || $uid === '' || $uid === false) {
133
-			return null;
134
-		}
135
-		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
-			return $this->cachedUsers[$uid];
137
-		}
138
-		foreach ($this->backends as $backend) {
139
-			if ($backend->userExists($uid)) {
140
-				return $this->getUserObject($uid, $backend);
141
-			}
142
-		}
143
-		return null;
144
-	}
145
-
146
-	/**
147
-	 * get or construct the user object
148
-	 *
149
-	 * @param string $uid
150
-	 * @param \OCP\UserInterface $backend
151
-	 * @param bool $cacheUser If false the newly created user object will not be cached
152
-	 * @return \OC\User\User
153
-	 */
154
-	protected function getUserObject($uid, $backend, $cacheUser = true) {
155
-		if (isset($this->cachedUsers[$uid])) {
156
-			return $this->cachedUsers[$uid];
157
-		}
158
-
159
-		$user = new User($uid, $backend, $this, $this->config);
160
-		if ($cacheUser) {
161
-			$this->cachedUsers[$uid] = $user;
162
-		}
163
-		return $user;
164
-	}
165
-
166
-	/**
167
-	 * check if a user exists
168
-	 *
169
-	 * @param string $uid
170
-	 * @return bool
171
-	 */
172
-	public function userExists($uid) {
173
-		$user = $this->get($uid);
174
-		return ($user !== null);
175
-	}
176
-
177
-	/**
178
-	 * Check if the password is valid for the user
179
-	 *
180
-	 * @param string $loginName
181
-	 * @param string $password
182
-	 * @return mixed the User object on success, false otherwise
183
-	 */
184
-	public function checkPassword($loginName, $password) {
185
-		$result = $this->checkPasswordNoLogging($loginName, $password);
186
-
187
-		if ($result === false) {
188
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
-		}
190
-
191
-		return $result;
192
-	}
193
-
194
-	/**
195
-	 * Check if the password is valid for the user
196
-	 *
197
-	 * @internal
198
-	 * @param string $loginName
199
-	 * @param string $password
200
-	 * @return mixed the User object on success, false otherwise
201
-	 */
202
-	public function checkPasswordNoLogging($loginName, $password) {
203
-		$loginName = str_replace("\0", '', $loginName);
204
-		$password = str_replace("\0", '', $password);
205
-
206
-		foreach ($this->backends as $backend) {
207
-			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
-				$uid = $backend->checkPassword($loginName, $password);
209
-				if ($uid !== false) {
210
-					return $this->getUserObject($uid, $backend);
211
-				}
212
-			}
213
-		}
214
-
215
-		return false;
216
-	}
217
-
218
-	/**
219
-	 * search by user id
220
-	 *
221
-	 * @param string $pattern
222
-	 * @param int $limit
223
-	 * @param int $offset
224
-	 * @return \OC\User\User[]
225
-	 */
226
-	public function search($pattern, $limit = null, $offset = null) {
227
-		$users = array();
228
-		foreach ($this->backends as $backend) {
229
-			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
-			if (is_array($backendUsers)) {
231
-				foreach ($backendUsers as $uid) {
232
-					$users[$uid] = $this->getUserObject($uid, $backend);
233
-				}
234
-			}
235
-		}
236
-
237
-		uasort($users, function ($a, $b) {
238
-			/**
239
-			 * @var \OC\User\User $a
240
-			 * @var \OC\User\User $b
241
-			 */
242
-			return strcasecmp($a->getUID(), $b->getUID());
243
-		});
244
-		return $users;
245
-	}
246
-
247
-	/**
248
-	 * search by displayName
249
-	 *
250
-	 * @param string $pattern
251
-	 * @param int $limit
252
-	 * @param int $offset
253
-	 * @return \OC\User\User[]
254
-	 */
255
-	public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
-		$users = array();
257
-		foreach ($this->backends as $backend) {
258
-			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
-			if (is_array($backendUsers)) {
260
-				foreach ($backendUsers as $uid => $displayName) {
261
-					$users[] = $this->getUserObject($uid, $backend);
262
-				}
263
-			}
264
-		}
265
-
266
-		usort($users, function ($a, $b) {
267
-			/**
268
-			 * @var \OC\User\User $a
269
-			 * @var \OC\User\User $b
270
-			 */
271
-			return strcasecmp($a->getDisplayName(), $b->getDisplayName());
272
-		});
273
-		return $users;
274
-	}
275
-
276
-	/**
277
-	 * @param string $uid
278
-	 * @param string $password
279
-	 * @throws \InvalidArgumentException
280
-	 * @return bool|IUser the created user or false
281
-	 */
282
-	public function createUser($uid, $password) {
283
-		$localBackends = [];
284
-		foreach ($this->backends as $backend) {
285
-			if ($backend instanceof Database) {
286
-				// First check if there is another user backend
287
-				$localBackends[] = $backend;
288
-				continue;
289
-			}
290
-
291
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
292
-				return $this->createUserFromBackend($uid, $password, $backend);
293
-			}
294
-		}
295
-
296
-		foreach ($localBackends as $backend) {
297
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
298
-				return $this->createUserFromBackend($uid, $password, $backend);
299
-			}
300
-		}
301
-
302
-		return false;
303
-	}
304
-
305
-	/**
306
-	 * @param string $uid
307
-	 * @param string $password
308
-	 * @param UserInterface $backend
309
-	 * @return IUser|null
310
-	 * @throws \InvalidArgumentException
311
-	 */
312
-	public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
-		$l = \OC::$server->getL10N('lib');
314
-
315
-		// Check the name for bad characters
316
-		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
-		if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
-			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
-				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
-		}
321
-		// No empty username
322
-		if (trim($uid) === '') {
323
-			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
-		}
325
-		// No whitespace at the beginning or at the end
326
-		if (trim($uid) !== $uid) {
327
-			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
-		}
329
-		// Username only consists of 1 or 2 dots (directory traversal)
330
-		if ($uid === '.' || $uid === '..') {
331
-			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
-		}
333
-		// No empty password
334
-		if (trim($password) === '') {
335
-			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
-		}
337
-
338
-		// Check if user already exists
339
-		if ($this->userExists($uid)) {
340
-			throw new \InvalidArgumentException($l->t('The username is already being used'));
341
-		}
342
-
343
-		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
-		$state = $backend->createUser($uid, $password);
345
-		if($state === false) {
346
-			throw new \InvalidArgumentException($l->t('Could not create user'));
347
-		}
348
-		$user = $this->getUserObject($uid, $backend);
349
-		if ($user instanceof IUser) {
350
-			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
-		}
352
-		return $user;
353
-	}
354
-
355
-	/**
356
-	 * returns how many users per backend exist (if supported by backend)
357
-	 *
358
-	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
-	 *                entry in the preferences table will be affected
360
-	 * @return array|int an array of backend class as key and count number as value
361
-	 *                if $hasLoggedIn is true only an int is returned
362
-	 */
363
-	public function countUsers($hasLoggedIn = false) {
364
-		if ($hasLoggedIn) {
365
-			return $this->countSeenUsers();
366
-		}
367
-		$userCountStatistics = [];
368
-		foreach ($this->backends as $backend) {
369
-			if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
-				$backendUsers = $backend->countUsers();
371
-				if($backendUsers !== false) {
372
-					if($backend instanceof IUserBackend) {
373
-						$name = $backend->getBackendName();
374
-					} else {
375
-						$name = get_class($backend);
376
-					}
377
-					if(isset($userCountStatistics[$name])) {
378
-						$userCountStatistics[$name] += $backendUsers;
379
-					} else {
380
-						$userCountStatistics[$name] = $backendUsers;
381
-					}
382
-				}
383
-			}
384
-		}
385
-		return $userCountStatistics;
386
-	}
387
-
388
-	/**
389
-	 * returns how many users per backend exist in the requested groups (if supported by backend)
390
-	 *
391
-	 * @param IGroup[] $groups an array of gid to search in
392
-	 * @return array|int an array of backend class as key and count number as value
393
-	 *                if $hasLoggedIn is true only an int is returned
394
-	 */
395
-	public function countUsersOfGroups(array $groups) {
396
-		$users = [];
397
-		foreach($groups as $group) {
398
-			$usersIds = array_map(function($user) {
399
-				return $user->getUID();
400
-			}, $group->getUsers());
401
-			$users = array_merge($users, $usersIds);
402
-		}
403
-		return count(array_unique($users));
404
-	}
405
-
406
-	/**
407
-	 * The callback is executed for each user on each backend.
408
-	 * If the callback returns false no further users will be retrieved.
409
-	 *
410
-	 * @param \Closure $callback
411
-	 * @param string $search
412
-	 * @param boolean $onlySeen when true only users that have a lastLogin entry
413
-	 *                in the preferences table will be affected
414
-	 * @since 9.0.0
415
-	 */
416
-	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
-		if ($onlySeen) {
418
-			$this->callForSeenUsers($callback);
419
-		} else {
420
-			foreach ($this->getBackends() as $backend) {
421
-				$limit = 500;
422
-				$offset = 0;
423
-				do {
424
-					$users = $backend->getUsers($search, $limit, $offset);
425
-					foreach ($users as $uid) {
426
-						if (!$backend->userExists($uid)) {
427
-							continue;
428
-						}
429
-						$user = $this->getUserObject($uid, $backend, false);
430
-						$return = $callback($user);
431
-						if ($return === false) {
432
-							break;
433
-						}
434
-					}
435
-					$offset += $limit;
436
-				} while (count($users) >= $limit);
437
-			}
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * returns how many users are disabled
443
-	 *
444
-	 * @return int
445
-	 * @since 12.0.0
446
-	 */
447
-	public function countDisabledUsers(): int {
448
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
-		$queryBuilder->select($queryBuilder->func()->count('*'))
450
-			->from('preferences')
451
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
61
+    /**
62
+     * @var \OCP\UserInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\User[] $cachedUsers
68
+     */
69
+    private $cachedUsers = array();
70
+
71
+    /**
72
+     * @var \OCP\IConfig $config
73
+     */
74
+    private $config;
75
+
76
+    /**
77
+     * @param \OCP\IConfig $config
78
+     */
79
+    public function __construct(IConfig $config) {
80
+        $this->config = $config;
81
+        $cachedUsers = &$this->cachedUsers;
82
+        $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
+            /** @var \OC\User\User $user */
84
+            unset($cachedUsers[$user->getUID()]);
85
+        });
86
+    }
87
+
88
+    /**
89
+     * Get the active backends
90
+     * @return \OCP\UserInterface[]
91
+     */
92
+    public function getBackends() {
93
+        return $this->backends;
94
+    }
95
+
96
+    /**
97
+     * register a user backend
98
+     *
99
+     * @param \OCP\UserInterface $backend
100
+     */
101
+    public function registerBackend($backend) {
102
+        $this->backends[] = $backend;
103
+    }
104
+
105
+    /**
106
+     * remove a user backend
107
+     *
108
+     * @param \OCP\UserInterface $backend
109
+     */
110
+    public function removeBackend($backend) {
111
+        $this->cachedUsers = array();
112
+        if (($i = array_search($backend, $this->backends)) !== false) {
113
+            unset($this->backends[$i]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * remove all user backends
119
+     */
120
+    public function clearBackends() {
121
+        $this->cachedUsers = array();
122
+        $this->backends = array();
123
+    }
124
+
125
+    /**
126
+     * get a user by user id
127
+     *
128
+     * @param string $uid
129
+     * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
+     */
131
+    public function get($uid) {
132
+        if (is_null($uid) || $uid === '' || $uid === false) {
133
+            return null;
134
+        }
135
+        if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
+            return $this->cachedUsers[$uid];
137
+        }
138
+        foreach ($this->backends as $backend) {
139
+            if ($backend->userExists($uid)) {
140
+                return $this->getUserObject($uid, $backend);
141
+            }
142
+        }
143
+        return null;
144
+    }
145
+
146
+    /**
147
+     * get or construct the user object
148
+     *
149
+     * @param string $uid
150
+     * @param \OCP\UserInterface $backend
151
+     * @param bool $cacheUser If false the newly created user object will not be cached
152
+     * @return \OC\User\User
153
+     */
154
+    protected function getUserObject($uid, $backend, $cacheUser = true) {
155
+        if (isset($this->cachedUsers[$uid])) {
156
+            return $this->cachedUsers[$uid];
157
+        }
158
+
159
+        $user = new User($uid, $backend, $this, $this->config);
160
+        if ($cacheUser) {
161
+            $this->cachedUsers[$uid] = $user;
162
+        }
163
+        return $user;
164
+    }
165
+
166
+    /**
167
+     * check if a user exists
168
+     *
169
+     * @param string $uid
170
+     * @return bool
171
+     */
172
+    public function userExists($uid) {
173
+        $user = $this->get($uid);
174
+        return ($user !== null);
175
+    }
176
+
177
+    /**
178
+     * Check if the password is valid for the user
179
+     *
180
+     * @param string $loginName
181
+     * @param string $password
182
+     * @return mixed the User object on success, false otherwise
183
+     */
184
+    public function checkPassword($loginName, $password) {
185
+        $result = $this->checkPasswordNoLogging($loginName, $password);
186
+
187
+        if ($result === false) {
188
+            \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
+        }
190
+
191
+        return $result;
192
+    }
193
+
194
+    /**
195
+     * Check if the password is valid for the user
196
+     *
197
+     * @internal
198
+     * @param string $loginName
199
+     * @param string $password
200
+     * @return mixed the User object on success, false otherwise
201
+     */
202
+    public function checkPasswordNoLogging($loginName, $password) {
203
+        $loginName = str_replace("\0", '', $loginName);
204
+        $password = str_replace("\0", '', $password);
205
+
206
+        foreach ($this->backends as $backend) {
207
+            if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
+                $uid = $backend->checkPassword($loginName, $password);
209
+                if ($uid !== false) {
210
+                    return $this->getUserObject($uid, $backend);
211
+                }
212
+            }
213
+        }
214
+
215
+        return false;
216
+    }
217
+
218
+    /**
219
+     * search by user id
220
+     *
221
+     * @param string $pattern
222
+     * @param int $limit
223
+     * @param int $offset
224
+     * @return \OC\User\User[]
225
+     */
226
+    public function search($pattern, $limit = null, $offset = null) {
227
+        $users = array();
228
+        foreach ($this->backends as $backend) {
229
+            $backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
+            if (is_array($backendUsers)) {
231
+                foreach ($backendUsers as $uid) {
232
+                    $users[$uid] = $this->getUserObject($uid, $backend);
233
+                }
234
+            }
235
+        }
236
+
237
+        uasort($users, function ($a, $b) {
238
+            /**
239
+             * @var \OC\User\User $a
240
+             * @var \OC\User\User $b
241
+             */
242
+            return strcasecmp($a->getUID(), $b->getUID());
243
+        });
244
+        return $users;
245
+    }
246
+
247
+    /**
248
+     * search by displayName
249
+     *
250
+     * @param string $pattern
251
+     * @param int $limit
252
+     * @param int $offset
253
+     * @return \OC\User\User[]
254
+     */
255
+    public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
+        $users = array();
257
+        foreach ($this->backends as $backend) {
258
+            $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
+            if (is_array($backendUsers)) {
260
+                foreach ($backendUsers as $uid => $displayName) {
261
+                    $users[] = $this->getUserObject($uid, $backend);
262
+                }
263
+            }
264
+        }
265
+
266
+        usort($users, function ($a, $b) {
267
+            /**
268
+             * @var \OC\User\User $a
269
+             * @var \OC\User\User $b
270
+             */
271
+            return strcasecmp($a->getDisplayName(), $b->getDisplayName());
272
+        });
273
+        return $users;
274
+    }
275
+
276
+    /**
277
+     * @param string $uid
278
+     * @param string $password
279
+     * @throws \InvalidArgumentException
280
+     * @return bool|IUser the created user or false
281
+     */
282
+    public function createUser($uid, $password) {
283
+        $localBackends = [];
284
+        foreach ($this->backends as $backend) {
285
+            if ($backend instanceof Database) {
286
+                // First check if there is another user backend
287
+                $localBackends[] = $backend;
288
+                continue;
289
+            }
290
+
291
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
292
+                return $this->createUserFromBackend($uid, $password, $backend);
293
+            }
294
+        }
295
+
296
+        foreach ($localBackends as $backend) {
297
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
298
+                return $this->createUserFromBackend($uid, $password, $backend);
299
+            }
300
+        }
301
+
302
+        return false;
303
+    }
304
+
305
+    /**
306
+     * @param string $uid
307
+     * @param string $password
308
+     * @param UserInterface $backend
309
+     * @return IUser|null
310
+     * @throws \InvalidArgumentException
311
+     */
312
+    public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
+        $l = \OC::$server->getL10N('lib');
314
+
315
+        // Check the name for bad characters
316
+        // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
+        if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
+            throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
+                . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
+        }
321
+        // No empty username
322
+        if (trim($uid) === '') {
323
+            throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
+        }
325
+        // No whitespace at the beginning or at the end
326
+        if (trim($uid) !== $uid) {
327
+            throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
+        }
329
+        // Username only consists of 1 or 2 dots (directory traversal)
330
+        if ($uid === '.' || $uid === '..') {
331
+            throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
+        }
333
+        // No empty password
334
+        if (trim($password) === '') {
335
+            throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
+        }
337
+
338
+        // Check if user already exists
339
+        if ($this->userExists($uid)) {
340
+            throw new \InvalidArgumentException($l->t('The username is already being used'));
341
+        }
342
+
343
+        $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
+        $state = $backend->createUser($uid, $password);
345
+        if($state === false) {
346
+            throw new \InvalidArgumentException($l->t('Could not create user'));
347
+        }
348
+        $user = $this->getUserObject($uid, $backend);
349
+        if ($user instanceof IUser) {
350
+            $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
+        }
352
+        return $user;
353
+    }
354
+
355
+    /**
356
+     * returns how many users per backend exist (if supported by backend)
357
+     *
358
+     * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
+     *                entry in the preferences table will be affected
360
+     * @return array|int an array of backend class as key and count number as value
361
+     *                if $hasLoggedIn is true only an int is returned
362
+     */
363
+    public function countUsers($hasLoggedIn = false) {
364
+        if ($hasLoggedIn) {
365
+            return $this->countSeenUsers();
366
+        }
367
+        $userCountStatistics = [];
368
+        foreach ($this->backends as $backend) {
369
+            if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
+                $backendUsers = $backend->countUsers();
371
+                if($backendUsers !== false) {
372
+                    if($backend instanceof IUserBackend) {
373
+                        $name = $backend->getBackendName();
374
+                    } else {
375
+                        $name = get_class($backend);
376
+                    }
377
+                    if(isset($userCountStatistics[$name])) {
378
+                        $userCountStatistics[$name] += $backendUsers;
379
+                    } else {
380
+                        $userCountStatistics[$name] = $backendUsers;
381
+                    }
382
+                }
383
+            }
384
+        }
385
+        return $userCountStatistics;
386
+    }
387
+
388
+    /**
389
+     * returns how many users per backend exist in the requested groups (if supported by backend)
390
+     *
391
+     * @param IGroup[] $groups an array of gid to search in
392
+     * @return array|int an array of backend class as key and count number as value
393
+     *                if $hasLoggedIn is true only an int is returned
394
+     */
395
+    public function countUsersOfGroups(array $groups) {
396
+        $users = [];
397
+        foreach($groups as $group) {
398
+            $usersIds = array_map(function($user) {
399
+                return $user->getUID();
400
+            }, $group->getUsers());
401
+            $users = array_merge($users, $usersIds);
402
+        }
403
+        return count(array_unique($users));
404
+    }
405
+
406
+    /**
407
+     * The callback is executed for each user on each backend.
408
+     * If the callback returns false no further users will be retrieved.
409
+     *
410
+     * @param \Closure $callback
411
+     * @param string $search
412
+     * @param boolean $onlySeen when true only users that have a lastLogin entry
413
+     *                in the preferences table will be affected
414
+     * @since 9.0.0
415
+     */
416
+    public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
+        if ($onlySeen) {
418
+            $this->callForSeenUsers($callback);
419
+        } else {
420
+            foreach ($this->getBackends() as $backend) {
421
+                $limit = 500;
422
+                $offset = 0;
423
+                do {
424
+                    $users = $backend->getUsers($search, $limit, $offset);
425
+                    foreach ($users as $uid) {
426
+                        if (!$backend->userExists($uid)) {
427
+                            continue;
428
+                        }
429
+                        $user = $this->getUserObject($uid, $backend, false);
430
+                        $return = $callback($user);
431
+                        if ($return === false) {
432
+                            break;
433
+                        }
434
+                    }
435
+                    $offset += $limit;
436
+                } while (count($users) >= $limit);
437
+            }
438
+        }
439
+    }
440
+
441
+    /**
442
+     * returns how many users are disabled
443
+     *
444
+     * @return int
445
+     * @since 12.0.0
446
+     */
447
+    public function countDisabledUsers(): int {
448
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
+        $queryBuilder->select($queryBuilder->func()->count('*'))
450
+            ->from('preferences')
451
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
454 454
 
455 455
 		
456
-		$result = $queryBuilder->execute();
457
-		$count = $result->fetchColumn();
458
-		$result->closeCursor();
456
+        $result = $queryBuilder->execute();
457
+        $count = $result->fetchColumn();
458
+        $result->closeCursor();
459 459
 		
460
-		if ($count !== false) {
461
-			$count = (int)$count;
462
-		} else {
463
-			$count = 0;
464
-		}
465
-
466
-		return $count;
467
-	}
468
-
469
-	/**
470
-	 * returns how many users are disabled in the requested groups
471
-	 *
472
-	 * @param array $groups groupids to search
473
-	 * @return int
474
-	 * @since 14.0.0
475
-	 */
476
-	public function countDisabledUsersOfGroups(array $groups): int {
477
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
479
-			->from('preferences', 'p')
480
-			->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
481
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
-			->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
-
486
-		$result = $queryBuilder->execute();
487
-		$count = $result->fetchColumn();
488
-		$result->closeCursor();
460
+        if ($count !== false) {
461
+            $count = (int)$count;
462
+        } else {
463
+            $count = 0;
464
+        }
465
+
466
+        return $count;
467
+    }
468
+
469
+    /**
470
+     * returns how many users are disabled in the requested groups
471
+     *
472
+     * @param array $groups groupids to search
473
+     * @return int
474
+     * @since 14.0.0
475
+     */
476
+    public function countDisabledUsersOfGroups(array $groups): int {
477
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
479
+            ->from('preferences', 'p')
480
+            ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
481
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
+            ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
+
486
+        $result = $queryBuilder->execute();
487
+        $count = $result->fetchColumn();
488
+        $result->closeCursor();
489 489
 		
490
-		if ($count !== false) {
491
-			$count = (int)$count;
492
-		} else {
493
-			$count = 0;
494
-		}
495
-
496
-		return $count;
497
-	}
498
-
499
-	/**
500
-	 * returns how many users have logged in once
501
-	 *
502
-	 * @return int
503
-	 * @since 11.0.0
504
-	 */
505
-	public function countSeenUsers() {
506
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
-		$queryBuilder->select($queryBuilder->func()->count('*'))
508
-			->from('preferences')
509
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
-
513
-		$query = $queryBuilder->execute();
514
-
515
-		$result = (int)$query->fetchColumn();
516
-		$query->closeCursor();
517
-
518
-		return $result;
519
-	}
520
-
521
-	/**
522
-	 * @param \Closure $callback
523
-	 * @since 11.0.0
524
-	 */
525
-	public function callForSeenUsers(\Closure $callback) {
526
-		$limit = 1000;
527
-		$offset = 0;
528
-		do {
529
-			$userIds = $this->getSeenUserIds($limit, $offset);
530
-			$offset += $limit;
531
-			foreach ($userIds as $userId) {
532
-				foreach ($this->backends as $backend) {
533
-					if ($backend->userExists($userId)) {
534
-						$user = $this->getUserObject($userId, $backend, false);
535
-						$return = $callback($user);
536
-						if ($return === false) {
537
-							return;
538
-						}
539
-						break;
540
-					}
541
-				}
542
-			}
543
-		} while (count($userIds) >= $limit);
544
-	}
545
-
546
-	/**
547
-	 * Getting all userIds that have a listLogin value requires checking the
548
-	 * value in php because on oracle you cannot use a clob in a where clause,
549
-	 * preventing us from doing a not null or length(value) > 0 check.
550
-	 *
551
-	 * @param int $limit
552
-	 * @param int $offset
553
-	 * @return string[] with user ids
554
-	 */
555
-	private function getSeenUserIds($limit = null, $offset = null) {
556
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
-		$queryBuilder->select(['userid'])
558
-			->from('preferences')
559
-			->where($queryBuilder->expr()->eq(
560
-				'appid', $queryBuilder->createNamedParameter('login'))
561
-			)
562
-			->andWhere($queryBuilder->expr()->eq(
563
-				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
-			)
565
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
-			);
567
-
568
-		if ($limit !== null) {
569
-			$queryBuilder->setMaxResults($limit);
570
-		}
571
-		if ($offset !== null) {
572
-			$queryBuilder->setFirstResult($offset);
573
-		}
574
-		$query = $queryBuilder->execute();
575
-		$result = [];
576
-
577
-		while ($row = $query->fetch()) {
578
-			$result[] = $row['userid'];
579
-		}
580
-
581
-		$query->closeCursor();
582
-
583
-		return $result;
584
-	}
585
-
586
-	/**
587
-	 * @param string $email
588
-	 * @return IUser[]
589
-	 * @since 9.1.0
590
-	 */
591
-	public function getByEmail($email) {
592
-		$userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
593
-
594
-		$users = array_map(function($uid) {
595
-			return $this->get($uid);
596
-		}, $userIds);
597
-
598
-		return array_values(array_filter($users, function($u) {
599
-			return ($u instanceof IUser);
600
-		}));
601
-	}
490
+        if ($count !== false) {
491
+            $count = (int)$count;
492
+        } else {
493
+            $count = 0;
494
+        }
495
+
496
+        return $count;
497
+    }
498
+
499
+    /**
500
+     * returns how many users have logged in once
501
+     *
502
+     * @return int
503
+     * @since 11.0.0
504
+     */
505
+    public function countSeenUsers() {
506
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
+        $queryBuilder->select($queryBuilder->func()->count('*'))
508
+            ->from('preferences')
509
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
+
513
+        $query = $queryBuilder->execute();
514
+
515
+        $result = (int)$query->fetchColumn();
516
+        $query->closeCursor();
517
+
518
+        return $result;
519
+    }
520
+
521
+    /**
522
+     * @param \Closure $callback
523
+     * @since 11.0.0
524
+     */
525
+    public function callForSeenUsers(\Closure $callback) {
526
+        $limit = 1000;
527
+        $offset = 0;
528
+        do {
529
+            $userIds = $this->getSeenUserIds($limit, $offset);
530
+            $offset += $limit;
531
+            foreach ($userIds as $userId) {
532
+                foreach ($this->backends as $backend) {
533
+                    if ($backend->userExists($userId)) {
534
+                        $user = $this->getUserObject($userId, $backend, false);
535
+                        $return = $callback($user);
536
+                        if ($return === false) {
537
+                            return;
538
+                        }
539
+                        break;
540
+                    }
541
+                }
542
+            }
543
+        } while (count($userIds) >= $limit);
544
+    }
545
+
546
+    /**
547
+     * Getting all userIds that have a listLogin value requires checking the
548
+     * value in php because on oracle you cannot use a clob in a where clause,
549
+     * preventing us from doing a not null or length(value) > 0 check.
550
+     *
551
+     * @param int $limit
552
+     * @param int $offset
553
+     * @return string[] with user ids
554
+     */
555
+    private function getSeenUserIds($limit = null, $offset = null) {
556
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
+        $queryBuilder->select(['userid'])
558
+            ->from('preferences')
559
+            ->where($queryBuilder->expr()->eq(
560
+                'appid', $queryBuilder->createNamedParameter('login'))
561
+            )
562
+            ->andWhere($queryBuilder->expr()->eq(
563
+                'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
+            )
565
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
+            );
567
+
568
+        if ($limit !== null) {
569
+            $queryBuilder->setMaxResults($limit);
570
+        }
571
+        if ($offset !== null) {
572
+            $queryBuilder->setFirstResult($offset);
573
+        }
574
+        $query = $queryBuilder->execute();
575
+        $result = [];
576
+
577
+        while ($row = $query->fetch()) {
578
+            $result[] = $row['userid'];
579
+        }
580
+
581
+        $query->closeCursor();
582
+
583
+        return $result;
584
+    }
585
+
586
+    /**
587
+     * @param string $email
588
+     * @return IUser[]
589
+     * @since 9.1.0
590
+     */
591
+    public function getByEmail($email) {
592
+        $userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
593
+
594
+        $users = array_map(function($uid) {
595
+            return $this->get($uid);
596
+        }, $userIds);
597
+
598
+        return array_values(array_filter($users, function($u) {
599
+            return ($u instanceof IUser);
600
+        }));
601
+    }
602 602
 }
Please login to merge, or discard this patch.
lib/private/Group/Database.php 1 patch
Indentation   +349 added lines, -349 removed lines patch added patch discarded remove patch
@@ -55,357 +55,357 @@
 block discarded – undo
55 55
  * Class for group management in a SQL Database (e.g. MySQL, SQLite)
56 56
  */
57 57
 class Database extends ABackend
58
-	implements IAddToGroupBackend,
59
-	           ICountDisabledInGroup,
60
-	           ICountUsersBackend,
61
-	           ICreateGroupBackend,
62
-	           IDeleteGroupBackend,
63
-	           IRemoveFromGroupBackend {
64
-
65
-	/** @var string[] */
66
-	private $groupCache = [];
67
-
68
-	/** @var IDBConnection */
69
-	private $dbConn;
70
-
71
-	/**
72
-	 * \OC\Group\Database constructor.
73
-	 *
74
-	 * @param IDBConnection|null $dbConn
75
-	 */
76
-	public function __construct(IDBConnection $dbConn = null) {
77
-		$this->dbConn = $dbConn;
78
-	}
79
-
80
-	/**
81
-	 * FIXME: This function should not be required!
82
-	 */
83
-	private function fixDI() {
84
-		if ($this->dbConn === null) {
85
-			$this->dbConn = \OC::$server->getDatabaseConnection();
86
-		}
87
-	}
88
-
89
-	/**
90
-	 * Try to create a new group
91
-	 * @param string $gid The name of the group to create
92
-	 * @return bool
93
-	 *
94
-	 * Tries to create a new group. If the group name already exists, false will
95
-	 * be returned.
96
-	 */
97
-	public function createGroup(string $gid): bool {
98
-		$this->fixDI();
99
-
100
-		// Add group
101
-		$result = $this->dbConn->insertIfNotExist('*PREFIX*groups', [
102
-			'gid' => $gid,
103
-		]);
104
-
105
-		// Add to cache
106
-		$this->groupCache[$gid] = $gid;
107
-
108
-		return $result === 1;
109
-	}
110
-
111
-	/**
112
-	 * delete a group
113
-	 * @param string $gid gid of the group to delete
114
-	 * @return bool
115
-	 *
116
-	 * Deletes a group and removes it from the group_user-table
117
-	 */
118
-	public function deleteGroup(string $gid): bool {
119
-		$this->fixDI();
120
-
121
-		// Delete the group
122
-		$qb = $this->dbConn->getQueryBuilder();
123
-		$qb->delete('groups')
124
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
125
-			->execute();
126
-
127
-		// Delete the group-user relation
128
-		$qb = $this->dbConn->getQueryBuilder();
129
-		$qb->delete('group_user')
130
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
131
-			->execute();
132
-
133
-		// Delete the group-groupadmin relation
134
-		$qb = $this->dbConn->getQueryBuilder();
135
-		$qb->delete('group_admin')
136
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
137
-			->execute();
138
-
139
-		// Delete from cache
140
-		unset($this->groupCache[$gid]);
141
-
142
-		return true;
143
-	}
144
-
145
-	/**
146
-	 * is user in group?
147
-	 * @param string $uid uid of the user
148
-	 * @param string $gid gid of the group
149
-	 * @return bool
150
-	 *
151
-	 * Checks whether the user is member of a group or not.
152
-	 */
153
-	public function inGroup( $uid, $gid ) {
154
-		$this->fixDI();
155
-
156
-		// check
157
-		$qb = $this->dbConn->getQueryBuilder();
158
-		$cursor = $qb->select('uid')
159
-			->from('group_user')
160
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
161
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
162
-			->execute();
163
-
164
-		$result = $cursor->fetch();
165
-		$cursor->closeCursor();
166
-
167
-		return $result ? true : false;
168
-	}
169
-
170
-	/**
171
-	 * Add a user to a group
172
-	 * @param string $uid Name of the user to add to group
173
-	 * @param string $gid Name of the group in which add the user
174
-	 * @return bool
175
-	 *
176
-	 * Adds a user to a group.
177
-	 */
178
-	public function addToGroup(string $uid, string $gid): bool {
179
-		$this->fixDI();
180
-
181
-		// No duplicate entries!
182
-		if( !$this->inGroup( $uid, $gid )) {
183
-			$qb = $this->dbConn->getQueryBuilder();
184
-			$qb->insert('group_user')
185
-				->setValue('uid', $qb->createNamedParameter($uid))
186
-				->setValue('gid', $qb->createNamedParameter($gid))
187
-				->execute();
188
-			return true;
189
-		}else{
190
-			return false;
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * Removes a user from a group
196
-	 * @param string $uid Name of the user to remove from group
197
-	 * @param string $gid Name of the group from which remove the user
198
-	 * @return bool
199
-	 *
200
-	 * removes the user from a group.
201
-	 */
202
-	public function removeFromGroup(string $uid, string $gid): bool {
203
-		$this->fixDI();
204
-
205
-		$qb = $this->dbConn->getQueryBuilder();
206
-		$qb->delete('group_user')
207
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
208
-			->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
209
-			->execute();
210
-
211
-		return true;
212
-	}
213
-
214
-	/**
215
-	 * Get all groups a user belongs to
216
-	 * @param string $uid Name of the user
217
-	 * @return array an array of group names
218
-	 *
219
-	 * This function fetches all groups a user belongs to. It does not check
220
-	 * if the user exists at all.
221
-	 */
222
-	public function getUserGroups( $uid ) {
223
-		//guests has empty or null $uid
224
-		if ($uid === null || $uid === '') {
225
-			return [];
226
-		}
227
-
228
-		$this->fixDI();
229
-
230
-		// No magic!
231
-		$qb = $this->dbConn->getQueryBuilder();
232
-		$cursor = $qb->select('gid')
233
-			->from('group_user')
234
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
235
-			->execute();
236
-
237
-		$groups = [];
238
-		while( $row = $cursor->fetch()) {
239
-			$groups[] = $row['gid'];
240
-			$this->groupCache[$row['gid']] = $row['gid'];
241
-		}
242
-		$cursor->closeCursor();
243
-
244
-		return $groups;
245
-	}
246
-
247
-	/**
248
-	 * get a list of all groups
249
-	 * @param string $search
250
-	 * @param int $limit
251
-	 * @param int $offset
252
-	 * @return array an array of group names
253
-	 *
254
-	 * Returns a list with all groups
255
-	 */
256
-	public function getGroups($search = '', $limit = null, $offset = null) {
257
-		$this->fixDI();
258
-
259
-		$query = $this->dbConn->getQueryBuilder();
260
-		$query->select('gid')
261
-			->from('groups')
262
-			->orderBy('gid', 'ASC');
263
-
264
-		if ($search !== '') {
265
-			$query->where($query->expr()->iLike('gid', $query->createNamedParameter(
266
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
267
-			)));
268
-		}
269
-
270
-		$query->setMaxResults($limit)
271
-			->setFirstResult($offset);
272
-		$result = $query->execute();
273
-
274
-		$groups = [];
275
-		while ($row = $result->fetch()) {
276
-			$groups[] = $row['gid'];
277
-		}
278
-		$result->closeCursor();
279
-
280
-		return $groups;
281
-	}
282
-
283
-	/**
284
-	 * check if a group exists
285
-	 * @param string $gid
286
-	 * @return bool
287
-	 */
288
-	public function groupExists($gid) {
289
-		$this->fixDI();
290
-
291
-		// Check cache first
292
-		if (isset($this->groupCache[$gid])) {
293
-			return true;
294
-		}
295
-
296
-		$qb = $this->dbConn->getQueryBuilder();
297
-		$cursor = $qb->select('gid')
298
-			->from('groups')
299
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
300
-			->execute();
301
-		$result = $cursor->fetch();
302
-		$cursor->closeCursor();
303
-
304
-		if ($result !== false) {
305
-			$this->groupCache[$gid] = $gid;
306
-			return true;
307
-		}
308
-		return false;
309
-	}
310
-
311
-	/**
312
-	 * get a list of all users in a group
313
-	 * @param string $gid
314
-	 * @param string $search
315
-	 * @param int $limit
316
-	 * @param int $offset
317
-	 * @return array an array of user ids
318
-	 */
319
-	public function usersInGroup($gid, $search = '', $limit = null, $offset = null) {
320
-		$this->fixDI();
321
-
322
-		$query = $this->dbConn->getQueryBuilder();
323
-		$query->select('uid')
324
-			->from('group_user')
325
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
326
-			->orderBy('uid', 'ASC');
327
-
328
-		if ($search !== '') {
329
-			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
330
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
331
-			)));
332
-		}
333
-
334
-		$query->setMaxResults($limit)
335
-			->setFirstResult($offset);
336
-		$result = $query->execute();
337
-
338
-		$users = [];
339
-		while ($row = $result->fetch()) {
340
-			$users[] = $row['uid'];
341
-		}
342
-		$result->closeCursor();
343
-
344
-		return $users;
345
-	}
346
-
347
-	/**
348
-	 * get the number of all users matching the search string in a group
349
-	 * @param string $gid
350
-	 * @param string $search
351
-	 * @return int
352
-	 */
353
-	public function countUsersInGroup(string $gid, string $search = ''): int {
354
-		$this->fixDI();
355
-
356
-		$query = $this->dbConn->getQueryBuilder();
357
-		$query->select($query->func()->count('*', 'num_users'))
358
-			->from('group_user')
359
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
360
-
361
-		if ($search !== '') {
362
-			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
363
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
364
-			)));
365
-		}
366
-
367
-		$result = $query->execute();
368
-		$count = $result->fetchColumn();
369
-		$result->closeCursor();
370
-
371
-		if ($count !== false) {
372
-			$count = (int)$count;
373
-		} else {
374
-			$count = 0;
375
-		}
376
-
377
-		return $count;
378
-	}
379
-
380
-	/**
381
-	 * get the number of disabled users in a group
382
-	 *
383
-	 * @param string $search
384
-	 * @return int|bool
385
-	 */
386
-	public function countDisabledInGroup(string $gid): int {
387
-		$this->fixDI();
58
+    implements IAddToGroupBackend,
59
+                ICountDisabledInGroup,
60
+                ICountUsersBackend,
61
+                ICreateGroupBackend,
62
+                IDeleteGroupBackend,
63
+                IRemoveFromGroupBackend {
64
+
65
+    /** @var string[] */
66
+    private $groupCache = [];
67
+
68
+    /** @var IDBConnection */
69
+    private $dbConn;
70
+
71
+    /**
72
+     * \OC\Group\Database constructor.
73
+     *
74
+     * @param IDBConnection|null $dbConn
75
+     */
76
+    public function __construct(IDBConnection $dbConn = null) {
77
+        $this->dbConn = $dbConn;
78
+    }
79
+
80
+    /**
81
+     * FIXME: This function should not be required!
82
+     */
83
+    private function fixDI() {
84
+        if ($this->dbConn === null) {
85
+            $this->dbConn = \OC::$server->getDatabaseConnection();
86
+        }
87
+    }
88
+
89
+    /**
90
+     * Try to create a new group
91
+     * @param string $gid The name of the group to create
92
+     * @return bool
93
+     *
94
+     * Tries to create a new group. If the group name already exists, false will
95
+     * be returned.
96
+     */
97
+    public function createGroup(string $gid): bool {
98
+        $this->fixDI();
99
+
100
+        // Add group
101
+        $result = $this->dbConn->insertIfNotExist('*PREFIX*groups', [
102
+            'gid' => $gid,
103
+        ]);
104
+
105
+        // Add to cache
106
+        $this->groupCache[$gid] = $gid;
107
+
108
+        return $result === 1;
109
+    }
110
+
111
+    /**
112
+     * delete a group
113
+     * @param string $gid gid of the group to delete
114
+     * @return bool
115
+     *
116
+     * Deletes a group and removes it from the group_user-table
117
+     */
118
+    public function deleteGroup(string $gid): bool {
119
+        $this->fixDI();
120
+
121
+        // Delete the group
122
+        $qb = $this->dbConn->getQueryBuilder();
123
+        $qb->delete('groups')
124
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
125
+            ->execute();
126
+
127
+        // Delete the group-user relation
128
+        $qb = $this->dbConn->getQueryBuilder();
129
+        $qb->delete('group_user')
130
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
131
+            ->execute();
132
+
133
+        // Delete the group-groupadmin relation
134
+        $qb = $this->dbConn->getQueryBuilder();
135
+        $qb->delete('group_admin')
136
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
137
+            ->execute();
138
+
139
+        // Delete from cache
140
+        unset($this->groupCache[$gid]);
141
+
142
+        return true;
143
+    }
144
+
145
+    /**
146
+     * is user in group?
147
+     * @param string $uid uid of the user
148
+     * @param string $gid gid of the group
149
+     * @return bool
150
+     *
151
+     * Checks whether the user is member of a group or not.
152
+     */
153
+    public function inGroup( $uid, $gid ) {
154
+        $this->fixDI();
155
+
156
+        // check
157
+        $qb = $this->dbConn->getQueryBuilder();
158
+        $cursor = $qb->select('uid')
159
+            ->from('group_user')
160
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
161
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
162
+            ->execute();
163
+
164
+        $result = $cursor->fetch();
165
+        $cursor->closeCursor();
166
+
167
+        return $result ? true : false;
168
+    }
169
+
170
+    /**
171
+     * Add a user to a group
172
+     * @param string $uid Name of the user to add to group
173
+     * @param string $gid Name of the group in which add the user
174
+     * @return bool
175
+     *
176
+     * Adds a user to a group.
177
+     */
178
+    public function addToGroup(string $uid, string $gid): bool {
179
+        $this->fixDI();
180
+
181
+        // No duplicate entries!
182
+        if( !$this->inGroup( $uid, $gid )) {
183
+            $qb = $this->dbConn->getQueryBuilder();
184
+            $qb->insert('group_user')
185
+                ->setValue('uid', $qb->createNamedParameter($uid))
186
+                ->setValue('gid', $qb->createNamedParameter($gid))
187
+                ->execute();
188
+            return true;
189
+        }else{
190
+            return false;
191
+        }
192
+    }
193
+
194
+    /**
195
+     * Removes a user from a group
196
+     * @param string $uid Name of the user to remove from group
197
+     * @param string $gid Name of the group from which remove the user
198
+     * @return bool
199
+     *
200
+     * removes the user from a group.
201
+     */
202
+    public function removeFromGroup(string $uid, string $gid): bool {
203
+        $this->fixDI();
204
+
205
+        $qb = $this->dbConn->getQueryBuilder();
206
+        $qb->delete('group_user')
207
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
208
+            ->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
209
+            ->execute();
210
+
211
+        return true;
212
+    }
213
+
214
+    /**
215
+     * Get all groups a user belongs to
216
+     * @param string $uid Name of the user
217
+     * @return array an array of group names
218
+     *
219
+     * This function fetches all groups a user belongs to. It does not check
220
+     * if the user exists at all.
221
+     */
222
+    public function getUserGroups( $uid ) {
223
+        //guests has empty or null $uid
224
+        if ($uid === null || $uid === '') {
225
+            return [];
226
+        }
227
+
228
+        $this->fixDI();
229
+
230
+        // No magic!
231
+        $qb = $this->dbConn->getQueryBuilder();
232
+        $cursor = $qb->select('gid')
233
+            ->from('group_user')
234
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
235
+            ->execute();
236
+
237
+        $groups = [];
238
+        while( $row = $cursor->fetch()) {
239
+            $groups[] = $row['gid'];
240
+            $this->groupCache[$row['gid']] = $row['gid'];
241
+        }
242
+        $cursor->closeCursor();
243
+
244
+        return $groups;
245
+    }
246
+
247
+    /**
248
+     * get a list of all groups
249
+     * @param string $search
250
+     * @param int $limit
251
+     * @param int $offset
252
+     * @return array an array of group names
253
+     *
254
+     * Returns a list with all groups
255
+     */
256
+    public function getGroups($search = '', $limit = null, $offset = null) {
257
+        $this->fixDI();
258
+
259
+        $query = $this->dbConn->getQueryBuilder();
260
+        $query->select('gid')
261
+            ->from('groups')
262
+            ->orderBy('gid', 'ASC');
263
+
264
+        if ($search !== '') {
265
+            $query->where($query->expr()->iLike('gid', $query->createNamedParameter(
266
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
267
+            )));
268
+        }
269
+
270
+        $query->setMaxResults($limit)
271
+            ->setFirstResult($offset);
272
+        $result = $query->execute();
273
+
274
+        $groups = [];
275
+        while ($row = $result->fetch()) {
276
+            $groups[] = $row['gid'];
277
+        }
278
+        $result->closeCursor();
279
+
280
+        return $groups;
281
+    }
282
+
283
+    /**
284
+     * check if a group exists
285
+     * @param string $gid
286
+     * @return bool
287
+     */
288
+    public function groupExists($gid) {
289
+        $this->fixDI();
290
+
291
+        // Check cache first
292
+        if (isset($this->groupCache[$gid])) {
293
+            return true;
294
+        }
295
+
296
+        $qb = $this->dbConn->getQueryBuilder();
297
+        $cursor = $qb->select('gid')
298
+            ->from('groups')
299
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
300
+            ->execute();
301
+        $result = $cursor->fetch();
302
+        $cursor->closeCursor();
303
+
304
+        if ($result !== false) {
305
+            $this->groupCache[$gid] = $gid;
306
+            return true;
307
+        }
308
+        return false;
309
+    }
310
+
311
+    /**
312
+     * get a list of all users in a group
313
+     * @param string $gid
314
+     * @param string $search
315
+     * @param int $limit
316
+     * @param int $offset
317
+     * @return array an array of user ids
318
+     */
319
+    public function usersInGroup($gid, $search = '', $limit = null, $offset = null) {
320
+        $this->fixDI();
321
+
322
+        $query = $this->dbConn->getQueryBuilder();
323
+        $query->select('uid')
324
+            ->from('group_user')
325
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
326
+            ->orderBy('uid', 'ASC');
327
+
328
+        if ($search !== '') {
329
+            $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
330
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
331
+            )));
332
+        }
333
+
334
+        $query->setMaxResults($limit)
335
+            ->setFirstResult($offset);
336
+        $result = $query->execute();
337
+
338
+        $users = [];
339
+        while ($row = $result->fetch()) {
340
+            $users[] = $row['uid'];
341
+        }
342
+        $result->closeCursor();
343
+
344
+        return $users;
345
+    }
346
+
347
+    /**
348
+     * get the number of all users matching the search string in a group
349
+     * @param string $gid
350
+     * @param string $search
351
+     * @return int
352
+     */
353
+    public function countUsersInGroup(string $gid, string $search = ''): int {
354
+        $this->fixDI();
355
+
356
+        $query = $this->dbConn->getQueryBuilder();
357
+        $query->select($query->func()->count('*', 'num_users'))
358
+            ->from('group_user')
359
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
360
+
361
+        if ($search !== '') {
362
+            $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
363
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
364
+            )));
365
+        }
366
+
367
+        $result = $query->execute();
368
+        $count = $result->fetchColumn();
369
+        $result->closeCursor();
370
+
371
+        if ($count !== false) {
372
+            $count = (int)$count;
373
+        } else {
374
+            $count = 0;
375
+        }
376
+
377
+        return $count;
378
+    }
379
+
380
+    /**
381
+     * get the number of disabled users in a group
382
+     *
383
+     * @param string $search
384
+     * @return int|bool
385
+     */
386
+    public function countDisabledInGroup(string $gid): int {
387
+        $this->fixDI();
388 388
 		
389
-		$query = $this->dbConn->getQueryBuilder();
390
-		$query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
391
-			->from('preferences', 'p')
392
-			->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
393
-			->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
394
-			->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
395
-			->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
396
-			->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
389
+        $query = $this->dbConn->getQueryBuilder();
390
+        $query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
391
+            ->from('preferences', 'p')
392
+            ->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
393
+            ->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
394
+            ->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
395
+            ->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
396
+            ->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
397 397
 		
398
-		$result = $query->execute();
399
-		$count = $result->fetchColumn();
400
-		$result->closeCursor();
398
+        $result = $query->execute();
399
+        $count = $result->fetchColumn();
400
+        $result->closeCursor();
401 401
 		
402
-		if ($count !== false) {
403
-			$count = (int)$count;
404
-		} else {
405
-			$count = 0;
406
-		}
407
-
408
-		return $count;
409
-	}
402
+        if ($count !== false) {
403
+            $count = (int)$count;
404
+        } else {
405
+            $count = 0;
406
+        }
407
+
408
+        return $count;
409
+    }
410 410
 
411 411
 }
Please login to merge, or discard this patch.
lib/private/SystemTag/SystemTagObjectMapper.php 1 patch
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -37,229 +37,229 @@
 block discarded – undo
37 37
 
38 38
 class SystemTagObjectMapper implements ISystemTagObjectMapper {
39 39
 
40
-	const RELATION_TABLE = 'systemtag_object_mapping';
41
-
42
-	/** @var ISystemTagManager */
43
-	protected $tagManager;
44
-
45
-	/** @var IDBConnection */
46
-	protected $connection;
47
-
48
-	/** @var EventDispatcherInterface */
49
-	protected $dispatcher;
50
-
51
-	/**
52
-	* Constructor.
53
-	*
54
-	* @param IDBConnection $connection database connection
55
-	* @param ISystemTagManager $tagManager system tag manager
56
-	* @param EventDispatcherInterface $dispatcher
57
-	*/
58
-	public function __construct(IDBConnection $connection, ISystemTagManager $tagManager, EventDispatcherInterface $dispatcher) {
59
-		$this->connection = $connection;
60
-		$this->tagManager = $tagManager;
61
-		$this->dispatcher = $dispatcher;
62
-	}
63
-
64
-	/**
65
-	 * {@inheritdoc}
66
-	 */
67
-	public function getTagIdsForObjects($objIds, string $objectType): array {
68
-		if (!\is_array($objIds)) {
69
-			$objIds = [$objIds];
70
-		} else if (empty($objIds)) {
71
-			return [];
72
-		}
73
-
74
-		$query = $this->connection->getQueryBuilder();
75
-		$query->select(['systemtagid', 'objectid'])
76
-			->from(self::RELATION_TABLE)
77
-			->where($query->expr()->in('objectid', $query->createParameter('objectids')))
78
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
79
-			->setParameter('objectids', $objIds, IQueryBuilder::PARAM_INT_ARRAY)
80
-			->setParameter('objecttype', $objectType)
81
-			->addOrderBy('objectid', 'ASC')
82
-			->addOrderBy('systemtagid', 'ASC');
83
-
84
-		$mapping = [];
85
-		foreach ($objIds as $objId) {
86
-			$mapping[$objId] = [];
87
-		}
88
-
89
-		$result = $query->execute();
90
-		while ($row = $result->fetch()) {
91
-			$objectId = $row['objectid'];
92
-			$mapping[$objectId][] = $row['systemtagid'];
93
-		}
94
-
95
-		$result->closeCursor();
96
-
97
-		return $mapping;
98
-	}
99
-
100
-	/**
101
-	 * {@inheritdoc}
102
-	 */
103
-	public function getObjectIdsForTags($tagIds, string $objectType, int $limit = 0, string $offset = ''): array {
104
-		if (!\is_array($tagIds)) {
105
-			$tagIds = [$tagIds];
106
-		}
107
-
108
-		$this->assertTagsExist($tagIds);
109
-
110
-		$query = $this->connection->getQueryBuilder();
111
-		$query->selectDistinct('objectid')
112
-			->from(self::RELATION_TABLE)
113
-			->where($query->expr()->in('systemtagid', $query->createNamedParameter($tagIds, IQueryBuilder::PARAM_INT_ARRAY)))
114
-			->andWhere($query->expr()->eq('objecttype', $query->createNamedParameter($objectType)));
115
-
116
-		if ($limit) {
117
-			if (\count($tagIds) !== 1) {
118
-				throw new \InvalidArgumentException('Limit is only allowed with a single tag');
119
-			}
120
-
121
-			$query->setMaxResults($limit)
122
-				->orderBy('objectid', 'ASC');
123
-
124
-			if ($offset !== '') {
125
-				$query->andWhere($query->expr()->gt('objectid', $query->createNamedParameter($offset)));
126
-			}
127
-		}
128
-
129
-		$objectIds = [];
130
-
131
-		$result = $query->execute();
132
-		while ($row = $result->fetch()) {
133
-			$objectIds[] = $row['objectid'];
134
-		}
135
-
136
-		return $objectIds;
137
-	}
138
-
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function assignTags(string $objId, string $objectType, $tagIds) {
143
-		if (!\is_array($tagIds)) {
144
-			$tagIds = [$tagIds];
145
-		}
146
-
147
-		$this->assertTagsExist($tagIds);
148
-
149
-		$query = $this->connection->getQueryBuilder();
150
-		$query->insert(self::RELATION_TABLE)
151
-			->values([
152
-				'objectid' => $query->createNamedParameter($objId),
153
-				'objecttype' => $query->createNamedParameter($objectType),
154
-				'systemtagid' => $query->createParameter('tagid'),
155
-			]);
156
-
157
-		foreach ($tagIds as $tagId) {
158
-			try {
159
-				$query->setParameter('tagid', $tagId);
160
-				$query->execute();
161
-			} catch (UniqueConstraintViolationException $e) {
162
-				// ignore existing relations
163
-			}
164
-		}
165
-
166
-		$this->dispatcher->dispatch(MapperEvent::EVENT_ASSIGN, new MapperEvent(
167
-			MapperEvent::EVENT_ASSIGN,
168
-			$objectType,
169
-			$objId,
170
-			$tagIds
171
-		));
172
-	}
173
-
174
-	/**
175
-	 * {@inheritdoc}
176
-	 */
177
-	public function unassignTags(string $objId, string $objectType, $tagIds) {
178
-		if (!\is_array($tagIds)) {
179
-			$tagIds = [$tagIds];
180
-		}
181
-
182
-		$this->assertTagsExist($tagIds);
183
-
184
-		$query = $this->connection->getQueryBuilder();
185
-		$query->delete(self::RELATION_TABLE)
186
-			->where($query->expr()->eq('objectid', $query->createParameter('objectid')))
187
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
188
-			->andWhere($query->expr()->in('systemtagid', $query->createParameter('tagids')))
189
-			->setParameter('objectid', $objId)
190
-			->setParameter('objecttype', $objectType)
191
-			->setParameter('tagids', $tagIds, IQueryBuilder::PARAM_INT_ARRAY)
192
-			->execute();
193
-
194
-		$this->dispatcher->dispatch(MapperEvent::EVENT_UNASSIGN, new MapperEvent(
195
-			MapperEvent::EVENT_UNASSIGN,
196
-			$objectType,
197
-			$objId,
198
-			$tagIds
199
-		));
200
-	}
201
-
202
-	/**
203
-	 * {@inheritdoc}
204
-	 */
205
-	public function haveTag($objIds, string $objectType, string $tagId, bool $all = true): bool {
206
-		$this->assertTagsExist([$tagId]);
207
-
208
-		if (!\is_array($objIds)) {
209
-			$objIds = [$objIds];
210
-		}
211
-
212
-		$query = $this->connection->getQueryBuilder();
213
-
214
-		if (!$all) {
215
-			// If we only need one entry, we make the query lighter, by not
216
-			// counting the elements
217
-			$query->select('*')
218
-				->setMaxResults(1);
219
-		} else {
220
-			$query->select($query->func()->count($query->expr()->literal(1)));
221
-		}
222
-
223
-		$query->from(self::RELATION_TABLE)
224
-			->where($query->expr()->in('objectid', $query->createParameter('objectids')))
225
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
226
-			->andWhere($query->expr()->eq('systemtagid', $query->createParameter('tagid')))
227
-			->setParameter('objectids', $objIds, IQueryBuilder::PARAM_STR_ARRAY)
228
-			->setParameter('tagid', $tagId)
229
-			->setParameter('objecttype', $objectType);
230
-
231
-		$result = $query->execute();
232
-		$row = $result->fetch(\PDO::FETCH_NUM);
233
-		$result->closeCursor();
234
-
235
-		if ($all) {
236
-			return ((int)$row[0] === \count($objIds));
237
-		}
238
-
239
-		return (bool) $row;
240
-	}
241
-
242
-	/**
243
-	 * Asserts that all the given tag ids exist.
244
-	 *
245
-	 * @param string[] $tagIds tag ids to check
246
-	 *
247
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
248
-	 */
249
-	private function assertTagsExist($tagIds) {
250
-		$tags = $this->tagManager->getTagsByIds($tagIds);
251
-		if (\count($tags) !== \count($tagIds)) {
252
-			// at least one tag missing, bail out
253
-			$foundTagIds = array_map(
254
-				function(ISystemTag $tag) {
255
-					return $tag->getId();
256
-				},
257
-				$tags
258
-			);
259
-			$missingTagIds = array_diff($tagIds, $foundTagIds);
260
-			throw new TagNotFoundException(
261
-				'Tags not found', 0, null, $missingTagIds
262
-			);
263
-		}
264
-	}
40
+    const RELATION_TABLE = 'systemtag_object_mapping';
41
+
42
+    /** @var ISystemTagManager */
43
+    protected $tagManager;
44
+
45
+    /** @var IDBConnection */
46
+    protected $connection;
47
+
48
+    /** @var EventDispatcherInterface */
49
+    protected $dispatcher;
50
+
51
+    /**
52
+     * Constructor.
53
+     *
54
+     * @param IDBConnection $connection database connection
55
+     * @param ISystemTagManager $tagManager system tag manager
56
+     * @param EventDispatcherInterface $dispatcher
57
+     */
58
+    public function __construct(IDBConnection $connection, ISystemTagManager $tagManager, EventDispatcherInterface $dispatcher) {
59
+        $this->connection = $connection;
60
+        $this->tagManager = $tagManager;
61
+        $this->dispatcher = $dispatcher;
62
+    }
63
+
64
+    /**
65
+     * {@inheritdoc}
66
+     */
67
+    public function getTagIdsForObjects($objIds, string $objectType): array {
68
+        if (!\is_array($objIds)) {
69
+            $objIds = [$objIds];
70
+        } else if (empty($objIds)) {
71
+            return [];
72
+        }
73
+
74
+        $query = $this->connection->getQueryBuilder();
75
+        $query->select(['systemtagid', 'objectid'])
76
+            ->from(self::RELATION_TABLE)
77
+            ->where($query->expr()->in('objectid', $query->createParameter('objectids')))
78
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
79
+            ->setParameter('objectids', $objIds, IQueryBuilder::PARAM_INT_ARRAY)
80
+            ->setParameter('objecttype', $objectType)
81
+            ->addOrderBy('objectid', 'ASC')
82
+            ->addOrderBy('systemtagid', 'ASC');
83
+
84
+        $mapping = [];
85
+        foreach ($objIds as $objId) {
86
+            $mapping[$objId] = [];
87
+        }
88
+
89
+        $result = $query->execute();
90
+        while ($row = $result->fetch()) {
91
+            $objectId = $row['objectid'];
92
+            $mapping[$objectId][] = $row['systemtagid'];
93
+        }
94
+
95
+        $result->closeCursor();
96
+
97
+        return $mapping;
98
+    }
99
+
100
+    /**
101
+     * {@inheritdoc}
102
+     */
103
+    public function getObjectIdsForTags($tagIds, string $objectType, int $limit = 0, string $offset = ''): array {
104
+        if (!\is_array($tagIds)) {
105
+            $tagIds = [$tagIds];
106
+        }
107
+
108
+        $this->assertTagsExist($tagIds);
109
+
110
+        $query = $this->connection->getQueryBuilder();
111
+        $query->selectDistinct('objectid')
112
+            ->from(self::RELATION_TABLE)
113
+            ->where($query->expr()->in('systemtagid', $query->createNamedParameter($tagIds, IQueryBuilder::PARAM_INT_ARRAY)))
114
+            ->andWhere($query->expr()->eq('objecttype', $query->createNamedParameter($objectType)));
115
+
116
+        if ($limit) {
117
+            if (\count($tagIds) !== 1) {
118
+                throw new \InvalidArgumentException('Limit is only allowed with a single tag');
119
+            }
120
+
121
+            $query->setMaxResults($limit)
122
+                ->orderBy('objectid', 'ASC');
123
+
124
+            if ($offset !== '') {
125
+                $query->andWhere($query->expr()->gt('objectid', $query->createNamedParameter($offset)));
126
+            }
127
+        }
128
+
129
+        $objectIds = [];
130
+
131
+        $result = $query->execute();
132
+        while ($row = $result->fetch()) {
133
+            $objectIds[] = $row['objectid'];
134
+        }
135
+
136
+        return $objectIds;
137
+    }
138
+
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function assignTags(string $objId, string $objectType, $tagIds) {
143
+        if (!\is_array($tagIds)) {
144
+            $tagIds = [$tagIds];
145
+        }
146
+
147
+        $this->assertTagsExist($tagIds);
148
+
149
+        $query = $this->connection->getQueryBuilder();
150
+        $query->insert(self::RELATION_TABLE)
151
+            ->values([
152
+                'objectid' => $query->createNamedParameter($objId),
153
+                'objecttype' => $query->createNamedParameter($objectType),
154
+                'systemtagid' => $query->createParameter('tagid'),
155
+            ]);
156
+
157
+        foreach ($tagIds as $tagId) {
158
+            try {
159
+                $query->setParameter('tagid', $tagId);
160
+                $query->execute();
161
+            } catch (UniqueConstraintViolationException $e) {
162
+                // ignore existing relations
163
+            }
164
+        }
165
+
166
+        $this->dispatcher->dispatch(MapperEvent::EVENT_ASSIGN, new MapperEvent(
167
+            MapperEvent::EVENT_ASSIGN,
168
+            $objectType,
169
+            $objId,
170
+            $tagIds
171
+        ));
172
+    }
173
+
174
+    /**
175
+     * {@inheritdoc}
176
+     */
177
+    public function unassignTags(string $objId, string $objectType, $tagIds) {
178
+        if (!\is_array($tagIds)) {
179
+            $tagIds = [$tagIds];
180
+        }
181
+
182
+        $this->assertTagsExist($tagIds);
183
+
184
+        $query = $this->connection->getQueryBuilder();
185
+        $query->delete(self::RELATION_TABLE)
186
+            ->where($query->expr()->eq('objectid', $query->createParameter('objectid')))
187
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
188
+            ->andWhere($query->expr()->in('systemtagid', $query->createParameter('tagids')))
189
+            ->setParameter('objectid', $objId)
190
+            ->setParameter('objecttype', $objectType)
191
+            ->setParameter('tagids', $tagIds, IQueryBuilder::PARAM_INT_ARRAY)
192
+            ->execute();
193
+
194
+        $this->dispatcher->dispatch(MapperEvent::EVENT_UNASSIGN, new MapperEvent(
195
+            MapperEvent::EVENT_UNASSIGN,
196
+            $objectType,
197
+            $objId,
198
+            $tagIds
199
+        ));
200
+    }
201
+
202
+    /**
203
+     * {@inheritdoc}
204
+     */
205
+    public function haveTag($objIds, string $objectType, string $tagId, bool $all = true): bool {
206
+        $this->assertTagsExist([$tagId]);
207
+
208
+        if (!\is_array($objIds)) {
209
+            $objIds = [$objIds];
210
+        }
211
+
212
+        $query = $this->connection->getQueryBuilder();
213
+
214
+        if (!$all) {
215
+            // If we only need one entry, we make the query lighter, by not
216
+            // counting the elements
217
+            $query->select('*')
218
+                ->setMaxResults(1);
219
+        } else {
220
+            $query->select($query->func()->count($query->expr()->literal(1)));
221
+        }
222
+
223
+        $query->from(self::RELATION_TABLE)
224
+            ->where($query->expr()->in('objectid', $query->createParameter('objectids')))
225
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
226
+            ->andWhere($query->expr()->eq('systemtagid', $query->createParameter('tagid')))
227
+            ->setParameter('objectids', $objIds, IQueryBuilder::PARAM_STR_ARRAY)
228
+            ->setParameter('tagid', $tagId)
229
+            ->setParameter('objecttype', $objectType);
230
+
231
+        $result = $query->execute();
232
+        $row = $result->fetch(\PDO::FETCH_NUM);
233
+        $result->closeCursor();
234
+
235
+        if ($all) {
236
+            return ((int)$row[0] === \count($objIds));
237
+        }
238
+
239
+        return (bool) $row;
240
+    }
241
+
242
+    /**
243
+     * Asserts that all the given tag ids exist.
244
+     *
245
+     * @param string[] $tagIds tag ids to check
246
+     *
247
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
248
+     */
249
+    private function assertTagsExist($tagIds) {
250
+        $tags = $this->tagManager->getTagsByIds($tagIds);
251
+        if (\count($tags) !== \count($tagIds)) {
252
+            // at least one tag missing, bail out
253
+            $foundTagIds = array_map(
254
+                function(ISystemTag $tag) {
255
+                    return $tag->getId();
256
+                },
257
+                $tags
258
+            );
259
+            $missingTagIds = array_diff($tagIds, $foundTagIds);
260
+            throw new TagNotFoundException(
261
+                'Tags not found', 0, null, $missingTagIds
262
+            );
263
+        }
264
+    }
265 265
 }
Please login to merge, or discard this patch.
lib/private/Comments/Manager.php 1 patch
Indentation   +1013 added lines, -1013 removed lines patch added patch discarded remove patch
@@ -41,1017 +41,1017 @@
 block discarded – undo
41 41
 
42 42
 class Manager implements ICommentsManager {
43 43
 
44
-	/** @var  IDBConnection */
45
-	protected $dbConn;
46
-
47
-	/** @var  ILogger */
48
-	protected $logger;
49
-
50
-	/** @var IConfig */
51
-	protected $config;
52
-
53
-	/** @var IComment[] */
54
-	protected $commentsCache = [];
55
-
56
-	/** @var  \Closure[] */
57
-	protected $eventHandlerClosures = [];
58
-
59
-	/** @var  ICommentsEventHandler[] */
60
-	protected $eventHandlers = [];
61
-
62
-	/** @var \Closure[] */
63
-	protected $displayNameResolvers = [];
64
-
65
-	/**
66
-	 * Manager constructor.
67
-	 *
68
-	 * @param IDBConnection $dbConn
69
-	 * @param ILogger $logger
70
-	 * @param IConfig $config
71
-	 */
72
-	public function __construct(
73
-		IDBConnection $dbConn,
74
-		ILogger $logger,
75
-		IConfig $config
76
-	) {
77
-		$this->dbConn = $dbConn;
78
-		$this->logger = $logger;
79
-		$this->config = $config;
80
-	}
81
-
82
-	/**
83
-	 * converts data base data into PHP native, proper types as defined by
84
-	 * IComment interface.
85
-	 *
86
-	 * @param array $data
87
-	 * @return array
88
-	 */
89
-	protected function normalizeDatabaseData(array $data) {
90
-		$data['id'] = (string)$data['id'];
91
-		$data['parent_id'] = (string)$data['parent_id'];
92
-		$data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
93
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
-		if (!is_null($data['latest_child_timestamp'])) {
95
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
-		}
97
-		$data['children_count'] = (int)$data['children_count'];
98
-		return $data;
99
-	}
100
-
101
-	/**
102
-	 * prepares a comment for an insert or update operation after making sure
103
-	 * all necessary fields have a value assigned.
104
-	 *
105
-	 * @param IComment $comment
106
-	 * @return IComment returns the same updated IComment instance as provided
107
-	 *                  by parameter for convenience
108
-	 * @throws \UnexpectedValueException
109
-	 */
110
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
-		if (!$comment->getActorType()
112
-			|| !$comment->getActorId()
113
-			|| !$comment->getObjectType()
114
-			|| !$comment->getObjectId()
115
-			|| !$comment->getVerb()
116
-		) {
117
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
-		}
119
-
120
-		if ($comment->getId() === '') {
121
-			$comment->setChildrenCount(0);
122
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
-			$comment->setLatestChildDateTime(null);
124
-		}
125
-
126
-		if (is_null($comment->getCreationDateTime())) {
127
-			$comment->setCreationDateTime(new \DateTime());
128
-		}
129
-
130
-		if ($comment->getParentId() !== '0') {
131
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
-		} else {
133
-			$comment->setTopmostParentId('0');
134
-		}
135
-
136
-		$this->cache($comment);
137
-
138
-		return $comment;
139
-	}
140
-
141
-	/**
142
-	 * returns the topmost parent id of a given comment identified by ID
143
-	 *
144
-	 * @param string $id
145
-	 * @return string
146
-	 * @throws NotFoundException
147
-	 */
148
-	protected function determineTopmostParentId($id) {
149
-		$comment = $this->get($id);
150
-		if ($comment->getParentId() === '0') {
151
-			return $comment->getId();
152
-		} else {
153
-			return $this->determineTopmostParentId($comment->getId());
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * updates child information of a comment
159
-	 *
160
-	 * @param string $id
161
-	 * @param \DateTime $cDateTime the date time of the most recent child
162
-	 * @throws NotFoundException
163
-	 */
164
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
-		$qb = $this->dbConn->getQueryBuilder();
166
-		$query = $qb->select($qb->func()->count('id'))
167
-			->from('comments')
168
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
-			->setParameter('id', $id);
170
-
171
-		$resultStatement = $query->execute();
172
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
-		$resultStatement->closeCursor();
174
-		$children = (int)$data[0];
175
-
176
-		$comment = $this->get($id);
177
-		$comment->setChildrenCount($children);
178
-		$comment->setLatestChildDateTime($cDateTime);
179
-		$this->save($comment);
180
-	}
181
-
182
-	/**
183
-	 * Tests whether actor or object type and id parameters are acceptable.
184
-	 * Throws exception if not.
185
-	 *
186
-	 * @param string $role
187
-	 * @param string $type
188
-	 * @param string $id
189
-	 * @throws \InvalidArgumentException
190
-	 */
191
-	protected function checkRoleParameters($role, $type, $id) {
192
-		if (
193
-			!is_string($type) || empty($type)
194
-			|| !is_string($id) || empty($id)
195
-		) {
196
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * run-time caches a comment
202
-	 *
203
-	 * @param IComment $comment
204
-	 */
205
-	protected function cache(IComment $comment) {
206
-		$id = $comment->getId();
207
-		if (empty($id)) {
208
-			return;
209
-		}
210
-		$this->commentsCache[(string)$id] = $comment;
211
-	}
212
-
213
-	/**
214
-	 * removes an entry from the comments run time cache
215
-	 *
216
-	 * @param mixed $id the comment's id
217
-	 */
218
-	protected function uncache($id) {
219
-		$id = (string)$id;
220
-		if (isset($this->commentsCache[$id])) {
221
-			unset($this->commentsCache[$id]);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * returns a comment instance
227
-	 *
228
-	 * @param string $id the ID of the comment
229
-	 * @return IComment
230
-	 * @throws NotFoundException
231
-	 * @throws \InvalidArgumentException
232
-	 * @since 9.0.0
233
-	 */
234
-	public function get($id) {
235
-		if ((int)$id === 0) {
236
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
-		}
238
-
239
-		if (isset($this->commentsCache[$id])) {
240
-			return $this->commentsCache[$id];
241
-		}
242
-
243
-		$qb = $this->dbConn->getQueryBuilder();
244
-		$resultStatement = $qb->select('*')
245
-			->from('comments')
246
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
-			->execute();
249
-
250
-		$data = $resultStatement->fetch();
251
-		$resultStatement->closeCursor();
252
-		if (!$data) {
253
-			throw new NotFoundException();
254
-		}
255
-
256
-		$comment = new Comment($this->normalizeDatabaseData($data));
257
-		$this->cache($comment);
258
-		return $comment;
259
-	}
260
-
261
-	/**
262
-	 * returns the comment specified by the id and all it's child comments.
263
-	 * At this point of time, we do only support one level depth.
264
-	 *
265
-	 * @param string $id
266
-	 * @param int $limit max number of entries to return, 0 returns all
267
-	 * @param int $offset the start entry
268
-	 * @return array
269
-	 * @since 9.0.0
270
-	 *
271
-	 * The return array looks like this
272
-	 * [
273
-	 *   'comment' => IComment, // root comment
274
-	 *   'replies' =>
275
-	 *   [
276
-	 *     0 =>
277
-	 *     [
278
-	 *       'comment' => IComment,
279
-	 *       'replies' => []
280
-	 *     ]
281
-	 *     1 =>
282
-	 *     [
283
-	 *       'comment' => IComment,
284
-	 *       'replies'=> []
285
-	 *     ],
286
-	 *     …
287
-	 *   ]
288
-	 * ]
289
-	 */
290
-	public function getTree($id, $limit = 0, $offset = 0) {
291
-		$tree = [];
292
-		$tree['comment'] = $this->get($id);
293
-		$tree['replies'] = [];
294
-
295
-		$qb = $this->dbConn->getQueryBuilder();
296
-		$query = $qb->select('*')
297
-			->from('comments')
298
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
-			->orderBy('creation_timestamp', 'DESC')
300
-			->setParameter('id', $id);
301
-
302
-		if ($limit > 0) {
303
-			$query->setMaxResults($limit);
304
-		}
305
-		if ($offset > 0) {
306
-			$query->setFirstResult($offset);
307
-		}
308
-
309
-		$resultStatement = $query->execute();
310
-		while ($data = $resultStatement->fetch()) {
311
-			$comment = new Comment($this->normalizeDatabaseData($data));
312
-			$this->cache($comment);
313
-			$tree['replies'][] = [
314
-				'comment' => $comment,
315
-				'replies' => []
316
-			];
317
-		}
318
-		$resultStatement->closeCursor();
319
-
320
-		return $tree;
321
-	}
322
-
323
-	/**
324
-	 * returns comments for a specific object (e.g. a file).
325
-	 *
326
-	 * The sort order is always newest to oldest.
327
-	 *
328
-	 * @param string $objectType the object type, e.g. 'files'
329
-	 * @param string $objectId the id of the object
330
-	 * @param int $limit optional, number of maximum comments to be returned. if
331
-	 * not specified, all comments are returned.
332
-	 * @param int $offset optional, starting point
333
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
-	 * that may be returned
335
-	 * @return IComment[]
336
-	 * @since 9.0.0
337
-	 */
338
-	public function getForObject(
339
-		$objectType,
340
-		$objectId,
341
-		$limit = 0,
342
-		$offset = 0,
343
-		\DateTime $notOlderThan = null
344
-	) {
345
-		$comments = [];
346
-
347
-		$qb = $this->dbConn->getQueryBuilder();
348
-		$query = $qb->select('*')
349
-			->from('comments')
350
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
-			->orderBy('creation_timestamp', 'DESC')
353
-			->setParameter('type', $objectType)
354
-			->setParameter('id', $objectId);
355
-
356
-		if ($limit > 0) {
357
-			$query->setMaxResults($limit);
358
-		}
359
-		if ($offset > 0) {
360
-			$query->setFirstResult($offset);
361
-		}
362
-		if (!is_null($notOlderThan)) {
363
-			$query
364
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
-		}
367
-
368
-		$resultStatement = $query->execute();
369
-		while ($data = $resultStatement->fetch()) {
370
-			$comment = new Comment($this->normalizeDatabaseData($data));
371
-			$this->cache($comment);
372
-			$comments[] = $comment;
373
-		}
374
-		$resultStatement->closeCursor();
375
-
376
-		return $comments;
377
-	}
378
-
379
-	/**
380
-	 * @param string $objectType the object type, e.g. 'files'
381
-	 * @param string $objectId the id of the object
382
-	 * @param int $lastKnownCommentId the last known comment (will be used as offset)
383
-	 * @param string $sortDirection direction of the comments (`asc` or `desc`)
384
-	 * @param int $limit optional, number of maximum comments to be returned. if
385
-	 * set to 0, all comments are returned.
386
-	 * @return IComment[]
387
-	 * @return array
388
-	 */
389
-	public function getForObjectSince(
390
-		string $objectType,
391
-		string $objectId,
392
-		int $lastKnownCommentId,
393
-		string $sortDirection = 'asc',
394
-		int $limit = 30
395
-	): array {
396
-		$comments = [];
397
-
398
-		$query = $this->dbConn->getQueryBuilder();
399
-		$query->select('*')
400
-			->from('comments')
401
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
402
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
403
-			->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
404
-			->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
405
-
406
-		if ($limit > 0) {
407
-			$query->setMaxResults($limit);
408
-		}
409
-
410
-		$lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
411
-			$objectType,
412
-			$objectId,
413
-			$lastKnownCommentId
414
-		) : null;
415
-		if ($lastKnownComment instanceof IComment) {
416
-			$lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
417
-			if ($sortDirection === 'desc') {
418
-				$query->andWhere(
419
-					$query->expr()->orX(
420
-						$query->expr()->lt(
421
-							'creation_timestamp',
422
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
423
-							IQueryBuilder::PARAM_DATE
424
-						),
425
-						$query->expr()->andX(
426
-							$query->expr()->eq(
427
-								'creation_timestamp',
428
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
429
-								IQueryBuilder::PARAM_DATE
430
-							),
431
-							$query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
432
-						)
433
-					)
434
-				);
435
-			} else {
436
-				$query->andWhere(
437
-					$query->expr()->orX(
438
-						$query->expr()->gt(
439
-							'creation_timestamp',
440
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
441
-							IQueryBuilder::PARAM_DATE
442
-						),
443
-						$query->expr()->andX(
444
-							$query->expr()->eq(
445
-								'creation_timestamp',
446
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
447
-								IQueryBuilder::PARAM_DATE
448
-							),
449
-							$query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
450
-						)
451
-					)
452
-				);
453
-			}
454
-		}
455
-
456
-		$resultStatement = $query->execute();
457
-		while ($data = $resultStatement->fetch()) {
458
-			$comment = new Comment($this->normalizeDatabaseData($data));
459
-			$this->cache($comment);
460
-			$comments[] = $comment;
461
-		}
462
-		$resultStatement->closeCursor();
463
-
464
-		return $comments;
465
-	}
466
-
467
-	/**
468
-	 * @param string $objectType the object type, e.g. 'files'
469
-	 * @param string $objectId the id of the object
470
-	 * @param int $id the comment to look for
471
-	 * @return Comment|null
472
-	 */
473
-	protected function getLastKnownComment(string $objectType,
474
-										   string $objectId,
475
-										   int $id) {
476
-		$query = $this->dbConn->getQueryBuilder();
477
-		$query->select('*')
478
-			->from('comments')
479
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
480
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
481
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
482
-
483
-		$result = $query->execute();
484
-		$row = $result->fetch();
485
-		$result->closeCursor();
486
-
487
-		if ($row) {
488
-			$comment = new Comment($this->normalizeDatabaseData($row));
489
-			$this->cache($comment);
490
-			return $comment;
491
-		}
492
-
493
-		return null;
494
-	}
495
-
496
-	/**
497
-	 * Search for comments with a given content
498
-	 *
499
-	 * @param string $search content to search for
500
-	 * @param string $objectType Limit the search by object type
501
-	 * @param string $objectId Limit the search by object id
502
-	 * @param string $verb Limit the verb of the comment
503
-	 * @param int $offset
504
-	 * @param int $limit
505
-	 * @return IComment[]
506
-	 */
507
-	public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
508
-		$query = $this->dbConn->getQueryBuilder();
509
-
510
-		$query->select('*')
511
-			->from('comments')
512
-			->where($query->expr()->iLike('message', $query->createNamedParameter(
513
-				'%' . $this->dbConn->escapeLikeParameter($search). '%'
514
-			)))
515
-			->orderBy('creation_timestamp', 'DESC')
516
-			->addOrderBy('id', 'DESC')
517
-			->setMaxResults($limit);
518
-
519
-		if ($objectType !== '') {
520
-			$query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
521
-		}
522
-		if ($objectId !== '') {
523
-			$query->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
524
-		}
525
-		if ($verb !== '') {
526
-			$query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
527
-		}
528
-		if ($offset !== 0) {
529
-			$query->setFirstResult($offset);
530
-		}
531
-
532
-		$comments = [];
533
-		$result = $query->execute();
534
-		while ($data = $result->fetch()) {
535
-			$comment = new Comment($this->normalizeDatabaseData($data));
536
-			$this->cache($comment);
537
-			$comments[] = $comment;
538
-		}
539
-		$result->closeCursor();
540
-
541
-		return $comments;
542
-	}
543
-
544
-	/**
545
-	 * @param $objectType string the object type, e.g. 'files'
546
-	 * @param $objectId string the id of the object
547
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
548
-	 * that may be returned
549
-	 * @param string $verb Limit the verb of the comment - Added in 14.0.0
550
-	 * @return Int
551
-	 * @since 9.0.0
552
-	 */
553
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
554
-		$qb = $this->dbConn->getQueryBuilder();
555
-		$query = $qb->select($qb->func()->count('id'))
556
-			->from('comments')
557
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
558
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
559
-			->setParameter('type', $objectType)
560
-			->setParameter('id', $objectId);
561
-
562
-		if (!is_null($notOlderThan)) {
563
-			$query
564
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
565
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
566
-		}
567
-
568
-		if ($verb !== '') {
569
-			$query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
570
-		}
571
-
572
-		$resultStatement = $query->execute();
573
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
574
-		$resultStatement->closeCursor();
575
-		return (int)$data[0];
576
-	}
577
-
578
-	/**
579
-	 * Get the number of unread comments for all files in a folder
580
-	 *
581
-	 * @param int $folderId
582
-	 * @param IUser $user
583
-	 * @return array [$fileId => $unreadCount]
584
-	 */
585
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
586
-		$qb = $this->dbConn->getQueryBuilder();
587
-		$query = $qb->select('f.fileid')
588
-			->addSelect($qb->func()->count('c.id', 'num_ids'))
589
-			->from('comments', 'c')
590
-			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
591
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
592
-				$qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
593
-			))
594
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
595
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
596
-				$qb->expr()->eq('m.object_id', 'c.object_id'),
597
-				$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
598
-			))
599
-			->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
600
-			->andWhere($qb->expr()->orX(
601
-				$qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
602
-				$qb->expr()->isNull('marker_datetime')
603
-			))
604
-			->groupBy('f.fileid');
605
-
606
-		$resultStatement = $query->execute();
607
-
608
-		$results = [];
609
-		while ($row = $resultStatement->fetch()) {
610
-			$results[$row['fileid']] = (int) $row['num_ids'];
611
-		}
612
-		$resultStatement->closeCursor();
613
-		return $results;
614
-	}
615
-
616
-	/**
617
-	 * creates a new comment and returns it. At this point of time, it is not
618
-	 * saved in the used data storage. Use save() after setting other fields
619
-	 * of the comment (e.g. message or verb).
620
-	 *
621
-	 * @param string $actorType the actor type (e.g. 'users')
622
-	 * @param string $actorId a user id
623
-	 * @param string $objectType the object type the comment is attached to
624
-	 * @param string $objectId the object id the comment is attached to
625
-	 * @return IComment
626
-	 * @since 9.0.0
627
-	 */
628
-	public function create($actorType, $actorId, $objectType, $objectId) {
629
-		$comment = new Comment();
630
-		$comment
631
-			->setActor($actorType, $actorId)
632
-			->setObject($objectType, $objectId);
633
-		return $comment;
634
-	}
635
-
636
-	/**
637
-	 * permanently deletes the comment specified by the ID
638
-	 *
639
-	 * When the comment has child comments, their parent ID will be changed to
640
-	 * the parent ID of the item that is to be deleted.
641
-	 *
642
-	 * @param string $id
643
-	 * @return bool
644
-	 * @throws \InvalidArgumentException
645
-	 * @since 9.0.0
646
-	 */
647
-	public function delete($id) {
648
-		if (!is_string($id)) {
649
-			throw new \InvalidArgumentException('Parameter must be string');
650
-		}
651
-
652
-		try {
653
-			$comment = $this->get($id);
654
-		} catch (\Exception $e) {
655
-			// Ignore exceptions, we just don't fire a hook then
656
-			$comment = null;
657
-		}
658
-
659
-		$qb = $this->dbConn->getQueryBuilder();
660
-		$query = $qb->delete('comments')
661
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
662
-			->setParameter('id', $id);
663
-
664
-		try {
665
-			$affectedRows = $query->execute();
666
-			$this->uncache($id);
667
-		} catch (DriverException $e) {
668
-			$this->logger->logException($e, ['app' => 'core_comments']);
669
-			return false;
670
-		}
671
-
672
-		if ($affectedRows > 0 && $comment instanceof IComment) {
673
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
674
-		}
675
-
676
-		return ($affectedRows > 0);
677
-	}
678
-
679
-	/**
680
-	 * saves the comment permanently
681
-	 *
682
-	 * if the supplied comment has an empty ID, a new entry comment will be
683
-	 * saved and the instance updated with the new ID.
684
-	 *
685
-	 * Otherwise, an existing comment will be updated.
686
-	 *
687
-	 * Throws NotFoundException when a comment that is to be updated does not
688
-	 * exist anymore at this point of time.
689
-	 *
690
-	 * @param IComment $comment
691
-	 * @return bool
692
-	 * @throws NotFoundException
693
-	 * @since 9.0.0
694
-	 */
695
-	public function save(IComment $comment) {
696
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
697
-			$result = $this->insert($comment);
698
-		} else {
699
-			$result = $this->update($comment);
700
-		}
701
-
702
-		if ($result && !!$comment->getParentId()) {
703
-			$this->updateChildrenInformation(
704
-				$comment->getParentId(),
705
-				$comment->getCreationDateTime()
706
-			);
707
-			$this->cache($comment);
708
-		}
709
-
710
-		return $result;
711
-	}
712
-
713
-	/**
714
-	 * inserts the provided comment in the database
715
-	 *
716
-	 * @param IComment $comment
717
-	 * @return bool
718
-	 */
719
-	protected function insert(IComment &$comment) {
720
-		$qb = $this->dbConn->getQueryBuilder();
721
-		$affectedRows = $qb
722
-			->insert('comments')
723
-			->values([
724
-				'parent_id' => $qb->createNamedParameter($comment->getParentId()),
725
-				'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
726
-				'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
727
-				'actor_type' => $qb->createNamedParameter($comment->getActorType()),
728
-				'actor_id' => $qb->createNamedParameter($comment->getActorId()),
729
-				'message' => $qb->createNamedParameter($comment->getMessage()),
730
-				'verb' => $qb->createNamedParameter($comment->getVerb()),
731
-				'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
732
-				'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
733
-				'object_type' => $qb->createNamedParameter($comment->getObjectType()),
734
-				'object_id' => $qb->createNamedParameter($comment->getObjectId()),
735
-			])
736
-			->execute();
737
-
738
-		if ($affectedRows > 0) {
739
-			$comment->setId((string)$qb->getLastInsertId());
740
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
741
-		}
742
-
743
-		return $affectedRows > 0;
744
-	}
745
-
746
-	/**
747
-	 * updates a Comment data row
748
-	 *
749
-	 * @param IComment $comment
750
-	 * @return bool
751
-	 * @throws NotFoundException
752
-	 */
753
-	protected function update(IComment $comment) {
754
-		// for properly working preUpdate Events we need the old comments as is
755
-		// in the DB and overcome caching. Also avoid that outdated information stays.
756
-		$this->uncache($comment->getId());
757
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
758
-		$this->uncache($comment->getId());
759
-
760
-		$qb = $this->dbConn->getQueryBuilder();
761
-		$affectedRows = $qb
762
-			->update('comments')
763
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
764
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
765
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
766
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
767
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
768
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
769
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
770
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
771
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
772
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
773
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
774
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
775
-			->setParameter('id', $comment->getId())
776
-			->execute();
777
-
778
-		if ($affectedRows === 0) {
779
-			throw new NotFoundException('Comment to update does ceased to exist');
780
-		}
781
-
782
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
783
-
784
-		return $affectedRows > 0;
785
-	}
786
-
787
-	/**
788
-	 * removes references to specific actor (e.g. on user delete) of a comment.
789
-	 * The comment itself must not get lost/deleted.
790
-	 *
791
-	 * @param string $actorType the actor type (e.g. 'users')
792
-	 * @param string $actorId a user id
793
-	 * @return boolean
794
-	 * @since 9.0.0
795
-	 */
796
-	public function deleteReferencesOfActor($actorType, $actorId) {
797
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
798
-
799
-		$qb = $this->dbConn->getQueryBuilder();
800
-		$affectedRows = $qb
801
-			->update('comments')
802
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
803
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
804
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
805
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
806
-			->setParameter('type', $actorType)
807
-			->setParameter('id', $actorId)
808
-			->execute();
809
-
810
-		$this->commentsCache = [];
811
-
812
-		return is_int($affectedRows);
813
-	}
814
-
815
-	/**
816
-	 * deletes all comments made of a specific object (e.g. on file delete)
817
-	 *
818
-	 * @param string $objectType the object type (e.g. 'files')
819
-	 * @param string $objectId e.g. the file id
820
-	 * @return boolean
821
-	 * @since 9.0.0
822
-	 */
823
-	public function deleteCommentsAtObject($objectType, $objectId) {
824
-		$this->checkRoleParameters('Object', $objectType, $objectId);
825
-
826
-		$qb = $this->dbConn->getQueryBuilder();
827
-		$affectedRows = $qb
828
-			->delete('comments')
829
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
830
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
831
-			->setParameter('type', $objectType)
832
-			->setParameter('id', $objectId)
833
-			->execute();
834
-
835
-		$this->commentsCache = [];
836
-
837
-		return is_int($affectedRows);
838
-	}
839
-
840
-	/**
841
-	 * deletes the read markers for the specified user
842
-	 *
843
-	 * @param \OCP\IUser $user
844
-	 * @return bool
845
-	 * @since 9.0.0
846
-	 */
847
-	public function deleteReadMarksFromUser(IUser $user) {
848
-		$qb = $this->dbConn->getQueryBuilder();
849
-		$query = $qb->delete('comments_read_markers')
850
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
851
-			->setParameter('user_id', $user->getUID());
852
-
853
-		try {
854
-			$affectedRows = $query->execute();
855
-		} catch (DriverException $e) {
856
-			$this->logger->logException($e, ['app' => 'core_comments']);
857
-			return false;
858
-		}
859
-		return ($affectedRows > 0);
860
-	}
861
-
862
-	/**
863
-	 * sets the read marker for a given file to the specified date for the
864
-	 * provided user
865
-	 *
866
-	 * @param string $objectType
867
-	 * @param string $objectId
868
-	 * @param \DateTime $dateTime
869
-	 * @param IUser $user
870
-	 * @since 9.0.0
871
-	 * @suppress SqlInjectionChecker
872
-	 */
873
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
874
-		$this->checkRoleParameters('Object', $objectType, $objectId);
875
-
876
-		$qb = $this->dbConn->getQueryBuilder();
877
-		$values = [
878
-			'user_id' => $qb->createNamedParameter($user->getUID()),
879
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
880
-			'object_type' => $qb->createNamedParameter($objectType),
881
-			'object_id' => $qb->createNamedParameter($objectId),
882
-		];
883
-
884
-		// Strategy: try to update, if this does not return affected rows, do an insert.
885
-		$affectedRows = $qb
886
-			->update('comments_read_markers')
887
-			->set('user_id', $values['user_id'])
888
-			->set('marker_datetime', $values['marker_datetime'])
889
-			->set('object_type', $values['object_type'])
890
-			->set('object_id', $values['object_id'])
891
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
892
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
893
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
894
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
895
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
896
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
897
-			->execute();
898
-
899
-		if ($affectedRows > 0) {
900
-			return;
901
-		}
902
-
903
-		$qb->insert('comments_read_markers')
904
-			->values($values)
905
-			->execute();
906
-	}
907
-
908
-	/**
909
-	 * returns the read marker for a given file to the specified date for the
910
-	 * provided user. It returns null, when the marker is not present, i.e.
911
-	 * no comments were marked as read.
912
-	 *
913
-	 * @param string $objectType
914
-	 * @param string $objectId
915
-	 * @param IUser $user
916
-	 * @return \DateTime|null
917
-	 * @since 9.0.0
918
-	 */
919
-	public function getReadMark($objectType, $objectId, IUser $user) {
920
-		$qb = $this->dbConn->getQueryBuilder();
921
-		$resultStatement = $qb->select('marker_datetime')
922
-			->from('comments_read_markers')
923
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
924
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
925
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
926
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
927
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
928
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
929
-			->execute();
930
-
931
-		$data = $resultStatement->fetch();
932
-		$resultStatement->closeCursor();
933
-		if (!$data || is_null($data['marker_datetime'])) {
934
-			return null;
935
-		}
936
-
937
-		return new \DateTime($data['marker_datetime']);
938
-	}
939
-
940
-	/**
941
-	 * deletes the read markers on the specified object
942
-	 *
943
-	 * @param string $objectType
944
-	 * @param string $objectId
945
-	 * @return bool
946
-	 * @since 9.0.0
947
-	 */
948
-	public function deleteReadMarksOnObject($objectType, $objectId) {
949
-		$this->checkRoleParameters('Object', $objectType, $objectId);
950
-
951
-		$qb = $this->dbConn->getQueryBuilder();
952
-		$query = $qb->delete('comments_read_markers')
953
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
954
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
955
-			->setParameter('object_type', $objectType)
956
-			->setParameter('object_id', $objectId);
957
-
958
-		try {
959
-			$affectedRows = $query->execute();
960
-		} catch (DriverException $e) {
961
-			$this->logger->logException($e, ['app' => 'core_comments']);
962
-			return false;
963
-		}
964
-		return ($affectedRows > 0);
965
-	}
966
-
967
-	/**
968
-	 * registers an Entity to the manager, so event notifications can be send
969
-	 * to consumers of the comments infrastructure
970
-	 *
971
-	 * @param \Closure $closure
972
-	 */
973
-	public function registerEventHandler(\Closure $closure) {
974
-		$this->eventHandlerClosures[] = $closure;
975
-		$this->eventHandlers = [];
976
-	}
977
-
978
-	/**
979
-	 * registers a method that resolves an ID to a display name for a given type
980
-	 *
981
-	 * @param string $type
982
-	 * @param \Closure $closure
983
-	 * @throws \OutOfBoundsException
984
-	 * @since 11.0.0
985
-	 *
986
-	 * Only one resolver shall be registered per type. Otherwise a
987
-	 * \OutOfBoundsException has to thrown.
988
-	 */
989
-	public function registerDisplayNameResolver($type, \Closure $closure) {
990
-		if (!is_string($type)) {
991
-			throw new \InvalidArgumentException('String expected.');
992
-		}
993
-		if (isset($this->displayNameResolvers[$type])) {
994
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
995
-		}
996
-		$this->displayNameResolvers[$type] = $closure;
997
-	}
998
-
999
-	/**
1000
-	 * resolves a given ID of a given Type to a display name.
1001
-	 *
1002
-	 * @param string $type
1003
-	 * @param string $id
1004
-	 * @return string
1005
-	 * @throws \OutOfBoundsException
1006
-	 * @since 11.0.0
1007
-	 *
1008
-	 * If a provided type was not registered, an \OutOfBoundsException shall
1009
-	 * be thrown. It is upon the resolver discretion what to return of the
1010
-	 * provided ID is unknown. It must be ensured that a string is returned.
1011
-	 */
1012
-	public function resolveDisplayName($type, $id) {
1013
-		if (!is_string($type)) {
1014
-			throw new \InvalidArgumentException('String expected.');
1015
-		}
1016
-		if (!isset($this->displayNameResolvers[$type])) {
1017
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1018
-		}
1019
-		return (string)$this->displayNameResolvers[$type]($id);
1020
-	}
1021
-
1022
-	/**
1023
-	 * returns valid, registered entities
1024
-	 *
1025
-	 * @return \OCP\Comments\ICommentsEventHandler[]
1026
-	 */
1027
-	private function getEventHandlers() {
1028
-		if (!empty($this->eventHandlers)) {
1029
-			return $this->eventHandlers;
1030
-		}
1031
-
1032
-		$this->eventHandlers = [];
1033
-		foreach ($this->eventHandlerClosures as $name => $closure) {
1034
-			$entity = $closure();
1035
-			if (!($entity instanceof ICommentsEventHandler)) {
1036
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1037
-			}
1038
-			$this->eventHandlers[$name] = $entity;
1039
-		}
1040
-
1041
-		return $this->eventHandlers;
1042
-	}
1043
-
1044
-	/**
1045
-	 * sends notifications to the registered entities
1046
-	 *
1047
-	 * @param $eventType
1048
-	 * @param IComment $comment
1049
-	 */
1050
-	private function sendEvent($eventType, IComment $comment) {
1051
-		$entities = $this->getEventHandlers();
1052
-		$event = new CommentsEvent($eventType, $comment);
1053
-		foreach ($entities as $entity) {
1054
-			$entity->handle($event);
1055
-		}
1056
-	}
44
+    /** @var  IDBConnection */
45
+    protected $dbConn;
46
+
47
+    /** @var  ILogger */
48
+    protected $logger;
49
+
50
+    /** @var IConfig */
51
+    protected $config;
52
+
53
+    /** @var IComment[] */
54
+    protected $commentsCache = [];
55
+
56
+    /** @var  \Closure[] */
57
+    protected $eventHandlerClosures = [];
58
+
59
+    /** @var  ICommentsEventHandler[] */
60
+    protected $eventHandlers = [];
61
+
62
+    /** @var \Closure[] */
63
+    protected $displayNameResolvers = [];
64
+
65
+    /**
66
+     * Manager constructor.
67
+     *
68
+     * @param IDBConnection $dbConn
69
+     * @param ILogger $logger
70
+     * @param IConfig $config
71
+     */
72
+    public function __construct(
73
+        IDBConnection $dbConn,
74
+        ILogger $logger,
75
+        IConfig $config
76
+    ) {
77
+        $this->dbConn = $dbConn;
78
+        $this->logger = $logger;
79
+        $this->config = $config;
80
+    }
81
+
82
+    /**
83
+     * converts data base data into PHP native, proper types as defined by
84
+     * IComment interface.
85
+     *
86
+     * @param array $data
87
+     * @return array
88
+     */
89
+    protected function normalizeDatabaseData(array $data) {
90
+        $data['id'] = (string)$data['id'];
91
+        $data['parent_id'] = (string)$data['parent_id'];
92
+        $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
93
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
+        if (!is_null($data['latest_child_timestamp'])) {
95
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
+        }
97
+        $data['children_count'] = (int)$data['children_count'];
98
+        return $data;
99
+    }
100
+
101
+    /**
102
+     * prepares a comment for an insert or update operation after making sure
103
+     * all necessary fields have a value assigned.
104
+     *
105
+     * @param IComment $comment
106
+     * @return IComment returns the same updated IComment instance as provided
107
+     *                  by parameter for convenience
108
+     * @throws \UnexpectedValueException
109
+     */
110
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
+        if (!$comment->getActorType()
112
+            || !$comment->getActorId()
113
+            || !$comment->getObjectType()
114
+            || !$comment->getObjectId()
115
+            || !$comment->getVerb()
116
+        ) {
117
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
+        }
119
+
120
+        if ($comment->getId() === '') {
121
+            $comment->setChildrenCount(0);
122
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
+            $comment->setLatestChildDateTime(null);
124
+        }
125
+
126
+        if (is_null($comment->getCreationDateTime())) {
127
+            $comment->setCreationDateTime(new \DateTime());
128
+        }
129
+
130
+        if ($comment->getParentId() !== '0') {
131
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
+        } else {
133
+            $comment->setTopmostParentId('0');
134
+        }
135
+
136
+        $this->cache($comment);
137
+
138
+        return $comment;
139
+    }
140
+
141
+    /**
142
+     * returns the topmost parent id of a given comment identified by ID
143
+     *
144
+     * @param string $id
145
+     * @return string
146
+     * @throws NotFoundException
147
+     */
148
+    protected function determineTopmostParentId($id) {
149
+        $comment = $this->get($id);
150
+        if ($comment->getParentId() === '0') {
151
+            return $comment->getId();
152
+        } else {
153
+            return $this->determineTopmostParentId($comment->getId());
154
+        }
155
+    }
156
+
157
+    /**
158
+     * updates child information of a comment
159
+     *
160
+     * @param string $id
161
+     * @param \DateTime $cDateTime the date time of the most recent child
162
+     * @throws NotFoundException
163
+     */
164
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
+        $qb = $this->dbConn->getQueryBuilder();
166
+        $query = $qb->select($qb->func()->count('id'))
167
+            ->from('comments')
168
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
+            ->setParameter('id', $id);
170
+
171
+        $resultStatement = $query->execute();
172
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
+        $resultStatement->closeCursor();
174
+        $children = (int)$data[0];
175
+
176
+        $comment = $this->get($id);
177
+        $comment->setChildrenCount($children);
178
+        $comment->setLatestChildDateTime($cDateTime);
179
+        $this->save($comment);
180
+    }
181
+
182
+    /**
183
+     * Tests whether actor or object type and id parameters are acceptable.
184
+     * Throws exception if not.
185
+     *
186
+     * @param string $role
187
+     * @param string $type
188
+     * @param string $id
189
+     * @throws \InvalidArgumentException
190
+     */
191
+    protected function checkRoleParameters($role, $type, $id) {
192
+        if (
193
+            !is_string($type) || empty($type)
194
+            || !is_string($id) || empty($id)
195
+        ) {
196
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
+        }
198
+    }
199
+
200
+    /**
201
+     * run-time caches a comment
202
+     *
203
+     * @param IComment $comment
204
+     */
205
+    protected function cache(IComment $comment) {
206
+        $id = $comment->getId();
207
+        if (empty($id)) {
208
+            return;
209
+        }
210
+        $this->commentsCache[(string)$id] = $comment;
211
+    }
212
+
213
+    /**
214
+     * removes an entry from the comments run time cache
215
+     *
216
+     * @param mixed $id the comment's id
217
+     */
218
+    protected function uncache($id) {
219
+        $id = (string)$id;
220
+        if (isset($this->commentsCache[$id])) {
221
+            unset($this->commentsCache[$id]);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * returns a comment instance
227
+     *
228
+     * @param string $id the ID of the comment
229
+     * @return IComment
230
+     * @throws NotFoundException
231
+     * @throws \InvalidArgumentException
232
+     * @since 9.0.0
233
+     */
234
+    public function get($id) {
235
+        if ((int)$id === 0) {
236
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
+        }
238
+
239
+        if (isset($this->commentsCache[$id])) {
240
+            return $this->commentsCache[$id];
241
+        }
242
+
243
+        $qb = $this->dbConn->getQueryBuilder();
244
+        $resultStatement = $qb->select('*')
245
+            ->from('comments')
246
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
+            ->execute();
249
+
250
+        $data = $resultStatement->fetch();
251
+        $resultStatement->closeCursor();
252
+        if (!$data) {
253
+            throw new NotFoundException();
254
+        }
255
+
256
+        $comment = new Comment($this->normalizeDatabaseData($data));
257
+        $this->cache($comment);
258
+        return $comment;
259
+    }
260
+
261
+    /**
262
+     * returns the comment specified by the id and all it's child comments.
263
+     * At this point of time, we do only support one level depth.
264
+     *
265
+     * @param string $id
266
+     * @param int $limit max number of entries to return, 0 returns all
267
+     * @param int $offset the start entry
268
+     * @return array
269
+     * @since 9.0.0
270
+     *
271
+     * The return array looks like this
272
+     * [
273
+     *   'comment' => IComment, // root comment
274
+     *   'replies' =>
275
+     *   [
276
+     *     0 =>
277
+     *     [
278
+     *       'comment' => IComment,
279
+     *       'replies' => []
280
+     *     ]
281
+     *     1 =>
282
+     *     [
283
+     *       'comment' => IComment,
284
+     *       'replies'=> []
285
+     *     ],
286
+     *     …
287
+     *   ]
288
+     * ]
289
+     */
290
+    public function getTree($id, $limit = 0, $offset = 0) {
291
+        $tree = [];
292
+        $tree['comment'] = $this->get($id);
293
+        $tree['replies'] = [];
294
+
295
+        $qb = $this->dbConn->getQueryBuilder();
296
+        $query = $qb->select('*')
297
+            ->from('comments')
298
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
+            ->orderBy('creation_timestamp', 'DESC')
300
+            ->setParameter('id', $id);
301
+
302
+        if ($limit > 0) {
303
+            $query->setMaxResults($limit);
304
+        }
305
+        if ($offset > 0) {
306
+            $query->setFirstResult($offset);
307
+        }
308
+
309
+        $resultStatement = $query->execute();
310
+        while ($data = $resultStatement->fetch()) {
311
+            $comment = new Comment($this->normalizeDatabaseData($data));
312
+            $this->cache($comment);
313
+            $tree['replies'][] = [
314
+                'comment' => $comment,
315
+                'replies' => []
316
+            ];
317
+        }
318
+        $resultStatement->closeCursor();
319
+
320
+        return $tree;
321
+    }
322
+
323
+    /**
324
+     * returns comments for a specific object (e.g. a file).
325
+     *
326
+     * The sort order is always newest to oldest.
327
+     *
328
+     * @param string $objectType the object type, e.g. 'files'
329
+     * @param string $objectId the id of the object
330
+     * @param int $limit optional, number of maximum comments to be returned. if
331
+     * not specified, all comments are returned.
332
+     * @param int $offset optional, starting point
333
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
+     * that may be returned
335
+     * @return IComment[]
336
+     * @since 9.0.0
337
+     */
338
+    public function getForObject(
339
+        $objectType,
340
+        $objectId,
341
+        $limit = 0,
342
+        $offset = 0,
343
+        \DateTime $notOlderThan = null
344
+    ) {
345
+        $comments = [];
346
+
347
+        $qb = $this->dbConn->getQueryBuilder();
348
+        $query = $qb->select('*')
349
+            ->from('comments')
350
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
+            ->orderBy('creation_timestamp', 'DESC')
353
+            ->setParameter('type', $objectType)
354
+            ->setParameter('id', $objectId);
355
+
356
+        if ($limit > 0) {
357
+            $query->setMaxResults($limit);
358
+        }
359
+        if ($offset > 0) {
360
+            $query->setFirstResult($offset);
361
+        }
362
+        if (!is_null($notOlderThan)) {
363
+            $query
364
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
+        }
367
+
368
+        $resultStatement = $query->execute();
369
+        while ($data = $resultStatement->fetch()) {
370
+            $comment = new Comment($this->normalizeDatabaseData($data));
371
+            $this->cache($comment);
372
+            $comments[] = $comment;
373
+        }
374
+        $resultStatement->closeCursor();
375
+
376
+        return $comments;
377
+    }
378
+
379
+    /**
380
+     * @param string $objectType the object type, e.g. 'files'
381
+     * @param string $objectId the id of the object
382
+     * @param int $lastKnownCommentId the last known comment (will be used as offset)
383
+     * @param string $sortDirection direction of the comments (`asc` or `desc`)
384
+     * @param int $limit optional, number of maximum comments to be returned. if
385
+     * set to 0, all comments are returned.
386
+     * @return IComment[]
387
+     * @return array
388
+     */
389
+    public function getForObjectSince(
390
+        string $objectType,
391
+        string $objectId,
392
+        int $lastKnownCommentId,
393
+        string $sortDirection = 'asc',
394
+        int $limit = 30
395
+    ): array {
396
+        $comments = [];
397
+
398
+        $query = $this->dbConn->getQueryBuilder();
399
+        $query->select('*')
400
+            ->from('comments')
401
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
402
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
403
+            ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
404
+            ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
405
+
406
+        if ($limit > 0) {
407
+            $query->setMaxResults($limit);
408
+        }
409
+
410
+        $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
411
+            $objectType,
412
+            $objectId,
413
+            $lastKnownCommentId
414
+        ) : null;
415
+        if ($lastKnownComment instanceof IComment) {
416
+            $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
417
+            if ($sortDirection === 'desc') {
418
+                $query->andWhere(
419
+                    $query->expr()->orX(
420
+                        $query->expr()->lt(
421
+                            'creation_timestamp',
422
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
423
+                            IQueryBuilder::PARAM_DATE
424
+                        ),
425
+                        $query->expr()->andX(
426
+                            $query->expr()->eq(
427
+                                'creation_timestamp',
428
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
429
+                                IQueryBuilder::PARAM_DATE
430
+                            ),
431
+                            $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
432
+                        )
433
+                    )
434
+                );
435
+            } else {
436
+                $query->andWhere(
437
+                    $query->expr()->orX(
438
+                        $query->expr()->gt(
439
+                            'creation_timestamp',
440
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
441
+                            IQueryBuilder::PARAM_DATE
442
+                        ),
443
+                        $query->expr()->andX(
444
+                            $query->expr()->eq(
445
+                                'creation_timestamp',
446
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
447
+                                IQueryBuilder::PARAM_DATE
448
+                            ),
449
+                            $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
450
+                        )
451
+                    )
452
+                );
453
+            }
454
+        }
455
+
456
+        $resultStatement = $query->execute();
457
+        while ($data = $resultStatement->fetch()) {
458
+            $comment = new Comment($this->normalizeDatabaseData($data));
459
+            $this->cache($comment);
460
+            $comments[] = $comment;
461
+        }
462
+        $resultStatement->closeCursor();
463
+
464
+        return $comments;
465
+    }
466
+
467
+    /**
468
+     * @param string $objectType the object type, e.g. 'files'
469
+     * @param string $objectId the id of the object
470
+     * @param int $id the comment to look for
471
+     * @return Comment|null
472
+     */
473
+    protected function getLastKnownComment(string $objectType,
474
+                                            string $objectId,
475
+                                            int $id) {
476
+        $query = $this->dbConn->getQueryBuilder();
477
+        $query->select('*')
478
+            ->from('comments')
479
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
480
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
481
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
482
+
483
+        $result = $query->execute();
484
+        $row = $result->fetch();
485
+        $result->closeCursor();
486
+
487
+        if ($row) {
488
+            $comment = new Comment($this->normalizeDatabaseData($row));
489
+            $this->cache($comment);
490
+            return $comment;
491
+        }
492
+
493
+        return null;
494
+    }
495
+
496
+    /**
497
+     * Search for comments with a given content
498
+     *
499
+     * @param string $search content to search for
500
+     * @param string $objectType Limit the search by object type
501
+     * @param string $objectId Limit the search by object id
502
+     * @param string $verb Limit the verb of the comment
503
+     * @param int $offset
504
+     * @param int $limit
505
+     * @return IComment[]
506
+     */
507
+    public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
508
+        $query = $this->dbConn->getQueryBuilder();
509
+
510
+        $query->select('*')
511
+            ->from('comments')
512
+            ->where($query->expr()->iLike('message', $query->createNamedParameter(
513
+                '%' . $this->dbConn->escapeLikeParameter($search). '%'
514
+            )))
515
+            ->orderBy('creation_timestamp', 'DESC')
516
+            ->addOrderBy('id', 'DESC')
517
+            ->setMaxResults($limit);
518
+
519
+        if ($objectType !== '') {
520
+            $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
521
+        }
522
+        if ($objectId !== '') {
523
+            $query->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
524
+        }
525
+        if ($verb !== '') {
526
+            $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
527
+        }
528
+        if ($offset !== 0) {
529
+            $query->setFirstResult($offset);
530
+        }
531
+
532
+        $comments = [];
533
+        $result = $query->execute();
534
+        while ($data = $result->fetch()) {
535
+            $comment = new Comment($this->normalizeDatabaseData($data));
536
+            $this->cache($comment);
537
+            $comments[] = $comment;
538
+        }
539
+        $result->closeCursor();
540
+
541
+        return $comments;
542
+    }
543
+
544
+    /**
545
+     * @param $objectType string the object type, e.g. 'files'
546
+     * @param $objectId string the id of the object
547
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
548
+     * that may be returned
549
+     * @param string $verb Limit the verb of the comment - Added in 14.0.0
550
+     * @return Int
551
+     * @since 9.0.0
552
+     */
553
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
554
+        $qb = $this->dbConn->getQueryBuilder();
555
+        $query = $qb->select($qb->func()->count('id'))
556
+            ->from('comments')
557
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
558
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
559
+            ->setParameter('type', $objectType)
560
+            ->setParameter('id', $objectId);
561
+
562
+        if (!is_null($notOlderThan)) {
563
+            $query
564
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
565
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
566
+        }
567
+
568
+        if ($verb !== '') {
569
+            $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
570
+        }
571
+
572
+        $resultStatement = $query->execute();
573
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
574
+        $resultStatement->closeCursor();
575
+        return (int)$data[0];
576
+    }
577
+
578
+    /**
579
+     * Get the number of unread comments for all files in a folder
580
+     *
581
+     * @param int $folderId
582
+     * @param IUser $user
583
+     * @return array [$fileId => $unreadCount]
584
+     */
585
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
586
+        $qb = $this->dbConn->getQueryBuilder();
587
+        $query = $qb->select('f.fileid')
588
+            ->addSelect($qb->func()->count('c.id', 'num_ids'))
589
+            ->from('comments', 'c')
590
+            ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
591
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
592
+                $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
593
+            ))
594
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
595
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
596
+                $qb->expr()->eq('m.object_id', 'c.object_id'),
597
+                $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
598
+            ))
599
+            ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
600
+            ->andWhere($qb->expr()->orX(
601
+                $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
602
+                $qb->expr()->isNull('marker_datetime')
603
+            ))
604
+            ->groupBy('f.fileid');
605
+
606
+        $resultStatement = $query->execute();
607
+
608
+        $results = [];
609
+        while ($row = $resultStatement->fetch()) {
610
+            $results[$row['fileid']] = (int) $row['num_ids'];
611
+        }
612
+        $resultStatement->closeCursor();
613
+        return $results;
614
+    }
615
+
616
+    /**
617
+     * creates a new comment and returns it. At this point of time, it is not
618
+     * saved in the used data storage. Use save() after setting other fields
619
+     * of the comment (e.g. message or verb).
620
+     *
621
+     * @param string $actorType the actor type (e.g. 'users')
622
+     * @param string $actorId a user id
623
+     * @param string $objectType the object type the comment is attached to
624
+     * @param string $objectId the object id the comment is attached to
625
+     * @return IComment
626
+     * @since 9.0.0
627
+     */
628
+    public function create($actorType, $actorId, $objectType, $objectId) {
629
+        $comment = new Comment();
630
+        $comment
631
+            ->setActor($actorType, $actorId)
632
+            ->setObject($objectType, $objectId);
633
+        return $comment;
634
+    }
635
+
636
+    /**
637
+     * permanently deletes the comment specified by the ID
638
+     *
639
+     * When the comment has child comments, their parent ID will be changed to
640
+     * the parent ID of the item that is to be deleted.
641
+     *
642
+     * @param string $id
643
+     * @return bool
644
+     * @throws \InvalidArgumentException
645
+     * @since 9.0.0
646
+     */
647
+    public function delete($id) {
648
+        if (!is_string($id)) {
649
+            throw new \InvalidArgumentException('Parameter must be string');
650
+        }
651
+
652
+        try {
653
+            $comment = $this->get($id);
654
+        } catch (\Exception $e) {
655
+            // Ignore exceptions, we just don't fire a hook then
656
+            $comment = null;
657
+        }
658
+
659
+        $qb = $this->dbConn->getQueryBuilder();
660
+        $query = $qb->delete('comments')
661
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
662
+            ->setParameter('id', $id);
663
+
664
+        try {
665
+            $affectedRows = $query->execute();
666
+            $this->uncache($id);
667
+        } catch (DriverException $e) {
668
+            $this->logger->logException($e, ['app' => 'core_comments']);
669
+            return false;
670
+        }
671
+
672
+        if ($affectedRows > 0 && $comment instanceof IComment) {
673
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
674
+        }
675
+
676
+        return ($affectedRows > 0);
677
+    }
678
+
679
+    /**
680
+     * saves the comment permanently
681
+     *
682
+     * if the supplied comment has an empty ID, a new entry comment will be
683
+     * saved and the instance updated with the new ID.
684
+     *
685
+     * Otherwise, an existing comment will be updated.
686
+     *
687
+     * Throws NotFoundException when a comment that is to be updated does not
688
+     * exist anymore at this point of time.
689
+     *
690
+     * @param IComment $comment
691
+     * @return bool
692
+     * @throws NotFoundException
693
+     * @since 9.0.0
694
+     */
695
+    public function save(IComment $comment) {
696
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
697
+            $result = $this->insert($comment);
698
+        } else {
699
+            $result = $this->update($comment);
700
+        }
701
+
702
+        if ($result && !!$comment->getParentId()) {
703
+            $this->updateChildrenInformation(
704
+                $comment->getParentId(),
705
+                $comment->getCreationDateTime()
706
+            );
707
+            $this->cache($comment);
708
+        }
709
+
710
+        return $result;
711
+    }
712
+
713
+    /**
714
+     * inserts the provided comment in the database
715
+     *
716
+     * @param IComment $comment
717
+     * @return bool
718
+     */
719
+    protected function insert(IComment &$comment) {
720
+        $qb = $this->dbConn->getQueryBuilder();
721
+        $affectedRows = $qb
722
+            ->insert('comments')
723
+            ->values([
724
+                'parent_id' => $qb->createNamedParameter($comment->getParentId()),
725
+                'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
726
+                'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
727
+                'actor_type' => $qb->createNamedParameter($comment->getActorType()),
728
+                'actor_id' => $qb->createNamedParameter($comment->getActorId()),
729
+                'message' => $qb->createNamedParameter($comment->getMessage()),
730
+                'verb' => $qb->createNamedParameter($comment->getVerb()),
731
+                'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
732
+                'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
733
+                'object_type' => $qb->createNamedParameter($comment->getObjectType()),
734
+                'object_id' => $qb->createNamedParameter($comment->getObjectId()),
735
+            ])
736
+            ->execute();
737
+
738
+        if ($affectedRows > 0) {
739
+            $comment->setId((string)$qb->getLastInsertId());
740
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
741
+        }
742
+
743
+        return $affectedRows > 0;
744
+    }
745
+
746
+    /**
747
+     * updates a Comment data row
748
+     *
749
+     * @param IComment $comment
750
+     * @return bool
751
+     * @throws NotFoundException
752
+     */
753
+    protected function update(IComment $comment) {
754
+        // for properly working preUpdate Events we need the old comments as is
755
+        // in the DB and overcome caching. Also avoid that outdated information stays.
756
+        $this->uncache($comment->getId());
757
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
758
+        $this->uncache($comment->getId());
759
+
760
+        $qb = $this->dbConn->getQueryBuilder();
761
+        $affectedRows = $qb
762
+            ->update('comments')
763
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
764
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
765
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
766
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
767
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
768
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
769
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
770
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
771
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
772
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
773
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
774
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
775
+            ->setParameter('id', $comment->getId())
776
+            ->execute();
777
+
778
+        if ($affectedRows === 0) {
779
+            throw new NotFoundException('Comment to update does ceased to exist');
780
+        }
781
+
782
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
783
+
784
+        return $affectedRows > 0;
785
+    }
786
+
787
+    /**
788
+     * removes references to specific actor (e.g. on user delete) of a comment.
789
+     * The comment itself must not get lost/deleted.
790
+     *
791
+     * @param string $actorType the actor type (e.g. 'users')
792
+     * @param string $actorId a user id
793
+     * @return boolean
794
+     * @since 9.0.0
795
+     */
796
+    public function deleteReferencesOfActor($actorType, $actorId) {
797
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
798
+
799
+        $qb = $this->dbConn->getQueryBuilder();
800
+        $affectedRows = $qb
801
+            ->update('comments')
802
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
803
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
804
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
805
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
806
+            ->setParameter('type', $actorType)
807
+            ->setParameter('id', $actorId)
808
+            ->execute();
809
+
810
+        $this->commentsCache = [];
811
+
812
+        return is_int($affectedRows);
813
+    }
814
+
815
+    /**
816
+     * deletes all comments made of a specific object (e.g. on file delete)
817
+     *
818
+     * @param string $objectType the object type (e.g. 'files')
819
+     * @param string $objectId e.g. the file id
820
+     * @return boolean
821
+     * @since 9.0.0
822
+     */
823
+    public function deleteCommentsAtObject($objectType, $objectId) {
824
+        $this->checkRoleParameters('Object', $objectType, $objectId);
825
+
826
+        $qb = $this->dbConn->getQueryBuilder();
827
+        $affectedRows = $qb
828
+            ->delete('comments')
829
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
830
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
831
+            ->setParameter('type', $objectType)
832
+            ->setParameter('id', $objectId)
833
+            ->execute();
834
+
835
+        $this->commentsCache = [];
836
+
837
+        return is_int($affectedRows);
838
+    }
839
+
840
+    /**
841
+     * deletes the read markers for the specified user
842
+     *
843
+     * @param \OCP\IUser $user
844
+     * @return bool
845
+     * @since 9.0.0
846
+     */
847
+    public function deleteReadMarksFromUser(IUser $user) {
848
+        $qb = $this->dbConn->getQueryBuilder();
849
+        $query = $qb->delete('comments_read_markers')
850
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
851
+            ->setParameter('user_id', $user->getUID());
852
+
853
+        try {
854
+            $affectedRows = $query->execute();
855
+        } catch (DriverException $e) {
856
+            $this->logger->logException($e, ['app' => 'core_comments']);
857
+            return false;
858
+        }
859
+        return ($affectedRows > 0);
860
+    }
861
+
862
+    /**
863
+     * sets the read marker for a given file to the specified date for the
864
+     * provided user
865
+     *
866
+     * @param string $objectType
867
+     * @param string $objectId
868
+     * @param \DateTime $dateTime
869
+     * @param IUser $user
870
+     * @since 9.0.0
871
+     * @suppress SqlInjectionChecker
872
+     */
873
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
874
+        $this->checkRoleParameters('Object', $objectType, $objectId);
875
+
876
+        $qb = $this->dbConn->getQueryBuilder();
877
+        $values = [
878
+            'user_id' => $qb->createNamedParameter($user->getUID()),
879
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
880
+            'object_type' => $qb->createNamedParameter($objectType),
881
+            'object_id' => $qb->createNamedParameter($objectId),
882
+        ];
883
+
884
+        // Strategy: try to update, if this does not return affected rows, do an insert.
885
+        $affectedRows = $qb
886
+            ->update('comments_read_markers')
887
+            ->set('user_id', $values['user_id'])
888
+            ->set('marker_datetime', $values['marker_datetime'])
889
+            ->set('object_type', $values['object_type'])
890
+            ->set('object_id', $values['object_id'])
891
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
892
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
893
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
894
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
895
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
896
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
897
+            ->execute();
898
+
899
+        if ($affectedRows > 0) {
900
+            return;
901
+        }
902
+
903
+        $qb->insert('comments_read_markers')
904
+            ->values($values)
905
+            ->execute();
906
+    }
907
+
908
+    /**
909
+     * returns the read marker for a given file to the specified date for the
910
+     * provided user. It returns null, when the marker is not present, i.e.
911
+     * no comments were marked as read.
912
+     *
913
+     * @param string $objectType
914
+     * @param string $objectId
915
+     * @param IUser $user
916
+     * @return \DateTime|null
917
+     * @since 9.0.0
918
+     */
919
+    public function getReadMark($objectType, $objectId, IUser $user) {
920
+        $qb = $this->dbConn->getQueryBuilder();
921
+        $resultStatement = $qb->select('marker_datetime')
922
+            ->from('comments_read_markers')
923
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
924
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
925
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
926
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
927
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
928
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
929
+            ->execute();
930
+
931
+        $data = $resultStatement->fetch();
932
+        $resultStatement->closeCursor();
933
+        if (!$data || is_null($data['marker_datetime'])) {
934
+            return null;
935
+        }
936
+
937
+        return new \DateTime($data['marker_datetime']);
938
+    }
939
+
940
+    /**
941
+     * deletes the read markers on the specified object
942
+     *
943
+     * @param string $objectType
944
+     * @param string $objectId
945
+     * @return bool
946
+     * @since 9.0.0
947
+     */
948
+    public function deleteReadMarksOnObject($objectType, $objectId) {
949
+        $this->checkRoleParameters('Object', $objectType, $objectId);
950
+
951
+        $qb = $this->dbConn->getQueryBuilder();
952
+        $query = $qb->delete('comments_read_markers')
953
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
954
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
955
+            ->setParameter('object_type', $objectType)
956
+            ->setParameter('object_id', $objectId);
957
+
958
+        try {
959
+            $affectedRows = $query->execute();
960
+        } catch (DriverException $e) {
961
+            $this->logger->logException($e, ['app' => 'core_comments']);
962
+            return false;
963
+        }
964
+        return ($affectedRows > 0);
965
+    }
966
+
967
+    /**
968
+     * registers an Entity to the manager, so event notifications can be send
969
+     * to consumers of the comments infrastructure
970
+     *
971
+     * @param \Closure $closure
972
+     */
973
+    public function registerEventHandler(\Closure $closure) {
974
+        $this->eventHandlerClosures[] = $closure;
975
+        $this->eventHandlers = [];
976
+    }
977
+
978
+    /**
979
+     * registers a method that resolves an ID to a display name for a given type
980
+     *
981
+     * @param string $type
982
+     * @param \Closure $closure
983
+     * @throws \OutOfBoundsException
984
+     * @since 11.0.0
985
+     *
986
+     * Only one resolver shall be registered per type. Otherwise a
987
+     * \OutOfBoundsException has to thrown.
988
+     */
989
+    public function registerDisplayNameResolver($type, \Closure $closure) {
990
+        if (!is_string($type)) {
991
+            throw new \InvalidArgumentException('String expected.');
992
+        }
993
+        if (isset($this->displayNameResolvers[$type])) {
994
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
995
+        }
996
+        $this->displayNameResolvers[$type] = $closure;
997
+    }
998
+
999
+    /**
1000
+     * resolves a given ID of a given Type to a display name.
1001
+     *
1002
+     * @param string $type
1003
+     * @param string $id
1004
+     * @return string
1005
+     * @throws \OutOfBoundsException
1006
+     * @since 11.0.0
1007
+     *
1008
+     * If a provided type was not registered, an \OutOfBoundsException shall
1009
+     * be thrown. It is upon the resolver discretion what to return of the
1010
+     * provided ID is unknown. It must be ensured that a string is returned.
1011
+     */
1012
+    public function resolveDisplayName($type, $id) {
1013
+        if (!is_string($type)) {
1014
+            throw new \InvalidArgumentException('String expected.');
1015
+        }
1016
+        if (!isset($this->displayNameResolvers[$type])) {
1017
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1018
+        }
1019
+        return (string)$this->displayNameResolvers[$type]($id);
1020
+    }
1021
+
1022
+    /**
1023
+     * returns valid, registered entities
1024
+     *
1025
+     * @return \OCP\Comments\ICommentsEventHandler[]
1026
+     */
1027
+    private function getEventHandlers() {
1028
+        if (!empty($this->eventHandlers)) {
1029
+            return $this->eventHandlers;
1030
+        }
1031
+
1032
+        $this->eventHandlers = [];
1033
+        foreach ($this->eventHandlerClosures as $name => $closure) {
1034
+            $entity = $closure();
1035
+            if (!($entity instanceof ICommentsEventHandler)) {
1036
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1037
+            }
1038
+            $this->eventHandlers[$name] = $entity;
1039
+        }
1040
+
1041
+        return $this->eventHandlers;
1042
+    }
1043
+
1044
+    /**
1045
+     * sends notifications to the registered entities
1046
+     *
1047
+     * @param $eventType
1048
+     * @param IComment $comment
1049
+     */
1050
+    private function sendEvent($eventType, IComment $comment) {
1051
+        $entities = $this->getEventHandlers();
1052
+        $event = new CommentsEvent($eventType, $comment);
1053
+        foreach ($entities as $entity) {
1054
+            $entity->handle($event);
1055
+        }
1056
+    }
1057 1057
 }
Please login to merge, or discard this patch.