Passed
Push — master ( b6209d...0acd4b )
by Joas
15:45 queued 14s
created
lib/private/AppFramework/Http/RequestId.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -27,26 +27,26 @@
 block discarded – undo
27 27
 use OCP\Security\ISecureRandom;
28 28
 
29 29
 class RequestId implements IRequestId {
30
-	protected ISecureRandom $secureRandom;
31
-	protected string $requestId;
30
+    protected ISecureRandom $secureRandom;
31
+    protected string $requestId;
32 32
 
33
-	public function __construct(string $uniqueId,
34
-								ISecureRandom $secureRandom) {
35
-		$this->requestId = $uniqueId;
36
-		$this->secureRandom = $secureRandom;
37
-	}
33
+    public function __construct(string $uniqueId,
34
+                                ISecureRandom $secureRandom) {
35
+        $this->requestId = $uniqueId;
36
+        $this->secureRandom = $secureRandom;
37
+    }
38 38
 
39
-	/**
40
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
41
-	 * If `mod_unique_id` is installed this value will be taken.
42
-	 * @return string
43
-	 */
44
-	public function getId(): string {
45
-		if (empty($this->requestId)) {
46
-			$validChars = ISecureRandom::CHAR_ALPHANUMERIC;
47
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
48
-		}
39
+    /**
40
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
41
+     * If `mod_unique_id` is installed this value will be taken.
42
+     * @return string
43
+     */
44
+    public function getId(): string {
45
+        if (empty($this->requestId)) {
46
+            $validChars = ISecureRandom::CHAR_ALPHANUMERIC;
47
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
48
+        }
49 49
 
50
-		return $this->requestId;
51
-	}
50
+        return $this->requestId;
51
+    }
52 52
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Request.php 1 patch
Indentation   +848 added lines, -848 removed lines patch added patch discarded remove patch
@@ -63,852 +63,852 @@
 block discarded – undo
63 63
  * @property mixed[] server
64 64
  */
65 65
 class Request implements \ArrayAccess, \Countable, IRequest {
66
-	public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
67
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
68
-	public const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
69
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
70
-	public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
71
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
72
-	public const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
73
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
74
-	public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
75
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
76
-	public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
77
-	public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
78
-	public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
79
-
80
-	protected $inputStream;
81
-	protected $content;
82
-	protected $items = [];
83
-	protected $allowedKeys = [
84
-		'get',
85
-		'post',
86
-		'files',
87
-		'server',
88
-		'env',
89
-		'cookies',
90
-		'urlParams',
91
-		'parameters',
92
-		'method',
93
-		'requesttoken',
94
-	];
95
-	/** @var RequestId */
96
-	protected $requestId;
97
-	/** @var IConfig */
98
-	protected $config;
99
-	/** @var ICrypto */
100
-	protected $crypto;
101
-	/** @var CsrfTokenManager|null */
102
-	protected $csrfTokenManager;
103
-
104
-	/** @var bool */
105
-	protected $contentDecoded = false;
106
-
107
-	/**
108
-	 * @param array $vars An associative array with the following optional values:
109
-	 *        - array 'urlParams' the parameters which were matched from the URL
110
-	 *        - array 'get' the $_GET array
111
-	 *        - array|string 'post' the $_POST array or JSON string
112
-	 *        - array 'files' the $_FILES array
113
-	 *        - array 'server' the $_SERVER array
114
-	 *        - array 'env' the $_ENV array
115
-	 *        - array 'cookies' the $_COOKIE array
116
-	 *        - string 'method' the request method (GET, POST etc)
117
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
118
-	 * @param IRequestId $requestId
119
-	 * @param IConfig $config
120
-	 * @param CsrfTokenManager|null $csrfTokenManager
121
-	 * @param string $stream
122
-	 * @see https://www.php.net/manual/en/reserved.variables.php
123
-	 */
124
-	public function __construct(array $vars,
125
-								IRequestId $requestId,
126
-								IConfig $config,
127
-								CsrfTokenManager $csrfTokenManager = null,
128
-								string $stream = 'php://input') {
129
-		$this->inputStream = $stream;
130
-		$this->items['params'] = [];
131
-		$this->requestId = $requestId;
132
-		$this->config = $config;
133
-		$this->csrfTokenManager = $csrfTokenManager;
134
-
135
-		if (!array_key_exists('method', $vars)) {
136
-			$vars['method'] = 'GET';
137
-		}
138
-
139
-		foreach ($this->allowedKeys as $name) {
140
-			$this->items[$name] = isset($vars[$name])
141
-				? $vars[$name]
142
-				: [];
143
-		}
144
-
145
-		$this->items['parameters'] = array_merge(
146
-			$this->items['get'],
147
-			$this->items['post'],
148
-			$this->items['urlParams'],
149
-			$this->items['params']
150
-		);
151
-	}
152
-	/**
153
-	 * @param array $parameters
154
-	 */
155
-	public function setUrlParameters(array $parameters) {
156
-		$this->items['urlParams'] = $parameters;
157
-		$this->items['parameters'] = array_merge(
158
-			$this->items['parameters'],
159
-			$this->items['urlParams']
160
-		);
161
-	}
162
-
163
-	/**
164
-	 * Countable method
165
-	 * @return int
166
-	 */
167
-	public function count(): int {
168
-		return \count($this->items['parameters']);
169
-	}
170
-
171
-	/**
172
-	 * ArrayAccess methods
173
-	 *
174
-	 * Gives access to the combined GET, POST and urlParams arrays
175
-	 *
176
-	 * Examples:
177
-	 *
178
-	 * $var = $request['myvar'];
179
-	 *
180
-	 * or
181
-	 *
182
-	 * if(!isset($request['myvar']) {
183
-	 * 	// Do something
184
-	 * }
185
-	 *
186
-	 * $request['myvar'] = 'something'; // This throws an exception.
187
-	 *
188
-	 * @param string $offset The key to lookup
189
-	 * @return boolean
190
-	 */
191
-	public function offsetExists($offset): bool {
192
-		return isset($this->items['parameters'][$offset]);
193
-	}
194
-
195
-	/**
196
-	 * @see offsetExists
197
-	 * @param string $offset
198
-	 * @return mixed
199
-	 */
200
-	#[\ReturnTypeWillChange]
201
-	public function offsetGet($offset) {
202
-		return isset($this->items['parameters'][$offset])
203
-			? $this->items['parameters'][$offset]
204
-			: null;
205
-	}
206
-
207
-	/**
208
-	 * @see offsetExists
209
-	 * @param string $offset
210
-	 * @param mixed $value
211
-	 */
212
-	public function offsetSet($offset, $value): void {
213
-		throw new \RuntimeException('You cannot change the contents of the request object');
214
-	}
215
-
216
-	/**
217
-	 * @see offsetExists
218
-	 * @param string $offset
219
-	 */
220
-	public function offsetUnset($offset): void {
221
-		throw new \RuntimeException('You cannot change the contents of the request object');
222
-	}
223
-
224
-	/**
225
-	 * Magic property accessors
226
-	 * @param string $name
227
-	 * @param mixed $value
228
-	 */
229
-	public function __set($name, $value) {
230
-		throw new \RuntimeException('You cannot change the contents of the request object');
231
-	}
232
-
233
-	/**
234
-	 * Access request variables by method and name.
235
-	 * Examples:
236
-	 *
237
-	 * $request->post['myvar']; // Only look for POST variables
238
-	 * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
239
-	 * Looks in the combined GET, POST and urlParams array.
240
-	 *
241
-	 * If you access e.g. ->post but the current HTTP request method
242
-	 * is GET a \LogicException will be thrown.
243
-	 *
244
-	 * @param string $name The key to look for.
245
-	 * @throws \LogicException
246
-	 * @return mixed|null
247
-	 */
248
-	public function __get($name) {
249
-		switch ($name) {
250
-			case 'put':
251
-			case 'patch':
252
-			case 'get':
253
-			case 'post':
254
-				if ($this->method !== strtoupper($name)) {
255
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
256
-				}
257
-				return $this->getContent();
258
-			case 'files':
259
-			case 'server':
260
-			case 'env':
261
-			case 'cookies':
262
-			case 'urlParams':
263
-			case 'method':
264
-				return isset($this->items[$name])
265
-					? $this->items[$name]
266
-					: null;
267
-			case 'parameters':
268
-			case 'params':
269
-				return $this->getContent();
270
-			default:
271
-				return isset($this[$name])
272
-					? $this[$name]
273
-					: null;
274
-		}
275
-	}
276
-
277
-	/**
278
-	 * @param string $name
279
-	 * @return bool
280
-	 */
281
-	public function __isset($name) {
282
-		if (\in_array($name, $this->allowedKeys, true)) {
283
-			return true;
284
-		}
285
-		return isset($this->items['parameters'][$name]);
286
-	}
287
-
288
-	/**
289
-	 * @param string $id
290
-	 */
291
-	public function __unset($id) {
292
-		throw new \RuntimeException('You cannot change the contents of the request object');
293
-	}
294
-
295
-	/**
296
-	 * Returns the value for a specific http header.
297
-	 *
298
-	 * This method returns an empty string if the header did not exist.
299
-	 *
300
-	 * @param string $name
301
-	 * @return string
302
-	 */
303
-	public function getHeader(string $name): string {
304
-		$name = strtoupper(str_replace('-', '_', $name));
305
-		if (isset($this->server['HTTP_' . $name])) {
306
-			return $this->server['HTTP_' . $name];
307
-		}
308
-
309
-		// There's a few headers that seem to end up in the top-level
310
-		// server array.
311
-		switch ($name) {
312
-			case 'CONTENT_TYPE':
313
-			case 'CONTENT_LENGTH':
314
-			case 'REMOTE_ADDR':
315
-				if (isset($this->server[$name])) {
316
-					return $this->server[$name];
317
-				}
318
-				break;
319
-		}
320
-
321
-		return '';
322
-	}
323
-
324
-	/**
325
-	 * Lets you access post and get parameters by the index
326
-	 * In case of json requests the encoded json body is accessed
327
-	 *
328
-	 * @param string $key the key which you want to access in the URL Parameter
329
-	 *                     placeholder, $_POST or $_GET array.
330
-	 *                     The priority how they're returned is the following:
331
-	 *                     1. URL parameters
332
-	 *                     2. POST parameters
333
-	 *                     3. GET parameters
334
-	 * @param mixed $default If the key is not found, this value will be returned
335
-	 * @return mixed the content of the array
336
-	 */
337
-	public function getParam(string $key, $default = null) {
338
-		return isset($this->parameters[$key])
339
-			? $this->parameters[$key]
340
-			: $default;
341
-	}
342
-
343
-	/**
344
-	 * Returns all params that were received, be it from the request
345
-	 * (as GET or POST) or throuh the URL by the route
346
-	 * @return array the array with all parameters
347
-	 */
348
-	public function getParams(): array {
349
-		return is_array($this->parameters) ? $this->parameters : [];
350
-	}
351
-
352
-	/**
353
-	 * Returns the method of the request
354
-	 * @return string the method of the request (POST, GET, etc)
355
-	 */
356
-	public function getMethod(): string {
357
-		return $this->method;
358
-	}
359
-
360
-	/**
361
-	 * Shortcut for accessing an uploaded file through the $_FILES array
362
-	 * @param string $key the key that will be taken from the $_FILES array
363
-	 * @return array the file in the $_FILES element
364
-	 */
365
-	public function getUploadedFile(string $key) {
366
-		return isset($this->files[$key]) ? $this->files[$key] : null;
367
-	}
368
-
369
-	/**
370
-	 * Shortcut for getting env variables
371
-	 * @param string $key the key that will be taken from the $_ENV array
372
-	 * @return array the value in the $_ENV element
373
-	 */
374
-	public function getEnv(string $key) {
375
-		return isset($this->env[$key]) ? $this->env[$key] : null;
376
-	}
377
-
378
-	/**
379
-	 * Shortcut for getting cookie variables
380
-	 * @param string $key the key that will be taken from the $_COOKIE array
381
-	 * @return string the value in the $_COOKIE element
382
-	 */
383
-	public function getCookie(string $key) {
384
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
385
-	}
386
-
387
-	/**
388
-	 * Returns the request body content.
389
-	 *
390
-	 * If the HTTP request method is PUT and the body
391
-	 * not application/x-www-form-urlencoded or application/json a stream
392
-	 * resource is returned, otherwise an array.
393
-	 *
394
-	 * @return array|string|resource The request body content or a resource to read the body stream.
395
-	 *
396
-	 * @throws \LogicException
397
-	 */
398
-	protected function getContent() {
399
-		// If the content can't be parsed into an array then return a stream resource.
400
-		if ($this->method === 'PUT'
401
-			&& $this->getHeader('Content-Length') !== '0'
402
-			&& $this->getHeader('Content-Length') !== ''
403
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
404
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
405
-		) {
406
-			if ($this->content === false) {
407
-				throw new \LogicException(
408
-					'"put" can only be accessed once if not '
409
-					. 'application/x-www-form-urlencoded or application/json.'
410
-				);
411
-			}
412
-			$this->content = false;
413
-			return fopen($this->inputStream, 'rb');
414
-		} else {
415
-			$this->decodeContent();
416
-			return $this->items['parameters'];
417
-		}
418
-	}
419
-
420
-	/**
421
-	 * Attempt to decode the content and populate parameters
422
-	 */
423
-	protected function decodeContent() {
424
-		if ($this->contentDecoded) {
425
-			return;
426
-		}
427
-		$params = [];
428
-
429
-		// 'application/json' must be decoded manually.
430
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
431
-			$params = json_decode(file_get_contents($this->inputStream), true);
432
-			if ($params !== null && \count($params) > 0) {
433
-				$this->items['params'] = $params;
434
-				if ($this->method === 'POST') {
435
-					$this->items['post'] = $params;
436
-				}
437
-			}
438
-
439
-			// Handle application/x-www-form-urlencoded for methods other than GET
440
-		// or post correctly
441
-		} elseif ($this->method !== 'GET'
442
-				&& $this->method !== 'POST'
443
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
444
-			parse_str(file_get_contents($this->inputStream), $params);
445
-			if (\is_array($params)) {
446
-				$this->items['params'] = $params;
447
-			}
448
-		}
449
-
450
-		if (\is_array($params)) {
451
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
452
-		}
453
-		$this->contentDecoded = true;
454
-	}
455
-
456
-
457
-	/**
458
-	 * Checks if the CSRF check was correct
459
-	 * @return bool true if CSRF check passed
460
-	 */
461
-	public function passesCSRFCheck(): bool {
462
-		if ($this->csrfTokenManager === null) {
463
-			return false;
464
-		}
465
-
466
-		if (!$this->passesStrictCookieCheck()) {
467
-			return false;
468
-		}
469
-
470
-		if (isset($this->items['get']['requesttoken'])) {
471
-			$token = $this->items['get']['requesttoken'];
472
-		} elseif (isset($this->items['post']['requesttoken'])) {
473
-			$token = $this->items['post']['requesttoken'];
474
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
475
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
476
-		} else {
477
-			//no token found.
478
-			return false;
479
-		}
480
-		$token = new CsrfToken($token);
481
-
482
-		return $this->csrfTokenManager->isTokenValid($token);
483
-	}
484
-
485
-	/**
486
-	 * Whether the cookie checks are required
487
-	 *
488
-	 * @return bool
489
-	 */
490
-	private function cookieCheckRequired(): bool {
491
-		if ($this->getHeader('OCS-APIREQUEST')) {
492
-			return false;
493
-		}
494
-		if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
495
-			return false;
496
-		}
497
-
498
-		return true;
499
-	}
500
-
501
-	/**
502
-	 * Wrapper around session_get_cookie_params
503
-	 *
504
-	 * @return array
505
-	 */
506
-	public function getCookieParams(): array {
507
-		return session_get_cookie_params();
508
-	}
509
-
510
-	/**
511
-	 * Appends the __Host- prefix to the cookie if applicable
512
-	 *
513
-	 * @param string $name
514
-	 * @return string
515
-	 */
516
-	protected function getProtectedCookieName(string $name): string {
517
-		$cookieParams = $this->getCookieParams();
518
-		$prefix = '';
519
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
520
-			$prefix = '__Host-';
521
-		}
522
-
523
-		return $prefix.$name;
524
-	}
525
-
526
-	/**
527
-	 * Checks if the strict cookie has been sent with the request if the request
528
-	 * is including any cookies.
529
-	 *
530
-	 * @return bool
531
-	 * @since 9.1.0
532
-	 */
533
-	public function passesStrictCookieCheck(): bool {
534
-		if (!$this->cookieCheckRequired()) {
535
-			return true;
536
-		}
537
-
538
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
539
-		if ($this->getCookie($cookieName) === 'true'
540
-			&& $this->passesLaxCookieCheck()) {
541
-			return true;
542
-		}
543
-		return false;
544
-	}
545
-
546
-	/**
547
-	 * Checks if the lax cookie has been sent with the request if the request
548
-	 * is including any cookies.
549
-	 *
550
-	 * @return bool
551
-	 * @since 9.1.0
552
-	 */
553
-	public function passesLaxCookieCheck(): bool {
554
-		if (!$this->cookieCheckRequired()) {
555
-			return true;
556
-		}
557
-
558
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
559
-		if ($this->getCookie($cookieName) === 'true') {
560
-			return true;
561
-		}
562
-		return false;
563
-	}
564
-
565
-
566
-	/**
567
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
568
-	 * If `mod_unique_id` is installed this value will be taken.
569
-	 * @return string
570
-	 */
571
-	public function getId(): string {
572
-		return $this->requestId->getId();
573
-	}
574
-
575
-	/**
576
-	 * Checks if given $remoteAddress matches given $trustedProxy.
577
-	 * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
578
-	 * $remoteAddress is an IPv4 address within that IP range.
579
-	 * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
580
-	 * will be returned.
581
-	 * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
582
-	 */
583
-	protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
584
-		$cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
585
-
586
-		if (preg_match($cidrre, $trustedProxy, $match)) {
587
-			$net = $match[1];
588
-			$shiftbits = min(32, max(0, 32 - intval($match[2])));
589
-			$netnum = ip2long($net) >> $shiftbits;
590
-			$ipnum = ip2long($remoteAddress) >> $shiftbits;
591
-
592
-			return $ipnum === $netnum;
593
-		}
594
-
595
-		return $trustedProxy === $remoteAddress;
596
-	}
597
-
598
-	/**
599
-	 * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
600
-	 * For details regarding what "match" means, refer to `matchesTrustedProxy`.
601
-	 * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
602
-	 */
603
-	protected function isTrustedProxy($trustedProxies, $remoteAddress) {
604
-		foreach ($trustedProxies as $tp) {
605
-			if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
606
-				return true;
607
-			}
608
-		}
609
-
610
-		return false;
611
-	}
612
-
613
-	/**
614
-	 * Returns the remote address, if the connection came from a trusted proxy
615
-	 * and `forwarded_for_headers` has been configured then the IP address
616
-	 * specified in this header will be returned instead.
617
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
618
-	 * @return string IP address
619
-	 */
620
-	public function getRemoteAddress(): string {
621
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
622
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
623
-
624
-		if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
625
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
626
-				'HTTP_X_FORWARDED_FOR'
627
-				// only have one default, so we cannot ship an insecure product out of the box
628
-			]);
629
-
630
-			foreach ($forwardedForHeaders as $header) {
631
-				if (isset($this->server[$header])) {
632
-					foreach (explode(',', $this->server[$header]) as $IP) {
633
-						$IP = trim($IP);
634
-
635
-						// remove brackets from IPv6 addresses
636
-						if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
637
-							$IP = substr($IP, 1, -1);
638
-						}
639
-
640
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
641
-							return $IP;
642
-						}
643
-					}
644
-				}
645
-			}
646
-		}
647
-
648
-		return $remoteAddress;
649
-	}
650
-
651
-	/**
652
-	 * Check overwrite condition
653
-	 * @param string $type
654
-	 * @return bool
655
-	 */
656
-	private function isOverwriteCondition(string $type = ''): bool {
657
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
658
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
659
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
660
-		|| $type !== 'protocol';
661
-	}
662
-
663
-	/**
664
-	 * Returns the server protocol. It respects one or more reverse proxies servers
665
-	 * and load balancers
666
-	 * @return string Server protocol (http or https)
667
-	 */
668
-	public function getServerProtocol(): string {
669
-		if ($this->config->getSystemValue('overwriteprotocol') !== ''
670
-			&& $this->isOverwriteCondition('protocol')) {
671
-			return $this->config->getSystemValue('overwriteprotocol');
672
-		}
673
-
674
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
675
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
676
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
677
-				$proto = strtolower(trim($parts[0]));
678
-			} else {
679
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
680
-			}
681
-
682
-			// Verify that the protocol is always HTTP or HTTPS
683
-			// default to http if an invalid value is provided
684
-			return $proto === 'https' ? 'https' : 'http';
685
-		}
686
-
687
-		if (isset($this->server['HTTPS'])
688
-			&& $this->server['HTTPS'] !== null
689
-			&& $this->server['HTTPS'] !== 'off'
690
-			&& $this->server['HTTPS'] !== '') {
691
-			return 'https';
692
-		}
693
-
694
-		return 'http';
695
-	}
696
-
697
-	/**
698
-	 * Returns the used HTTP protocol.
699
-	 *
700
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
701
-	 */
702
-	public function getHttpProtocol(): string {
703
-		$claimedProtocol = $this->server['SERVER_PROTOCOL'];
704
-
705
-		if (\is_string($claimedProtocol)) {
706
-			$claimedProtocol = strtoupper($claimedProtocol);
707
-		}
708
-
709
-		$validProtocols = [
710
-			'HTTP/1.0',
711
-			'HTTP/1.1',
712
-			'HTTP/2',
713
-		];
714
-
715
-		if (\in_array($claimedProtocol, $validProtocols, true)) {
716
-			return $claimedProtocol;
717
-		}
718
-
719
-		return 'HTTP/1.1';
720
-	}
721
-
722
-	/**
723
-	 * Returns the request uri, even if the website uses one or more
724
-	 * reverse proxies
725
-	 * @return string
726
-	 */
727
-	public function getRequestUri(): string {
728
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
729
-		if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
730
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
731
-		}
732
-		return $uri;
733
-	}
734
-
735
-	/**
736
-	 * Get raw PathInfo from request (not urldecoded)
737
-	 * @throws \Exception
738
-	 * @return string Path info
739
-	 */
740
-	public function getRawPathInfo(): string {
741
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
742
-		// remove too many slashes - can be caused by reverse proxy configuration
743
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
744
-
745
-		// Remove the query string from REQUEST_URI
746
-		if ($pos = strpos($requestUri, '?')) {
747
-			$requestUri = substr($requestUri, 0, $pos);
748
-		}
749
-
750
-		$scriptName = $this->server['SCRIPT_NAME'];
751
-		$pathInfo = $requestUri;
752
-
753
-		// strip off the script name's dir and file name
754
-		// FIXME: Sabre does not really belong here
755
-		[$path, $name] = \Sabre\Uri\split($scriptName);
756
-		if (!empty($path)) {
757
-			if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
758
-				$pathInfo = substr($pathInfo, \strlen($path));
759
-			} else {
760
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
761
-			}
762
-		}
763
-		if ($name === null) {
764
-			$name = '';
765
-		}
766
-
767
-		if (strpos($pathInfo, '/'.$name) === 0) {
768
-			$pathInfo = substr($pathInfo, \strlen($name) + 1);
769
-		}
770
-		if ($name !== '' && strpos($pathInfo, $name) === 0) {
771
-			$pathInfo = substr($pathInfo, \strlen($name));
772
-		}
773
-		if ($pathInfo === false || $pathInfo === '/') {
774
-			return '';
775
-		} else {
776
-			return $pathInfo;
777
-		}
778
-	}
779
-
780
-	/**
781
-	 * Get PathInfo from request
782
-	 * @throws \Exception
783
-	 * @return string|false Path info or false when not found
784
-	 */
785
-	public function getPathInfo() {
786
-		$pathInfo = $this->getRawPathInfo();
787
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
788
-		$pathInfo = rawurldecode($pathInfo);
789
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
790
-
791
-		switch ($encoding) {
792
-			case 'ISO-8859-1':
793
-				$pathInfo = utf8_encode($pathInfo);
794
-		}
795
-		// end copy
796
-
797
-		return $pathInfo;
798
-	}
799
-
800
-	/**
801
-	 * Returns the script name, even if the website uses one or more
802
-	 * reverse proxies
803
-	 * @return string the script name
804
-	 */
805
-	public function getScriptName(): string {
806
-		$name = $this->server['SCRIPT_NAME'];
807
-		$overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
808
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
809
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
810
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
811
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
812
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
813
-		}
814
-		return $name;
815
-	}
816
-
817
-	/**
818
-	 * Checks whether the user agent matches a given regex
819
-	 * @param array $agent array of agent names
820
-	 * @return bool true if at least one of the given agent matches, false otherwise
821
-	 */
822
-	public function isUserAgent(array $agent): bool {
823
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
824
-			return false;
825
-		}
826
-		foreach ($agent as $regex) {
827
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
828
-				return true;
829
-			}
830
-		}
831
-		return false;
832
-	}
833
-
834
-	/**
835
-	 * Returns the unverified server host from the headers without checking
836
-	 * whether it is a trusted domain
837
-	 * @return string Server host
838
-	 */
839
-	public function getInsecureServerHost(): string {
840
-		if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
841
-			return $this->getOverwriteHost();
842
-		}
843
-
844
-		$host = 'localhost';
845
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
846
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
847
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
848
-				$host = trim(current($parts));
849
-			} else {
850
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
851
-			}
852
-		} else {
853
-			if (isset($this->server['HTTP_HOST'])) {
854
-				$host = $this->server['HTTP_HOST'];
855
-			} elseif (isset($this->server['SERVER_NAME'])) {
856
-				$host = $this->server['SERVER_NAME'];
857
-			}
858
-		}
859
-
860
-		return $host;
861
-	}
862
-
863
-
864
-	/**
865
-	 * Returns the server host from the headers, or the first configured
866
-	 * trusted domain if the host isn't in the trusted list
867
-	 * @return string Server host
868
-	 */
869
-	public function getServerHost(): string {
870
-		// overwritehost is always trusted
871
-		$host = $this->getOverwriteHost();
872
-		if ($host !== null) {
873
-			return $host;
874
-		}
875
-
876
-		// get the host from the headers
877
-		$host = $this->getInsecureServerHost();
878
-
879
-		// Verify that the host is a trusted domain if the trusted domains
880
-		// are defined
881
-		// If no trusted domain is provided the first trusted domain is returned
882
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
883
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
884
-			return $host;
885
-		}
886
-
887
-		$trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
888
-		if (count($trustedList) > 0) {
889
-			return reset($trustedList);
890
-		}
891
-
892
-		return '';
893
-	}
894
-
895
-	/**
896
-	 * Returns the overwritehost setting from the config if set and
897
-	 * if the overwrite condition is met
898
-	 * @return string|null overwritehost value or null if not defined or the defined condition
899
-	 * isn't met
900
-	 */
901
-	private function getOverwriteHost() {
902
-		if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
903
-			return $this->config->getSystemValue('overwritehost');
904
-		}
905
-		return null;
906
-	}
907
-
908
-	private function fromTrustedProxy(): bool {
909
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
910
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
911
-
912
-		return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
913
-	}
66
+    public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
67
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
68
+    public const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
69
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
70
+    public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
71
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
72
+    public const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
73
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
74
+    public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
75
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
76
+    public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
77
+    public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
78
+    public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
79
+
80
+    protected $inputStream;
81
+    protected $content;
82
+    protected $items = [];
83
+    protected $allowedKeys = [
84
+        'get',
85
+        'post',
86
+        'files',
87
+        'server',
88
+        'env',
89
+        'cookies',
90
+        'urlParams',
91
+        'parameters',
92
+        'method',
93
+        'requesttoken',
94
+    ];
95
+    /** @var RequestId */
96
+    protected $requestId;
97
+    /** @var IConfig */
98
+    protected $config;
99
+    /** @var ICrypto */
100
+    protected $crypto;
101
+    /** @var CsrfTokenManager|null */
102
+    protected $csrfTokenManager;
103
+
104
+    /** @var bool */
105
+    protected $contentDecoded = false;
106
+
107
+    /**
108
+     * @param array $vars An associative array with the following optional values:
109
+     *        - array 'urlParams' the parameters which were matched from the URL
110
+     *        - array 'get' the $_GET array
111
+     *        - array|string 'post' the $_POST array or JSON string
112
+     *        - array 'files' the $_FILES array
113
+     *        - array 'server' the $_SERVER array
114
+     *        - array 'env' the $_ENV array
115
+     *        - array 'cookies' the $_COOKIE array
116
+     *        - string 'method' the request method (GET, POST etc)
117
+     *        - string|false 'requesttoken' the requesttoken or false when not available
118
+     * @param IRequestId $requestId
119
+     * @param IConfig $config
120
+     * @param CsrfTokenManager|null $csrfTokenManager
121
+     * @param string $stream
122
+     * @see https://www.php.net/manual/en/reserved.variables.php
123
+     */
124
+    public function __construct(array $vars,
125
+                                IRequestId $requestId,
126
+                                IConfig $config,
127
+                                CsrfTokenManager $csrfTokenManager = null,
128
+                                string $stream = 'php://input') {
129
+        $this->inputStream = $stream;
130
+        $this->items['params'] = [];
131
+        $this->requestId = $requestId;
132
+        $this->config = $config;
133
+        $this->csrfTokenManager = $csrfTokenManager;
134
+
135
+        if (!array_key_exists('method', $vars)) {
136
+            $vars['method'] = 'GET';
137
+        }
138
+
139
+        foreach ($this->allowedKeys as $name) {
140
+            $this->items[$name] = isset($vars[$name])
141
+                ? $vars[$name]
142
+                : [];
143
+        }
144
+
145
+        $this->items['parameters'] = array_merge(
146
+            $this->items['get'],
147
+            $this->items['post'],
148
+            $this->items['urlParams'],
149
+            $this->items['params']
150
+        );
151
+    }
152
+    /**
153
+     * @param array $parameters
154
+     */
155
+    public function setUrlParameters(array $parameters) {
156
+        $this->items['urlParams'] = $parameters;
157
+        $this->items['parameters'] = array_merge(
158
+            $this->items['parameters'],
159
+            $this->items['urlParams']
160
+        );
161
+    }
162
+
163
+    /**
164
+     * Countable method
165
+     * @return int
166
+     */
167
+    public function count(): int {
168
+        return \count($this->items['parameters']);
169
+    }
170
+
171
+    /**
172
+     * ArrayAccess methods
173
+     *
174
+     * Gives access to the combined GET, POST and urlParams arrays
175
+     *
176
+     * Examples:
177
+     *
178
+     * $var = $request['myvar'];
179
+     *
180
+     * or
181
+     *
182
+     * if(!isset($request['myvar']) {
183
+     * 	// Do something
184
+     * }
185
+     *
186
+     * $request['myvar'] = 'something'; // This throws an exception.
187
+     *
188
+     * @param string $offset The key to lookup
189
+     * @return boolean
190
+     */
191
+    public function offsetExists($offset): bool {
192
+        return isset($this->items['parameters'][$offset]);
193
+    }
194
+
195
+    /**
196
+     * @see offsetExists
197
+     * @param string $offset
198
+     * @return mixed
199
+     */
200
+    #[\ReturnTypeWillChange]
201
+    public function offsetGet($offset) {
202
+        return isset($this->items['parameters'][$offset])
203
+            ? $this->items['parameters'][$offset]
204
+            : null;
205
+    }
206
+
207
+    /**
208
+     * @see offsetExists
209
+     * @param string $offset
210
+     * @param mixed $value
211
+     */
212
+    public function offsetSet($offset, $value): void {
213
+        throw new \RuntimeException('You cannot change the contents of the request object');
214
+    }
215
+
216
+    /**
217
+     * @see offsetExists
218
+     * @param string $offset
219
+     */
220
+    public function offsetUnset($offset): void {
221
+        throw new \RuntimeException('You cannot change the contents of the request object');
222
+    }
223
+
224
+    /**
225
+     * Magic property accessors
226
+     * @param string $name
227
+     * @param mixed $value
228
+     */
229
+    public function __set($name, $value) {
230
+        throw new \RuntimeException('You cannot change the contents of the request object');
231
+    }
232
+
233
+    /**
234
+     * Access request variables by method and name.
235
+     * Examples:
236
+     *
237
+     * $request->post['myvar']; // Only look for POST variables
238
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
239
+     * Looks in the combined GET, POST and urlParams array.
240
+     *
241
+     * If you access e.g. ->post but the current HTTP request method
242
+     * is GET a \LogicException will be thrown.
243
+     *
244
+     * @param string $name The key to look for.
245
+     * @throws \LogicException
246
+     * @return mixed|null
247
+     */
248
+    public function __get($name) {
249
+        switch ($name) {
250
+            case 'put':
251
+            case 'patch':
252
+            case 'get':
253
+            case 'post':
254
+                if ($this->method !== strtoupper($name)) {
255
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
256
+                }
257
+                return $this->getContent();
258
+            case 'files':
259
+            case 'server':
260
+            case 'env':
261
+            case 'cookies':
262
+            case 'urlParams':
263
+            case 'method':
264
+                return isset($this->items[$name])
265
+                    ? $this->items[$name]
266
+                    : null;
267
+            case 'parameters':
268
+            case 'params':
269
+                return $this->getContent();
270
+            default:
271
+                return isset($this[$name])
272
+                    ? $this[$name]
273
+                    : null;
274
+        }
275
+    }
276
+
277
+    /**
278
+     * @param string $name
279
+     * @return bool
280
+     */
281
+    public function __isset($name) {
282
+        if (\in_array($name, $this->allowedKeys, true)) {
283
+            return true;
284
+        }
285
+        return isset($this->items['parameters'][$name]);
286
+    }
287
+
288
+    /**
289
+     * @param string $id
290
+     */
291
+    public function __unset($id) {
292
+        throw new \RuntimeException('You cannot change the contents of the request object');
293
+    }
294
+
295
+    /**
296
+     * Returns the value for a specific http header.
297
+     *
298
+     * This method returns an empty string if the header did not exist.
299
+     *
300
+     * @param string $name
301
+     * @return string
302
+     */
303
+    public function getHeader(string $name): string {
304
+        $name = strtoupper(str_replace('-', '_', $name));
305
+        if (isset($this->server['HTTP_' . $name])) {
306
+            return $this->server['HTTP_' . $name];
307
+        }
308
+
309
+        // There's a few headers that seem to end up in the top-level
310
+        // server array.
311
+        switch ($name) {
312
+            case 'CONTENT_TYPE':
313
+            case 'CONTENT_LENGTH':
314
+            case 'REMOTE_ADDR':
315
+                if (isset($this->server[$name])) {
316
+                    return $this->server[$name];
317
+                }
318
+                break;
319
+        }
320
+
321
+        return '';
322
+    }
323
+
324
+    /**
325
+     * Lets you access post and get parameters by the index
326
+     * In case of json requests the encoded json body is accessed
327
+     *
328
+     * @param string $key the key which you want to access in the URL Parameter
329
+     *                     placeholder, $_POST or $_GET array.
330
+     *                     The priority how they're returned is the following:
331
+     *                     1. URL parameters
332
+     *                     2. POST parameters
333
+     *                     3. GET parameters
334
+     * @param mixed $default If the key is not found, this value will be returned
335
+     * @return mixed the content of the array
336
+     */
337
+    public function getParam(string $key, $default = null) {
338
+        return isset($this->parameters[$key])
339
+            ? $this->parameters[$key]
340
+            : $default;
341
+    }
342
+
343
+    /**
344
+     * Returns all params that were received, be it from the request
345
+     * (as GET or POST) or throuh the URL by the route
346
+     * @return array the array with all parameters
347
+     */
348
+    public function getParams(): array {
349
+        return is_array($this->parameters) ? $this->parameters : [];
350
+    }
351
+
352
+    /**
353
+     * Returns the method of the request
354
+     * @return string the method of the request (POST, GET, etc)
355
+     */
356
+    public function getMethod(): string {
357
+        return $this->method;
358
+    }
359
+
360
+    /**
361
+     * Shortcut for accessing an uploaded file through the $_FILES array
362
+     * @param string $key the key that will be taken from the $_FILES array
363
+     * @return array the file in the $_FILES element
364
+     */
365
+    public function getUploadedFile(string $key) {
366
+        return isset($this->files[$key]) ? $this->files[$key] : null;
367
+    }
368
+
369
+    /**
370
+     * Shortcut for getting env variables
371
+     * @param string $key the key that will be taken from the $_ENV array
372
+     * @return array the value in the $_ENV element
373
+     */
374
+    public function getEnv(string $key) {
375
+        return isset($this->env[$key]) ? $this->env[$key] : null;
376
+    }
377
+
378
+    /**
379
+     * Shortcut for getting cookie variables
380
+     * @param string $key the key that will be taken from the $_COOKIE array
381
+     * @return string the value in the $_COOKIE element
382
+     */
383
+    public function getCookie(string $key) {
384
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
385
+    }
386
+
387
+    /**
388
+     * Returns the request body content.
389
+     *
390
+     * If the HTTP request method is PUT and the body
391
+     * not application/x-www-form-urlencoded or application/json a stream
392
+     * resource is returned, otherwise an array.
393
+     *
394
+     * @return array|string|resource The request body content or a resource to read the body stream.
395
+     *
396
+     * @throws \LogicException
397
+     */
398
+    protected function getContent() {
399
+        // If the content can't be parsed into an array then return a stream resource.
400
+        if ($this->method === 'PUT'
401
+            && $this->getHeader('Content-Length') !== '0'
402
+            && $this->getHeader('Content-Length') !== ''
403
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
404
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
405
+        ) {
406
+            if ($this->content === false) {
407
+                throw new \LogicException(
408
+                    '"put" can only be accessed once if not '
409
+                    . 'application/x-www-form-urlencoded or application/json.'
410
+                );
411
+            }
412
+            $this->content = false;
413
+            return fopen($this->inputStream, 'rb');
414
+        } else {
415
+            $this->decodeContent();
416
+            return $this->items['parameters'];
417
+        }
418
+    }
419
+
420
+    /**
421
+     * Attempt to decode the content and populate parameters
422
+     */
423
+    protected function decodeContent() {
424
+        if ($this->contentDecoded) {
425
+            return;
426
+        }
427
+        $params = [];
428
+
429
+        // 'application/json' must be decoded manually.
430
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
431
+            $params = json_decode(file_get_contents($this->inputStream), true);
432
+            if ($params !== null && \count($params) > 0) {
433
+                $this->items['params'] = $params;
434
+                if ($this->method === 'POST') {
435
+                    $this->items['post'] = $params;
436
+                }
437
+            }
438
+
439
+            // Handle application/x-www-form-urlencoded for methods other than GET
440
+        // or post correctly
441
+        } elseif ($this->method !== 'GET'
442
+                && $this->method !== 'POST'
443
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
444
+            parse_str(file_get_contents($this->inputStream), $params);
445
+            if (\is_array($params)) {
446
+                $this->items['params'] = $params;
447
+            }
448
+        }
449
+
450
+        if (\is_array($params)) {
451
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
452
+        }
453
+        $this->contentDecoded = true;
454
+    }
455
+
456
+
457
+    /**
458
+     * Checks if the CSRF check was correct
459
+     * @return bool true if CSRF check passed
460
+     */
461
+    public function passesCSRFCheck(): bool {
462
+        if ($this->csrfTokenManager === null) {
463
+            return false;
464
+        }
465
+
466
+        if (!$this->passesStrictCookieCheck()) {
467
+            return false;
468
+        }
469
+
470
+        if (isset($this->items['get']['requesttoken'])) {
471
+            $token = $this->items['get']['requesttoken'];
472
+        } elseif (isset($this->items['post']['requesttoken'])) {
473
+            $token = $this->items['post']['requesttoken'];
474
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
475
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
476
+        } else {
477
+            //no token found.
478
+            return false;
479
+        }
480
+        $token = new CsrfToken($token);
481
+
482
+        return $this->csrfTokenManager->isTokenValid($token);
483
+    }
484
+
485
+    /**
486
+     * Whether the cookie checks are required
487
+     *
488
+     * @return bool
489
+     */
490
+    private function cookieCheckRequired(): bool {
491
+        if ($this->getHeader('OCS-APIREQUEST')) {
492
+            return false;
493
+        }
494
+        if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
495
+            return false;
496
+        }
497
+
498
+        return true;
499
+    }
500
+
501
+    /**
502
+     * Wrapper around session_get_cookie_params
503
+     *
504
+     * @return array
505
+     */
506
+    public function getCookieParams(): array {
507
+        return session_get_cookie_params();
508
+    }
509
+
510
+    /**
511
+     * Appends the __Host- prefix to the cookie if applicable
512
+     *
513
+     * @param string $name
514
+     * @return string
515
+     */
516
+    protected function getProtectedCookieName(string $name): string {
517
+        $cookieParams = $this->getCookieParams();
518
+        $prefix = '';
519
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
520
+            $prefix = '__Host-';
521
+        }
522
+
523
+        return $prefix.$name;
524
+    }
525
+
526
+    /**
527
+     * Checks if the strict cookie has been sent with the request if the request
528
+     * is including any cookies.
529
+     *
530
+     * @return bool
531
+     * @since 9.1.0
532
+     */
533
+    public function passesStrictCookieCheck(): bool {
534
+        if (!$this->cookieCheckRequired()) {
535
+            return true;
536
+        }
537
+
538
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
539
+        if ($this->getCookie($cookieName) === 'true'
540
+            && $this->passesLaxCookieCheck()) {
541
+            return true;
542
+        }
543
+        return false;
544
+    }
545
+
546
+    /**
547
+     * Checks if the lax cookie has been sent with the request if the request
548
+     * is including any cookies.
549
+     *
550
+     * @return bool
551
+     * @since 9.1.0
552
+     */
553
+    public function passesLaxCookieCheck(): bool {
554
+        if (!$this->cookieCheckRequired()) {
555
+            return true;
556
+        }
557
+
558
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
559
+        if ($this->getCookie($cookieName) === 'true') {
560
+            return true;
561
+        }
562
+        return false;
563
+    }
564
+
565
+
566
+    /**
567
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
568
+     * If `mod_unique_id` is installed this value will be taken.
569
+     * @return string
570
+     */
571
+    public function getId(): string {
572
+        return $this->requestId->getId();
573
+    }
574
+
575
+    /**
576
+     * Checks if given $remoteAddress matches given $trustedProxy.
577
+     * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
578
+     * $remoteAddress is an IPv4 address within that IP range.
579
+     * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
580
+     * will be returned.
581
+     * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
582
+     */
583
+    protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
584
+        $cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
585
+
586
+        if (preg_match($cidrre, $trustedProxy, $match)) {
587
+            $net = $match[1];
588
+            $shiftbits = min(32, max(0, 32 - intval($match[2])));
589
+            $netnum = ip2long($net) >> $shiftbits;
590
+            $ipnum = ip2long($remoteAddress) >> $shiftbits;
591
+
592
+            return $ipnum === $netnum;
593
+        }
594
+
595
+        return $trustedProxy === $remoteAddress;
596
+    }
597
+
598
+    /**
599
+     * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
600
+     * For details regarding what "match" means, refer to `matchesTrustedProxy`.
601
+     * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
602
+     */
603
+    protected function isTrustedProxy($trustedProxies, $remoteAddress) {
604
+        foreach ($trustedProxies as $tp) {
605
+            if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
606
+                return true;
607
+            }
608
+        }
609
+
610
+        return false;
611
+    }
612
+
613
+    /**
614
+     * Returns the remote address, if the connection came from a trusted proxy
615
+     * and `forwarded_for_headers` has been configured then the IP address
616
+     * specified in this header will be returned instead.
617
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
618
+     * @return string IP address
619
+     */
620
+    public function getRemoteAddress(): string {
621
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
622
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
623
+
624
+        if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
625
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
626
+                'HTTP_X_FORWARDED_FOR'
627
+                // only have one default, so we cannot ship an insecure product out of the box
628
+            ]);
629
+
630
+            foreach ($forwardedForHeaders as $header) {
631
+                if (isset($this->server[$header])) {
632
+                    foreach (explode(',', $this->server[$header]) as $IP) {
633
+                        $IP = trim($IP);
634
+
635
+                        // remove brackets from IPv6 addresses
636
+                        if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
637
+                            $IP = substr($IP, 1, -1);
638
+                        }
639
+
640
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
641
+                            return $IP;
642
+                        }
643
+                    }
644
+                }
645
+            }
646
+        }
647
+
648
+        return $remoteAddress;
649
+    }
650
+
651
+    /**
652
+     * Check overwrite condition
653
+     * @param string $type
654
+     * @return bool
655
+     */
656
+    private function isOverwriteCondition(string $type = ''): bool {
657
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
658
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
659
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
660
+        || $type !== 'protocol';
661
+    }
662
+
663
+    /**
664
+     * Returns the server protocol. It respects one or more reverse proxies servers
665
+     * and load balancers
666
+     * @return string Server protocol (http or https)
667
+     */
668
+    public function getServerProtocol(): string {
669
+        if ($this->config->getSystemValue('overwriteprotocol') !== ''
670
+            && $this->isOverwriteCondition('protocol')) {
671
+            return $this->config->getSystemValue('overwriteprotocol');
672
+        }
673
+
674
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
675
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
676
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
677
+                $proto = strtolower(trim($parts[0]));
678
+            } else {
679
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
680
+            }
681
+
682
+            // Verify that the protocol is always HTTP or HTTPS
683
+            // default to http if an invalid value is provided
684
+            return $proto === 'https' ? 'https' : 'http';
685
+        }
686
+
687
+        if (isset($this->server['HTTPS'])
688
+            && $this->server['HTTPS'] !== null
689
+            && $this->server['HTTPS'] !== 'off'
690
+            && $this->server['HTTPS'] !== '') {
691
+            return 'https';
692
+        }
693
+
694
+        return 'http';
695
+    }
696
+
697
+    /**
698
+     * Returns the used HTTP protocol.
699
+     *
700
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
701
+     */
702
+    public function getHttpProtocol(): string {
703
+        $claimedProtocol = $this->server['SERVER_PROTOCOL'];
704
+
705
+        if (\is_string($claimedProtocol)) {
706
+            $claimedProtocol = strtoupper($claimedProtocol);
707
+        }
708
+
709
+        $validProtocols = [
710
+            'HTTP/1.0',
711
+            'HTTP/1.1',
712
+            'HTTP/2',
713
+        ];
714
+
715
+        if (\in_array($claimedProtocol, $validProtocols, true)) {
716
+            return $claimedProtocol;
717
+        }
718
+
719
+        return 'HTTP/1.1';
720
+    }
721
+
722
+    /**
723
+     * Returns the request uri, even if the website uses one or more
724
+     * reverse proxies
725
+     * @return string
726
+     */
727
+    public function getRequestUri(): string {
728
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
729
+        if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
730
+            $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
731
+        }
732
+        return $uri;
733
+    }
734
+
735
+    /**
736
+     * Get raw PathInfo from request (not urldecoded)
737
+     * @throws \Exception
738
+     * @return string Path info
739
+     */
740
+    public function getRawPathInfo(): string {
741
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
742
+        // remove too many slashes - can be caused by reverse proxy configuration
743
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
744
+
745
+        // Remove the query string from REQUEST_URI
746
+        if ($pos = strpos($requestUri, '?')) {
747
+            $requestUri = substr($requestUri, 0, $pos);
748
+        }
749
+
750
+        $scriptName = $this->server['SCRIPT_NAME'];
751
+        $pathInfo = $requestUri;
752
+
753
+        // strip off the script name's dir and file name
754
+        // FIXME: Sabre does not really belong here
755
+        [$path, $name] = \Sabre\Uri\split($scriptName);
756
+        if (!empty($path)) {
757
+            if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
758
+                $pathInfo = substr($pathInfo, \strlen($path));
759
+            } else {
760
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
761
+            }
762
+        }
763
+        if ($name === null) {
764
+            $name = '';
765
+        }
766
+
767
+        if (strpos($pathInfo, '/'.$name) === 0) {
768
+            $pathInfo = substr($pathInfo, \strlen($name) + 1);
769
+        }
770
+        if ($name !== '' && strpos($pathInfo, $name) === 0) {
771
+            $pathInfo = substr($pathInfo, \strlen($name));
772
+        }
773
+        if ($pathInfo === false || $pathInfo === '/') {
774
+            return '';
775
+        } else {
776
+            return $pathInfo;
777
+        }
778
+    }
779
+
780
+    /**
781
+     * Get PathInfo from request
782
+     * @throws \Exception
783
+     * @return string|false Path info or false when not found
784
+     */
785
+    public function getPathInfo() {
786
+        $pathInfo = $this->getRawPathInfo();
787
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
788
+        $pathInfo = rawurldecode($pathInfo);
789
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
790
+
791
+        switch ($encoding) {
792
+            case 'ISO-8859-1':
793
+                $pathInfo = utf8_encode($pathInfo);
794
+        }
795
+        // end copy
796
+
797
+        return $pathInfo;
798
+    }
799
+
800
+    /**
801
+     * Returns the script name, even if the website uses one or more
802
+     * reverse proxies
803
+     * @return string the script name
804
+     */
805
+    public function getScriptName(): string {
806
+        $name = $this->server['SCRIPT_NAME'];
807
+        $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
808
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
809
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
810
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
811
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
812
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
813
+        }
814
+        return $name;
815
+    }
816
+
817
+    /**
818
+     * Checks whether the user agent matches a given regex
819
+     * @param array $agent array of agent names
820
+     * @return bool true if at least one of the given agent matches, false otherwise
821
+     */
822
+    public function isUserAgent(array $agent): bool {
823
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
824
+            return false;
825
+        }
826
+        foreach ($agent as $regex) {
827
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
828
+                return true;
829
+            }
830
+        }
831
+        return false;
832
+    }
833
+
834
+    /**
835
+     * Returns the unverified server host from the headers without checking
836
+     * whether it is a trusted domain
837
+     * @return string Server host
838
+     */
839
+    public function getInsecureServerHost(): string {
840
+        if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
841
+            return $this->getOverwriteHost();
842
+        }
843
+
844
+        $host = 'localhost';
845
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
846
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
847
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
848
+                $host = trim(current($parts));
849
+            } else {
850
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
851
+            }
852
+        } else {
853
+            if (isset($this->server['HTTP_HOST'])) {
854
+                $host = $this->server['HTTP_HOST'];
855
+            } elseif (isset($this->server['SERVER_NAME'])) {
856
+                $host = $this->server['SERVER_NAME'];
857
+            }
858
+        }
859
+
860
+        return $host;
861
+    }
862
+
863
+
864
+    /**
865
+     * Returns the server host from the headers, or the first configured
866
+     * trusted domain if the host isn't in the trusted list
867
+     * @return string Server host
868
+     */
869
+    public function getServerHost(): string {
870
+        // overwritehost is always trusted
871
+        $host = $this->getOverwriteHost();
872
+        if ($host !== null) {
873
+            return $host;
874
+        }
875
+
876
+        // get the host from the headers
877
+        $host = $this->getInsecureServerHost();
878
+
879
+        // Verify that the host is a trusted domain if the trusted domains
880
+        // are defined
881
+        // If no trusted domain is provided the first trusted domain is returned
882
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
883
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
884
+            return $host;
885
+        }
886
+
887
+        $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
888
+        if (count($trustedList) > 0) {
889
+            return reset($trustedList);
890
+        }
891
+
892
+        return '';
893
+    }
894
+
895
+    /**
896
+     * Returns the overwritehost setting from the config if set and
897
+     * if the overwrite condition is met
898
+     * @return string|null overwritehost value or null if not defined or the defined condition
899
+     * isn't met
900
+     */
901
+    private function getOverwriteHost() {
902
+        if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
903
+            return $this->config->getSystemValue('overwritehost');
904
+        }
905
+        return null;
906
+    }
907
+
908
+    private function fromTrustedProxy(): bool {
909
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
910
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
911
+
912
+        return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
913
+    }
914 914
 }
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 2 patches
Indentation   +531 added lines, -531 removed lines patch added patch discarded remove patch
@@ -57,535 +57,535 @@
 block discarded – undo
57 57
 use OCP\PreConditionNotMetException;
58 58
 
59 59
 class Connection extends \Doctrine\DBAL\Connection {
60
-	/** @var string */
61
-	protected $tablePrefix;
62
-
63
-	/** @var \OC\DB\Adapter $adapter */
64
-	protected $adapter;
65
-
66
-	/** @var SystemConfig */
67
-	private $systemConfig;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	protected $lockedTable = null;
73
-
74
-	/** @var int */
75
-	protected $queriesBuilt = 0;
76
-
77
-	/** @var int */
78
-	protected $queriesExecuted = 0;
79
-
80
-	/**
81
-	 * @throws Exception
82
-	 */
83
-	public function connect() {
84
-		try {
85
-			if ($this->_conn) {
86
-				return parent::connect();
87
-			}
88
-
89
-			// Only trigger the event logger for the initial connect call
90
-			$eventLogger = \OC::$server->getEventLogger();
91
-			$eventLogger->start('connect:db', 'db connection opened');
92
-			$status = parent::connect();
93
-			$eventLogger->end('connect:db');
94
-
95
-			return $status;
96
-		} catch (Exception $e) {
97
-			// throw a new exception to prevent leaking info from the stacktrace
98
-			throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
99
-		}
100
-	}
101
-
102
-	public function getStats(): array {
103
-		return [
104
-			'built' => $this->queriesBuilt,
105
-			'executed' => $this->queriesExecuted,
106
-		];
107
-	}
108
-
109
-	/**
110
-	 * Returns a QueryBuilder for the connection.
111
-	 */
112
-	public function getQueryBuilder(): IQueryBuilder {
113
-		$this->queriesBuilt++;
114
-		return new QueryBuilder(
115
-			new ConnectionAdapter($this),
116
-			$this->systemConfig,
117
-			$this->logger
118
-		);
119
-	}
120
-
121
-	/**
122
-	 * Gets the QueryBuilder for the connection.
123
-	 *
124
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
125
-	 * @deprecated please use $this->getQueryBuilder() instead
126
-	 */
127
-	public function createQueryBuilder() {
128
-		$backtrace = $this->getCallerBacktrace();
129
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
130
-		$this->queriesBuilt++;
131
-		return parent::createQueryBuilder();
132
-	}
133
-
134
-	/**
135
-	 * Gets the ExpressionBuilder for the connection.
136
-	 *
137
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
138
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
139
-	 */
140
-	public function getExpressionBuilder() {
141
-		$backtrace = $this->getCallerBacktrace();
142
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
143
-		$this->queriesBuilt++;
144
-		return parent::getExpressionBuilder();
145
-	}
146
-
147
-	/**
148
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
149
-	 *
150
-	 * @return string
151
-	 */
152
-	protected function getCallerBacktrace() {
153
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
154
-
155
-		// 0 is the method where we use `getCallerBacktrace`
156
-		// 1 is the target method which uses the method we want to log
157
-		if (isset($traces[1])) {
158
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
159
-		}
160
-
161
-		return '';
162
-	}
163
-
164
-	/**
165
-	 * @return string
166
-	 */
167
-	public function getPrefix() {
168
-		return $this->tablePrefix;
169
-	}
170
-
171
-	/**
172
-	 * Initializes a new instance of the Connection class.
173
-	 *
174
-	 * @param array $params  The connection parameters.
175
-	 * @param \Doctrine\DBAL\Driver $driver
176
-	 * @param \Doctrine\DBAL\Configuration $config
177
-	 * @param \Doctrine\Common\EventManager $eventManager
178
-	 * @throws \Exception
179
-	 */
180
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
181
-		EventManager $eventManager = null) {
182
-		if (!isset($params['adapter'])) {
183
-			throw new \Exception('adapter not set');
184
-		}
185
-		if (!isset($params['tablePrefix'])) {
186
-			throw new \Exception('tablePrefix not set');
187
-		}
188
-		/**
189
-		 * @psalm-suppress InternalMethod
190
-		 */
191
-		parent::__construct($params, $driver, $config, $eventManager);
192
-		$this->adapter = new $params['adapter']($this);
193
-		$this->tablePrefix = $params['tablePrefix'];
194
-
195
-		$this->systemConfig = \OC::$server->getSystemConfig();
196
-		$this->logger = \OC::$server->getLogger();
197
-	}
198
-
199
-	/**
200
-	 * Prepares an SQL statement.
201
-	 *
202
-	 * @param string $statement The SQL statement to prepare.
203
-	 * @param int|null $limit
204
-	 * @param int|null $offset
205
-	 *
206
-	 * @return Statement The prepared statement.
207
-	 * @throws Exception
208
-	 */
209
-	public function prepare($statement, $limit = null, $offset = null): Statement {
210
-		if ($limit === -1 || $limit === null) {
211
-			$limit = null;
212
-		} else {
213
-			$limit = (int) $limit;
214
-		}
215
-		if ($offset !== null) {
216
-			$offset = (int) $offset;
217
-		}
218
-		if (!is_null($limit)) {
219
-			$platform = $this->getDatabasePlatform();
220
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
221
-		}
222
-		$statement = $this->replaceTablePrefix($statement);
223
-		$statement = $this->adapter->fixupStatement($statement);
224
-
225
-		return parent::prepare($statement);
226
-	}
227
-
228
-	/**
229
-	 * Executes an, optionally parametrized, SQL query.
230
-	 *
231
-	 * If the query is parametrized, a prepared statement is used.
232
-	 * If an SQLLogger is configured, the execution is logged.
233
-	 *
234
-	 * @param string                                      $sql  The SQL query to execute.
235
-	 * @param array                                       $params The parameters to bind to the query, if any.
236
-	 * @param array                                       $types  The types the previous parameters are in.
237
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
238
-	 *
239
-	 * @return Result The executed statement.
240
-	 *
241
-	 * @throws \Doctrine\DBAL\Exception
242
-	 */
243
-	public function executeQuery(string $sql, array $params = [], $types = [], QueryCacheProfile $qcp = null): Result {
244
-		$sql = $this->replaceTablePrefix($sql);
245
-		$sql = $this->adapter->fixupStatement($sql);
246
-		$this->queriesExecuted++;
247
-		$this->logQueryToFile($sql);
248
-		return parent::executeQuery($sql, $params, $types, $qcp);
249
-	}
250
-
251
-	/**
252
-	 * @throws Exception
253
-	 */
254
-	public function executeUpdate(string $sql, array $params = [], array $types = []): int {
255
-		$sql = $this->replaceTablePrefix($sql);
256
-		$sql = $this->adapter->fixupStatement($sql);
257
-		$this->queriesExecuted++;
258
-		$this->logQueryToFile($sql);
259
-		return parent::executeUpdate($sql, $params, $types);
260
-	}
261
-
262
-	/**
263
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
264
-	 * and returns the number of affected rows.
265
-	 *
266
-	 * This method supports PDO binding types as well as DBAL mapping types.
267
-	 *
268
-	 * @param string $sql  The SQL query.
269
-	 * @param array  $params The query parameters.
270
-	 * @param array  $types  The parameter types.
271
-	 *
272
-	 * @return int The number of affected rows.
273
-	 *
274
-	 * @throws \Doctrine\DBAL\Exception
275
-	 */
276
-	public function executeStatement($sql, array $params = [], array $types = []): int {
277
-		$sql = $this->replaceTablePrefix($sql);
278
-		$sql = $this->adapter->fixupStatement($sql);
279
-		$this->queriesExecuted++;
280
-		$this->logQueryToFile($sql);
281
-		return parent::executeStatement($sql, $params, $types);
282
-	}
283
-
284
-	protected function logQueryToFile(string $sql): void {
285
-		$logFile = $this->systemConfig->getValue('query_log_file');
286
-		if ($logFile !== '' && is_writable(dirname($logFile)) && (!file_exists($logFile) || is_writable($logFile))) {
287
-			$prefix = '';
288
-			if ($this->systemConfig->getValue('query_log_file_requestid') === 'yes') {
289
-				$prefix .= \OC::$server->get(IRequestId::class)->getId() . "\t";
290
-			}
291
-
292
-			file_put_contents(
293
-				$this->systemConfig->getValue('query_log_file', ''),
294
-				$prefix . $sql . "\n",
295
-				FILE_APPEND
296
-			);
297
-		}
298
-	}
299
-
300
-	/**
301
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
302
-	 * depending on the underlying driver.
303
-	 *
304
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
305
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
306
-	 * columns or sequences.
307
-	 *
308
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
309
-	 *
310
-	 * @return string the last inserted ID.
311
-	 * @throws Exception
312
-	 */
313
-	public function lastInsertId($seqName = null) {
314
-		if ($seqName) {
315
-			$seqName = $this->replaceTablePrefix($seqName);
316
-		}
317
-		return $this->adapter->lastInsertId($seqName);
318
-	}
319
-
320
-	/**
321
-	 * @internal
322
-	 * @throws Exception
323
-	 */
324
-	public function realLastInsertId($seqName = null) {
325
-		return parent::lastInsertId($seqName);
326
-	}
327
-
328
-	/**
329
-	 * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
330
-	 * it is needed that there is also a unique constraint on the values. Then this method will
331
-	 * catch the exception and return 0.
332
-	 *
333
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
334
-	 * @param array $input data that should be inserted into the table  (column name => value)
335
-	 * @param array|null $compare List of values that should be checked for "if not exists"
336
-	 *				If this is null or an empty array, all keys of $input will be compared
337
-	 *				Please note: text fields (clob) must not be used in the compare array
338
-	 * @return int number of inserted rows
339
-	 * @throws \Doctrine\DBAL\Exception
340
-	 * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
341
-	 */
342
-	public function insertIfNotExist($table, $input, array $compare = null) {
343
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
344
-	}
345
-
346
-	public function insertIgnoreConflict(string $table, array $values) : int {
347
-		return $this->adapter->insertIgnoreConflict($table, $values);
348
-	}
349
-
350
-	private function getType($value) {
351
-		if (is_bool($value)) {
352
-			return IQueryBuilder::PARAM_BOOL;
353
-		} elseif (is_int($value)) {
354
-			return IQueryBuilder::PARAM_INT;
355
-		} else {
356
-			return IQueryBuilder::PARAM_STR;
357
-		}
358
-	}
359
-
360
-	/**
361
-	 * Insert or update a row value
362
-	 *
363
-	 * @param string $table
364
-	 * @param array $keys (column name => value)
365
-	 * @param array $values (column name => value)
366
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
367
-	 * @return int number of new rows
368
-	 * @throws \Doctrine\DBAL\Exception
369
-	 * @throws PreConditionNotMetException
370
-	 */
371
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
372
-		try {
373
-			$insertQb = $this->getQueryBuilder();
374
-			$insertQb->insert($table)
375
-				->values(
376
-					array_map(function ($value) use ($insertQb) {
377
-						return $insertQb->createNamedParameter($value, $this->getType($value));
378
-					}, array_merge($keys, $values))
379
-				);
380
-			return $insertQb->execute();
381
-		} catch (NotNullConstraintViolationException $e) {
382
-			throw $e;
383
-		} catch (ConstraintViolationException $e) {
384
-			// value already exists, try update
385
-			$updateQb = $this->getQueryBuilder();
386
-			$updateQb->update($table);
387
-			foreach ($values as $name => $value) {
388
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
389
-			}
390
-			$where = $updateQb->expr()->andX();
391
-			$whereValues = array_merge($keys, $updatePreconditionValues);
392
-			foreach ($whereValues as $name => $value) {
393
-				if ($value === '') {
394
-					$where->add($updateQb->expr()->emptyString(
395
-						$name
396
-					));
397
-				} else {
398
-					$where->add($updateQb->expr()->eq(
399
-						$name,
400
-						$updateQb->createNamedParameter($value, $this->getType($value)),
401
-						$this->getType($value)
402
-					));
403
-				}
404
-			}
405
-			$updateQb->where($where);
406
-			$affected = $updateQb->execute();
407
-
408
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
409
-				throw new PreConditionNotMetException();
410
-			}
411
-
412
-			return 0;
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * Create an exclusive read+write lock on a table
418
-	 *
419
-	 * @param string $tableName
420
-	 *
421
-	 * @throws \BadMethodCallException When trying to acquire a second lock
422
-	 * @throws Exception
423
-	 * @since 9.1.0
424
-	 */
425
-	public function lockTable($tableName) {
426
-		if ($this->lockedTable !== null) {
427
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
428
-		}
429
-
430
-		$tableName = $this->tablePrefix . $tableName;
431
-		$this->lockedTable = $tableName;
432
-		$this->adapter->lockTable($tableName);
433
-	}
434
-
435
-	/**
436
-	 * Release a previous acquired lock again
437
-	 *
438
-	 * @throws Exception
439
-	 * @since 9.1.0
440
-	 */
441
-	public function unlockTable() {
442
-		$this->adapter->unlockTable();
443
-		$this->lockedTable = null;
444
-	}
445
-
446
-	/**
447
-	 * returns the error code and message as a string for logging
448
-	 * works with DoctrineException
449
-	 * @return string
450
-	 */
451
-	public function getError() {
452
-		$msg = $this->errorCode() . ': ';
453
-		$errorInfo = $this->errorInfo();
454
-		if (!empty($errorInfo)) {
455
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
456
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
457
-			$msg .= 'Driver Message = '.$errorInfo[2];
458
-		}
459
-		return $msg;
460
-	}
461
-
462
-	public function errorCode() {
463
-		return -1;
464
-	}
465
-
466
-	public function errorInfo() {
467
-		return [];
468
-	}
469
-
470
-	/**
471
-	 * Drop a table from the database if it exists
472
-	 *
473
-	 * @param string $table table name without the prefix
474
-	 *
475
-	 * @throws Exception
476
-	 */
477
-	public function dropTable($table) {
478
-		$table = $this->tablePrefix . trim($table);
479
-		$schema = $this->getSchemaManager();
480
-		if ($schema->tablesExist([$table])) {
481
-			$schema->dropTable($table);
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Check if a table exists
487
-	 *
488
-	 * @param string $table table name without the prefix
489
-	 *
490
-	 * @return bool
491
-	 * @throws Exception
492
-	 */
493
-	public function tableExists($table) {
494
-		$table = $this->tablePrefix . trim($table);
495
-		$schema = $this->getSchemaManager();
496
-		return $schema->tablesExist([$table]);
497
-	}
498
-
499
-	// internal use
500
-	/**
501
-	 * @param string $statement
502
-	 * @return string
503
-	 */
504
-	protected function replaceTablePrefix($statement) {
505
-		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
506
-	}
507
-
508
-	/**
509
-	 * Check if a transaction is active
510
-	 *
511
-	 * @return bool
512
-	 * @since 8.2.0
513
-	 */
514
-	public function inTransaction() {
515
-		return $this->getTransactionNestingLevel() > 0;
516
-	}
517
-
518
-	/**
519
-	 * Escape a parameter to be used in a LIKE query
520
-	 *
521
-	 * @param string $param
522
-	 * @return string
523
-	 */
524
-	public function escapeLikeParameter($param) {
525
-		return addcslashes($param, '\\_%');
526
-	}
527
-
528
-	/**
529
-	 * Check whether or not the current database support 4byte wide unicode
530
-	 *
531
-	 * @return bool
532
-	 * @since 11.0.0
533
-	 */
534
-	public function supports4ByteText() {
535
-		if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
536
-			return true;
537
-		}
538
-		return $this->getParams()['charset'] === 'utf8mb4';
539
-	}
540
-
541
-
542
-	/**
543
-	 * Create the schema of the connected database
544
-	 *
545
-	 * @return Schema
546
-	 * @throws Exception
547
-	 */
548
-	public function createSchema() {
549
-		$migrator = $this->getMigrator();
550
-		return $migrator->createSchema();
551
-	}
552
-
553
-	/**
554
-	 * Migrate the database to the given schema
555
-	 *
556
-	 * @param Schema $toSchema
557
-	 * @param bool $dryRun If true, will return the sql queries instead of running them.
558
-	 *
559
-	 * @throws Exception
560
-	 *
561
-	 * @return string|null Returns a string only if $dryRun is true.
562
-	 */
563
-	public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
564
-		$migrator = $this->getMigrator();
565
-
566
-		if ($dryRun) {
567
-			return $migrator->generateChangeScript($toSchema);
568
-		} else {
569
-			$migrator->migrate($toSchema);
570
-		}
571
-	}
572
-
573
-	private function getMigrator() {
574
-		// TODO properly inject those dependencies
575
-		$random = \OC::$server->getSecureRandom();
576
-		$platform = $this->getDatabasePlatform();
577
-		$config = \OC::$server->getConfig();
578
-		$dispatcher = \OC::$server->getEventDispatcher();
579
-		if ($platform instanceof SqlitePlatform) {
580
-			return new SQLiteMigrator($this, $config, $dispatcher);
581
-		} elseif ($platform instanceof OraclePlatform) {
582
-			return new OracleMigrator($this, $config, $dispatcher);
583
-		} elseif ($platform instanceof MySQLPlatform) {
584
-			return new MySQLMigrator($this, $config, $dispatcher);
585
-		} elseif ($platform instanceof PostgreSQL94Platform) {
586
-			return new PostgreSqlMigrator($this, $config, $dispatcher);
587
-		} else {
588
-			return new Migrator($this, $config, $dispatcher);
589
-		}
590
-	}
60
+    /** @var string */
61
+    protected $tablePrefix;
62
+
63
+    /** @var \OC\DB\Adapter $adapter */
64
+    protected $adapter;
65
+
66
+    /** @var SystemConfig */
67
+    private $systemConfig;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    protected $lockedTable = null;
73
+
74
+    /** @var int */
75
+    protected $queriesBuilt = 0;
76
+
77
+    /** @var int */
78
+    protected $queriesExecuted = 0;
79
+
80
+    /**
81
+     * @throws Exception
82
+     */
83
+    public function connect() {
84
+        try {
85
+            if ($this->_conn) {
86
+                return parent::connect();
87
+            }
88
+
89
+            // Only trigger the event logger for the initial connect call
90
+            $eventLogger = \OC::$server->getEventLogger();
91
+            $eventLogger->start('connect:db', 'db connection opened');
92
+            $status = parent::connect();
93
+            $eventLogger->end('connect:db');
94
+
95
+            return $status;
96
+        } catch (Exception $e) {
97
+            // throw a new exception to prevent leaking info from the stacktrace
98
+            throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
99
+        }
100
+    }
101
+
102
+    public function getStats(): array {
103
+        return [
104
+            'built' => $this->queriesBuilt,
105
+            'executed' => $this->queriesExecuted,
106
+        ];
107
+    }
108
+
109
+    /**
110
+     * Returns a QueryBuilder for the connection.
111
+     */
112
+    public function getQueryBuilder(): IQueryBuilder {
113
+        $this->queriesBuilt++;
114
+        return new QueryBuilder(
115
+            new ConnectionAdapter($this),
116
+            $this->systemConfig,
117
+            $this->logger
118
+        );
119
+    }
120
+
121
+    /**
122
+     * Gets the QueryBuilder for the connection.
123
+     *
124
+     * @return \Doctrine\DBAL\Query\QueryBuilder
125
+     * @deprecated please use $this->getQueryBuilder() instead
126
+     */
127
+    public function createQueryBuilder() {
128
+        $backtrace = $this->getCallerBacktrace();
129
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
130
+        $this->queriesBuilt++;
131
+        return parent::createQueryBuilder();
132
+    }
133
+
134
+    /**
135
+     * Gets the ExpressionBuilder for the connection.
136
+     *
137
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
138
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
139
+     */
140
+    public function getExpressionBuilder() {
141
+        $backtrace = $this->getCallerBacktrace();
142
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
143
+        $this->queriesBuilt++;
144
+        return parent::getExpressionBuilder();
145
+    }
146
+
147
+    /**
148
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
149
+     *
150
+     * @return string
151
+     */
152
+    protected function getCallerBacktrace() {
153
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
154
+
155
+        // 0 is the method where we use `getCallerBacktrace`
156
+        // 1 is the target method which uses the method we want to log
157
+        if (isset($traces[1])) {
158
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
159
+        }
160
+
161
+        return '';
162
+    }
163
+
164
+    /**
165
+     * @return string
166
+     */
167
+    public function getPrefix() {
168
+        return $this->tablePrefix;
169
+    }
170
+
171
+    /**
172
+     * Initializes a new instance of the Connection class.
173
+     *
174
+     * @param array $params  The connection parameters.
175
+     * @param \Doctrine\DBAL\Driver $driver
176
+     * @param \Doctrine\DBAL\Configuration $config
177
+     * @param \Doctrine\Common\EventManager $eventManager
178
+     * @throws \Exception
179
+     */
180
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
181
+        EventManager $eventManager = null) {
182
+        if (!isset($params['adapter'])) {
183
+            throw new \Exception('adapter not set');
184
+        }
185
+        if (!isset($params['tablePrefix'])) {
186
+            throw new \Exception('tablePrefix not set');
187
+        }
188
+        /**
189
+         * @psalm-suppress InternalMethod
190
+         */
191
+        parent::__construct($params, $driver, $config, $eventManager);
192
+        $this->adapter = new $params['adapter']($this);
193
+        $this->tablePrefix = $params['tablePrefix'];
194
+
195
+        $this->systemConfig = \OC::$server->getSystemConfig();
196
+        $this->logger = \OC::$server->getLogger();
197
+    }
198
+
199
+    /**
200
+     * Prepares an SQL statement.
201
+     *
202
+     * @param string $statement The SQL statement to prepare.
203
+     * @param int|null $limit
204
+     * @param int|null $offset
205
+     *
206
+     * @return Statement The prepared statement.
207
+     * @throws Exception
208
+     */
209
+    public function prepare($statement, $limit = null, $offset = null): Statement {
210
+        if ($limit === -1 || $limit === null) {
211
+            $limit = null;
212
+        } else {
213
+            $limit = (int) $limit;
214
+        }
215
+        if ($offset !== null) {
216
+            $offset = (int) $offset;
217
+        }
218
+        if (!is_null($limit)) {
219
+            $platform = $this->getDatabasePlatform();
220
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
221
+        }
222
+        $statement = $this->replaceTablePrefix($statement);
223
+        $statement = $this->adapter->fixupStatement($statement);
224
+
225
+        return parent::prepare($statement);
226
+    }
227
+
228
+    /**
229
+     * Executes an, optionally parametrized, SQL query.
230
+     *
231
+     * If the query is parametrized, a prepared statement is used.
232
+     * If an SQLLogger is configured, the execution is logged.
233
+     *
234
+     * @param string                                      $sql  The SQL query to execute.
235
+     * @param array                                       $params The parameters to bind to the query, if any.
236
+     * @param array                                       $types  The types the previous parameters are in.
237
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
238
+     *
239
+     * @return Result The executed statement.
240
+     *
241
+     * @throws \Doctrine\DBAL\Exception
242
+     */
243
+    public function executeQuery(string $sql, array $params = [], $types = [], QueryCacheProfile $qcp = null): Result {
244
+        $sql = $this->replaceTablePrefix($sql);
245
+        $sql = $this->adapter->fixupStatement($sql);
246
+        $this->queriesExecuted++;
247
+        $this->logQueryToFile($sql);
248
+        return parent::executeQuery($sql, $params, $types, $qcp);
249
+    }
250
+
251
+    /**
252
+     * @throws Exception
253
+     */
254
+    public function executeUpdate(string $sql, array $params = [], array $types = []): int {
255
+        $sql = $this->replaceTablePrefix($sql);
256
+        $sql = $this->adapter->fixupStatement($sql);
257
+        $this->queriesExecuted++;
258
+        $this->logQueryToFile($sql);
259
+        return parent::executeUpdate($sql, $params, $types);
260
+    }
261
+
262
+    /**
263
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
264
+     * and returns the number of affected rows.
265
+     *
266
+     * This method supports PDO binding types as well as DBAL mapping types.
267
+     *
268
+     * @param string $sql  The SQL query.
269
+     * @param array  $params The query parameters.
270
+     * @param array  $types  The parameter types.
271
+     *
272
+     * @return int The number of affected rows.
273
+     *
274
+     * @throws \Doctrine\DBAL\Exception
275
+     */
276
+    public function executeStatement($sql, array $params = [], array $types = []): int {
277
+        $sql = $this->replaceTablePrefix($sql);
278
+        $sql = $this->adapter->fixupStatement($sql);
279
+        $this->queriesExecuted++;
280
+        $this->logQueryToFile($sql);
281
+        return parent::executeStatement($sql, $params, $types);
282
+    }
283
+
284
+    protected function logQueryToFile(string $sql): void {
285
+        $logFile = $this->systemConfig->getValue('query_log_file');
286
+        if ($logFile !== '' && is_writable(dirname($logFile)) && (!file_exists($logFile) || is_writable($logFile))) {
287
+            $prefix = '';
288
+            if ($this->systemConfig->getValue('query_log_file_requestid') === 'yes') {
289
+                $prefix .= \OC::$server->get(IRequestId::class)->getId() . "\t";
290
+            }
291
+
292
+            file_put_contents(
293
+                $this->systemConfig->getValue('query_log_file', ''),
294
+                $prefix . $sql . "\n",
295
+                FILE_APPEND
296
+            );
297
+        }
298
+    }
299
+
300
+    /**
301
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
302
+     * depending on the underlying driver.
303
+     *
304
+     * Note: This method may not return a meaningful or consistent result across different drivers,
305
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
306
+     * columns or sequences.
307
+     *
308
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
309
+     *
310
+     * @return string the last inserted ID.
311
+     * @throws Exception
312
+     */
313
+    public function lastInsertId($seqName = null) {
314
+        if ($seqName) {
315
+            $seqName = $this->replaceTablePrefix($seqName);
316
+        }
317
+        return $this->adapter->lastInsertId($seqName);
318
+    }
319
+
320
+    /**
321
+     * @internal
322
+     * @throws Exception
323
+     */
324
+    public function realLastInsertId($seqName = null) {
325
+        return parent::lastInsertId($seqName);
326
+    }
327
+
328
+    /**
329
+     * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
330
+     * it is needed that there is also a unique constraint on the values. Then this method will
331
+     * catch the exception and return 0.
332
+     *
333
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
334
+     * @param array $input data that should be inserted into the table  (column name => value)
335
+     * @param array|null $compare List of values that should be checked for "if not exists"
336
+     *				If this is null or an empty array, all keys of $input will be compared
337
+     *				Please note: text fields (clob) must not be used in the compare array
338
+     * @return int number of inserted rows
339
+     * @throws \Doctrine\DBAL\Exception
340
+     * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
341
+     */
342
+    public function insertIfNotExist($table, $input, array $compare = null) {
343
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
344
+    }
345
+
346
+    public function insertIgnoreConflict(string $table, array $values) : int {
347
+        return $this->adapter->insertIgnoreConflict($table, $values);
348
+    }
349
+
350
+    private function getType($value) {
351
+        if (is_bool($value)) {
352
+            return IQueryBuilder::PARAM_BOOL;
353
+        } elseif (is_int($value)) {
354
+            return IQueryBuilder::PARAM_INT;
355
+        } else {
356
+            return IQueryBuilder::PARAM_STR;
357
+        }
358
+    }
359
+
360
+    /**
361
+     * Insert or update a row value
362
+     *
363
+     * @param string $table
364
+     * @param array $keys (column name => value)
365
+     * @param array $values (column name => value)
366
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
367
+     * @return int number of new rows
368
+     * @throws \Doctrine\DBAL\Exception
369
+     * @throws PreConditionNotMetException
370
+     */
371
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
372
+        try {
373
+            $insertQb = $this->getQueryBuilder();
374
+            $insertQb->insert($table)
375
+                ->values(
376
+                    array_map(function ($value) use ($insertQb) {
377
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
378
+                    }, array_merge($keys, $values))
379
+                );
380
+            return $insertQb->execute();
381
+        } catch (NotNullConstraintViolationException $e) {
382
+            throw $e;
383
+        } catch (ConstraintViolationException $e) {
384
+            // value already exists, try update
385
+            $updateQb = $this->getQueryBuilder();
386
+            $updateQb->update($table);
387
+            foreach ($values as $name => $value) {
388
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
389
+            }
390
+            $where = $updateQb->expr()->andX();
391
+            $whereValues = array_merge($keys, $updatePreconditionValues);
392
+            foreach ($whereValues as $name => $value) {
393
+                if ($value === '') {
394
+                    $where->add($updateQb->expr()->emptyString(
395
+                        $name
396
+                    ));
397
+                } else {
398
+                    $where->add($updateQb->expr()->eq(
399
+                        $name,
400
+                        $updateQb->createNamedParameter($value, $this->getType($value)),
401
+                        $this->getType($value)
402
+                    ));
403
+                }
404
+            }
405
+            $updateQb->where($where);
406
+            $affected = $updateQb->execute();
407
+
408
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
409
+                throw new PreConditionNotMetException();
410
+            }
411
+
412
+            return 0;
413
+        }
414
+    }
415
+
416
+    /**
417
+     * Create an exclusive read+write lock on a table
418
+     *
419
+     * @param string $tableName
420
+     *
421
+     * @throws \BadMethodCallException When trying to acquire a second lock
422
+     * @throws Exception
423
+     * @since 9.1.0
424
+     */
425
+    public function lockTable($tableName) {
426
+        if ($this->lockedTable !== null) {
427
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
428
+        }
429
+
430
+        $tableName = $this->tablePrefix . $tableName;
431
+        $this->lockedTable = $tableName;
432
+        $this->adapter->lockTable($tableName);
433
+    }
434
+
435
+    /**
436
+     * Release a previous acquired lock again
437
+     *
438
+     * @throws Exception
439
+     * @since 9.1.0
440
+     */
441
+    public function unlockTable() {
442
+        $this->adapter->unlockTable();
443
+        $this->lockedTable = null;
444
+    }
445
+
446
+    /**
447
+     * returns the error code and message as a string for logging
448
+     * works with DoctrineException
449
+     * @return string
450
+     */
451
+    public function getError() {
452
+        $msg = $this->errorCode() . ': ';
453
+        $errorInfo = $this->errorInfo();
454
+        if (!empty($errorInfo)) {
455
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
456
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
457
+            $msg .= 'Driver Message = '.$errorInfo[2];
458
+        }
459
+        return $msg;
460
+    }
461
+
462
+    public function errorCode() {
463
+        return -1;
464
+    }
465
+
466
+    public function errorInfo() {
467
+        return [];
468
+    }
469
+
470
+    /**
471
+     * Drop a table from the database if it exists
472
+     *
473
+     * @param string $table table name without the prefix
474
+     *
475
+     * @throws Exception
476
+     */
477
+    public function dropTable($table) {
478
+        $table = $this->tablePrefix . trim($table);
479
+        $schema = $this->getSchemaManager();
480
+        if ($schema->tablesExist([$table])) {
481
+            $schema->dropTable($table);
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Check if a table exists
487
+     *
488
+     * @param string $table table name without the prefix
489
+     *
490
+     * @return bool
491
+     * @throws Exception
492
+     */
493
+    public function tableExists($table) {
494
+        $table = $this->tablePrefix . trim($table);
495
+        $schema = $this->getSchemaManager();
496
+        return $schema->tablesExist([$table]);
497
+    }
498
+
499
+    // internal use
500
+    /**
501
+     * @param string $statement
502
+     * @return string
503
+     */
504
+    protected function replaceTablePrefix($statement) {
505
+        return str_replace('*PREFIX*', $this->tablePrefix, $statement);
506
+    }
507
+
508
+    /**
509
+     * Check if a transaction is active
510
+     *
511
+     * @return bool
512
+     * @since 8.2.0
513
+     */
514
+    public function inTransaction() {
515
+        return $this->getTransactionNestingLevel() > 0;
516
+    }
517
+
518
+    /**
519
+     * Escape a parameter to be used in a LIKE query
520
+     *
521
+     * @param string $param
522
+     * @return string
523
+     */
524
+    public function escapeLikeParameter($param) {
525
+        return addcslashes($param, '\\_%');
526
+    }
527
+
528
+    /**
529
+     * Check whether or not the current database support 4byte wide unicode
530
+     *
531
+     * @return bool
532
+     * @since 11.0.0
533
+     */
534
+    public function supports4ByteText() {
535
+        if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
536
+            return true;
537
+        }
538
+        return $this->getParams()['charset'] === 'utf8mb4';
539
+    }
540
+
541
+
542
+    /**
543
+     * Create the schema of the connected database
544
+     *
545
+     * @return Schema
546
+     * @throws Exception
547
+     */
548
+    public function createSchema() {
549
+        $migrator = $this->getMigrator();
550
+        return $migrator->createSchema();
551
+    }
552
+
553
+    /**
554
+     * Migrate the database to the given schema
555
+     *
556
+     * @param Schema $toSchema
557
+     * @param bool $dryRun If true, will return the sql queries instead of running them.
558
+     *
559
+     * @throws Exception
560
+     *
561
+     * @return string|null Returns a string only if $dryRun is true.
562
+     */
563
+    public function migrateToSchema(Schema $toSchema, bool $dryRun = false) {
564
+        $migrator = $this->getMigrator();
565
+
566
+        if ($dryRun) {
567
+            return $migrator->generateChangeScript($toSchema);
568
+        } else {
569
+            $migrator->migrate($toSchema);
570
+        }
571
+    }
572
+
573
+    private function getMigrator() {
574
+        // TODO properly inject those dependencies
575
+        $random = \OC::$server->getSecureRandom();
576
+        $platform = $this->getDatabasePlatform();
577
+        $config = \OC::$server->getConfig();
578
+        $dispatcher = \OC::$server->getEventDispatcher();
579
+        if ($platform instanceof SqlitePlatform) {
580
+            return new SQLiteMigrator($this, $config, $dispatcher);
581
+        } elseif ($platform instanceof OraclePlatform) {
582
+            return new OracleMigrator($this, $config, $dispatcher);
583
+        } elseif ($platform instanceof MySQLPlatform) {
584
+            return new MySQLMigrator($this, $config, $dispatcher);
585
+        } elseif ($platform instanceof PostgreSQL94Platform) {
586
+            return new PostgreSqlMigrator($this, $config, $dispatcher);
587
+        } else {
588
+            return new Migrator($this, $config, $dispatcher);
589
+        }
590
+    }
591 591
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 			return $status;
96 96
 		} catch (Exception $e) {
97 97
 			// throw a new exception to prevent leaking info from the stacktrace
98
-			throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
98
+			throw new Exception('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
99 99
 		}
100 100
 	}
101 101
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		// 0 is the method where we use `getCallerBacktrace`
156 156
 		// 1 is the target method which uses the method we want to log
157 157
 		if (isset($traces[1])) {
158
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
158
+			return $traces[1]['file'].':'.$traces[1]['line'];
159 159
 		}
160 160
 
161 161
 		return '';
@@ -286,12 +286,12 @@  discard block
 block discarded – undo
286 286
 		if ($logFile !== '' && is_writable(dirname($logFile)) && (!file_exists($logFile) || is_writable($logFile))) {
287 287
 			$prefix = '';
288 288
 			if ($this->systemConfig->getValue('query_log_file_requestid') === 'yes') {
289
-				$prefix .= \OC::$server->get(IRequestId::class)->getId() . "\t";
289
+				$prefix .= \OC::$server->get(IRequestId::class)->getId()."\t";
290 290
 			}
291 291
 
292 292
 			file_put_contents(
293 293
 				$this->systemConfig->getValue('query_log_file', ''),
294
-				$prefix . $sql . "\n",
294
+				$prefix.$sql."\n",
295 295
 				FILE_APPEND
296 296
 			);
297 297
 		}
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 			$insertQb = $this->getQueryBuilder();
374 374
 			$insertQb->insert($table)
375 375
 				->values(
376
-					array_map(function ($value) use ($insertQb) {
376
+					array_map(function($value) use ($insertQb) {
377 377
 						return $insertQb->createNamedParameter($value, $this->getType($value));
378 378
 					}, array_merge($keys, $values))
379 379
 				);
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
428 428
 		}
429 429
 
430
-		$tableName = $this->tablePrefix . $tableName;
430
+		$tableName = $this->tablePrefix.$tableName;
431 431
 		$this->lockedTable = $tableName;
432 432
 		$this->adapter->lockTable($tableName);
433 433
 	}
@@ -449,11 +449,11 @@  discard block
 block discarded – undo
449 449
 	 * @return string
450 450
 	 */
451 451
 	public function getError() {
452
-		$msg = $this->errorCode() . ': ';
452
+		$msg = $this->errorCode().': ';
453 453
 		$errorInfo = $this->errorInfo();
454 454
 		if (!empty($errorInfo)) {
455
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
456
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
455
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
456
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
457 457
 			$msg .= 'Driver Message = '.$errorInfo[2];
458 458
 		}
459 459
 		return $msg;
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 	 * @throws Exception
476 476
 	 */
477 477
 	public function dropTable($table) {
478
-		$table = $this->tablePrefix . trim($table);
478
+		$table = $this->tablePrefix.trim($table);
479 479
 		$schema = $this->getSchemaManager();
480 480
 		if ($schema->tablesExist([$table])) {
481 481
 			$schema->dropTable($table);
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
 	 * @throws Exception
492 492
 	 */
493 493
 	public function tableExists($table) {
494
-		$table = $this->tablePrefix . trim($table);
494
+		$table = $this->tablePrefix.trim($table);
495 495
 		$schema = $this->getSchemaManager();
496 496
 		return $schema->tablesExist([$table]);
497 497
 	}
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +2095 added lines, -2095 removed lines patch added patch discarded remove patch
@@ -270,2104 +270,2104 @@
 block discarded – undo
270 270
  */
271 271
 class Server extends ServerContainer implements IServerContainer {
272 272
 
273
-	/** @var string */
274
-	private $webRoot;
275
-
276
-	/**
277
-	 * @param string $webRoot
278
-	 * @param \OC\Config $config
279
-	 */
280
-	public function __construct($webRoot, \OC\Config $config) {
281
-		parent::__construct();
282
-		$this->webRoot = $webRoot;
283
-
284
-		// To find out if we are running from CLI or not
285
-		$this->registerParameter('isCLI', \OC::$CLI);
286
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
287
-
288
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
289
-			return $c;
290
-		});
291
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
292
-			return $c;
293
-		});
294
-
295
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
296
-		/** @deprecated 19.0.0 */
297
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
298
-
299
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
300
-		/** @deprecated 19.0.0 */
301
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
302
-
303
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
304
-		/** @deprecated 19.0.0 */
305
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
306
-
307
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
308
-		/** @deprecated 19.0.0 */
309
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
310
-
311
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
312
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
313
-
314
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
315
-
316
-		$this->registerService(View::class, function (Server $c) {
317
-			return new View();
318
-		}, false);
319
-
320
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
321
-			return new PreviewManager(
322
-				$c->get(\OCP\IConfig::class),
323
-				$c->get(IRootFolder::class),
324
-				new \OC\Preview\Storage\Root(
325
-					$c->get(IRootFolder::class),
326
-					$c->get(SystemConfig::class)
327
-				),
328
-				$c->get(SymfonyAdapter::class),
329
-				$c->get(GeneratorHelper::class),
330
-				$c->get(ISession::class)->get('user_id'),
331
-				$c->get(Coordinator::class),
332
-				$c->get(IServerContainer::class)
333
-			);
334
-		});
335
-		/** @deprecated 19.0.0 */
336
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
337
-
338
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
339
-			return new \OC\Preview\Watcher(
340
-				new \OC\Preview\Storage\Root(
341
-					$c->get(IRootFolder::class),
342
-					$c->get(SystemConfig::class)
343
-				)
344
-			);
345
-		});
346
-
347
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
348
-			$view = new View();
349
-			$util = new Encryption\Util(
350
-				$view,
351
-				$c->get(IUserManager::class),
352
-				$c->get(IGroupManager::class),
353
-				$c->get(\OCP\IConfig::class)
354
-			);
355
-			return new Encryption\Manager(
356
-				$c->get(\OCP\IConfig::class),
357
-				$c->get(ILogger::class),
358
-				$c->getL10N('core'),
359
-				new View(),
360
-				$util,
361
-				new ArrayCache()
362
-			);
363
-		});
364
-		/** @deprecated 19.0.0 */
365
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
366
-
367
-		/** @deprecated 21.0.0 */
368
-		$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
369
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
370
-			$util = new Encryption\Util(
371
-				new View(),
372
-				$c->get(IUserManager::class),
373
-				$c->get(IGroupManager::class),
374
-				$c->get(\OCP\IConfig::class)
375
-			);
376
-			return new Encryption\File(
377
-				$util,
378
-				$c->get(IRootFolder::class),
379
-				$c->get(\OCP\Share\IManager::class)
380
-			);
381
-		});
382
-
383
-		/** @deprecated 21.0.0 */
384
-		$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
385
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
386
-			$view = new View();
387
-			$util = new Encryption\Util(
388
-				$view,
389
-				$c->get(IUserManager::class),
390
-				$c->get(IGroupManager::class),
391
-				$c->get(\OCP\IConfig::class)
392
-			);
393
-
394
-			return new Encryption\Keys\Storage(
395
-				$view,
396
-				$util,
397
-				$c->get(ICrypto::class),
398
-				$c->get(\OCP\IConfig::class)
399
-			);
400
-		});
401
-		/** @deprecated 20.0.0 */
402
-		$this->registerDeprecatedAlias('TagMapper', TagMapper::class);
403
-
404
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
405
-		/** @deprecated 19.0.0 */
406
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
407
-
408
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
409
-			/** @var \OCP\IConfig $config */
410
-			$config = $c->get(\OCP\IConfig::class);
411
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
412
-			return new $factoryClass($this);
413
-		});
414
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
415
-			return $c->get('SystemTagManagerFactory')->getManager();
416
-		});
417
-		/** @deprecated 19.0.0 */
418
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
419
-
420
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
421
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
422
-		});
423
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
424
-			$manager = \OC\Files\Filesystem::getMountManager(null);
425
-			$view = new View();
426
-			$root = new Root(
427
-				$manager,
428
-				$view,
429
-				null,
430
-				$c->get(IUserMountCache::class),
431
-				$this->get(ILogger::class),
432
-				$this->get(IUserManager::class),
433
-				$this->get(IEventDispatcher::class),
434
-			);
435
-
436
-			$previewConnector = new \OC\Preview\WatcherConnector(
437
-				$root,
438
-				$c->get(SystemConfig::class)
439
-			);
440
-			$previewConnector->connectWatcher();
441
-
442
-			return $root;
443
-		});
444
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
445
-			return new HookConnector(
446
-				$c->get(IRootFolder::class),
447
-				new View(),
448
-				$c->get(\OC\EventDispatcher\SymfonyAdapter::class),
449
-				$c->get(IEventDispatcher::class)
450
-			);
451
-		});
452
-
453
-		/** @deprecated 19.0.0 */
454
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
455
-
456
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
457
-			return new LazyRoot(function () use ($c) {
458
-				return $c->get('RootFolder');
459
-			});
460
-		});
461
-		/** @deprecated 19.0.0 */
462
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
463
-
464
-		/** @deprecated 19.0.0 */
465
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
466
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
467
-
468
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
469
-			$groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
470
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
471
-				/** @var IEventDispatcher $dispatcher */
472
-				$dispatcher = $this->get(IEventDispatcher::class);
473
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
474
-			});
475
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
476
-				/** @var IEventDispatcher $dispatcher */
477
-				$dispatcher = $this->get(IEventDispatcher::class);
478
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
479
-			});
480
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
481
-				/** @var IEventDispatcher $dispatcher */
482
-				$dispatcher = $this->get(IEventDispatcher::class);
483
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
484
-			});
485
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
486
-				/** @var IEventDispatcher $dispatcher */
487
-				$dispatcher = $this->get(IEventDispatcher::class);
488
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
489
-			});
490
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
491
-				/** @var IEventDispatcher $dispatcher */
492
-				$dispatcher = $this->get(IEventDispatcher::class);
493
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
494
-			});
495
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
496
-				/** @var IEventDispatcher $dispatcher */
497
-				$dispatcher = $this->get(IEventDispatcher::class);
498
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
499
-			});
500
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
501
-				/** @var IEventDispatcher $dispatcher */
502
-				$dispatcher = $this->get(IEventDispatcher::class);
503
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
504
-			});
505
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
506
-				/** @var IEventDispatcher $dispatcher */
507
-				$dispatcher = $this->get(IEventDispatcher::class);
508
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
509
-			});
510
-			return $groupManager;
511
-		});
512
-		/** @deprecated 19.0.0 */
513
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
514
-
515
-		$this->registerService(Store::class, function (ContainerInterface $c) {
516
-			$session = $c->get(ISession::class);
517
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
518
-				$tokenProvider = $c->get(IProvider::class);
519
-			} else {
520
-				$tokenProvider = null;
521
-			}
522
-			$logger = $c->get(LoggerInterface::class);
523
-			return new Store($session, $logger, $tokenProvider);
524
-		});
525
-		$this->registerAlias(IStore::class, Store::class);
526
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
527
-
528
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
529
-			$manager = $c->get(IUserManager::class);
530
-			$session = new \OC\Session\Memory('');
531
-			$timeFactory = new TimeFactory();
532
-			// Token providers might require a working database. This code
533
-			// might however be called when Nextcloud is not yet setup.
534
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
535
-				$provider = $c->get(IProvider::class);
536
-			} else {
537
-				$provider = null;
538
-			}
539
-
540
-			$legacyDispatcher = $c->get(SymfonyAdapter::class);
541
-
542
-			$userSession = new \OC\User\Session(
543
-				$manager,
544
-				$session,
545
-				$timeFactory,
546
-				$provider,
547
-				$c->get(\OCP\IConfig::class),
548
-				$c->get(ISecureRandom::class),
549
-				$c->getLockdownManager(),
550
-				$c->get(ILogger::class),
551
-				$c->get(IEventDispatcher::class)
552
-			);
553
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
554
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
555
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
556
-			});
557
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
558
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
559
-				/** @var \OC\User\User $user */
560
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
561
-			});
562
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
563
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
564
-				/** @var \OC\User\User $user */
565
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
566
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
567
-			});
568
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
569
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
570
-				/** @var \OC\User\User $user */
571
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
572
-			});
573
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
574
-				/** @var \OC\User\User $user */
575
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
576
-
577
-				/** @var IEventDispatcher $dispatcher */
578
-				$dispatcher = $this->get(IEventDispatcher::class);
579
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
580
-			});
581
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
582
-				/** @var \OC\User\User $user */
583
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
584
-
585
-				/** @var IEventDispatcher $dispatcher */
586
-				$dispatcher = $this->get(IEventDispatcher::class);
587
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
588
-			});
589
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
590
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
591
-
592
-				/** @var IEventDispatcher $dispatcher */
593
-				$dispatcher = $this->get(IEventDispatcher::class);
594
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
595
-			});
596
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
597
-				/** @var \OC\User\User $user */
598
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
599
-
600
-				/** @var IEventDispatcher $dispatcher */
601
-				$dispatcher = $this->get(IEventDispatcher::class);
602
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
603
-			});
604
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
605
-				/** @var IEventDispatcher $dispatcher */
606
-				$dispatcher = $this->get(IEventDispatcher::class);
607
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
608
-			});
609
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
610
-				/** @var \OC\User\User $user */
611
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
612
-
613
-				/** @var IEventDispatcher $dispatcher */
614
-				$dispatcher = $this->get(IEventDispatcher::class);
615
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
616
-			});
617
-			$userSession->listen('\OC\User', 'logout', function ($user) {
618
-				\OC_Hook::emit('OC_User', 'logout', []);
619
-
620
-				/** @var IEventDispatcher $dispatcher */
621
-				$dispatcher = $this->get(IEventDispatcher::class);
622
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
623
-			});
624
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
625
-				/** @var IEventDispatcher $dispatcher */
626
-				$dispatcher = $this->get(IEventDispatcher::class);
627
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
628
-			});
629
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
630
-				/** @var \OC\User\User $user */
631
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
632
-
633
-				/** @var IEventDispatcher $dispatcher */
634
-				$dispatcher = $this->get(IEventDispatcher::class);
635
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
636
-			});
637
-			return $userSession;
638
-		});
639
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
640
-		/** @deprecated 19.0.0 */
641
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
642
-
643
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
644
-
645
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
646
-		/** @deprecated 19.0.0 */
647
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
648
-
649
-		/** @deprecated 19.0.0 */
650
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
651
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
652
-
653
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
654
-			return new \OC\SystemConfig($config);
655
-		});
656
-		/** @deprecated 19.0.0 */
657
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
658
-
659
-		/** @deprecated 19.0.0 */
660
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
661
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
662
-
663
-		$this->registerService(IFactory::class, function (Server $c) {
664
-			return new \OC\L10N\Factory(
665
-				$c->get(\OCP\IConfig::class),
666
-				$c->getRequest(),
667
-				$c->get(IUserSession::class),
668
-				\OC::$SERVERROOT
669
-			);
670
-		});
671
-		/** @deprecated 19.0.0 */
672
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
673
-
674
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
675
-		/** @deprecated 19.0.0 */
676
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
677
-
678
-		/** @deprecated 19.0.0 */
679
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
680
-		/** @deprecated 19.0.0 */
681
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
682
-
683
-		$this->registerService(ICache::class, function ($c) {
684
-			return new Cache\File();
685
-		});
686
-		/** @deprecated 19.0.0 */
687
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
688
-
689
-		$this->registerService(Factory::class, function (Server $c) {
690
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
691
-				ArrayCache::class,
692
-				ArrayCache::class,
693
-				ArrayCache::class
694
-			);
695
-			/** @var \OCP\IConfig $config */
696
-			$config = $c->get(\OCP\IConfig::class);
697
-
698
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
699
-				if (!$config->getSystemValueBool('log_query')) {
700
-					$v = \OC_App::getAppVersions();
701
-				} else {
702
-					// If the log_query is enabled, we can not get the app versions
703
-					// as that does a query, which will be logged and the logging
704
-					// depends on redis and here we are back again in the same function.
705
-					$v = [
706
-						'log_query' => 'enabled',
707
-					];
708
-				}
709
-				$v['core'] = implode(',', \OC_Util::getVersion());
710
-				$version = implode(',', $v);
711
-				$instanceId = \OC_Util::getInstanceId();
712
-				$path = \OC::$SERVERROOT;
713
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
714
-				return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
715
-					$config->getSystemValue('memcache.local', null),
716
-					$config->getSystemValue('memcache.distributed', null),
717
-					$config->getSystemValue('memcache.locking', null),
718
-					$config->getSystemValueString('redis_log_file')
719
-				);
720
-			}
721
-			return $arrayCacheFactory;
722
-		});
723
-		/** @deprecated 19.0.0 */
724
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
725
-		$this->registerAlias(ICacheFactory::class, Factory::class);
726
-
727
-		$this->registerService('RedisFactory', function (Server $c) {
728
-			$systemConfig = $c->get(SystemConfig::class);
729
-			return new RedisFactory($systemConfig, $c->getEventLogger());
730
-		});
731
-
732
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
733
-			$l10n = $this->get(IFactory::class)->get('lib');
734
-			return new \OC\Activity\Manager(
735
-				$c->getRequest(),
736
-				$c->get(IUserSession::class),
737
-				$c->get(\OCP\IConfig::class),
738
-				$c->get(IValidator::class),
739
-				$l10n
740
-			);
741
-		});
742
-		/** @deprecated 19.0.0 */
743
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
744
-
745
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
746
-			return new \OC\Activity\EventMerger(
747
-				$c->getL10N('lib')
748
-			);
749
-		});
750
-		$this->registerAlias(IValidator::class, Validator::class);
751
-
752
-		$this->registerService(AvatarManager::class, function (Server $c) {
753
-			return new AvatarManager(
754
-				$c->get(IUserSession::class),
755
-				$c->get(\OC\User\Manager::class),
756
-				$c->getAppDataDir('avatar'),
757
-				$c->getL10N('lib'),
758
-				$c->get(LoggerInterface::class),
759
-				$c->get(\OCP\IConfig::class),
760
-				$c->get(IAccountManager::class),
761
-				$c->get(KnownUserService::class)
762
-			);
763
-		});
764
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
765
-		/** @deprecated 19.0.0 */
766
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
767
-
768
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
769
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
770
-
771
-		$this->registerService(\OC\Log::class, function (Server $c) {
772
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
773
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
774
-			$logger = $factory->get($logType);
775
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
776
-
777
-			return new Log($logger, $this->get(SystemConfig::class), null, $registry);
778
-		});
779
-		$this->registerAlias(ILogger::class, \OC\Log::class);
780
-		/** @deprecated 19.0.0 */
781
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
782
-		// PSR-3 logger
783
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
784
-
785
-		$this->registerService(ILogFactory::class, function (Server $c) {
786
-			return new LogFactory($c, $this->get(SystemConfig::class));
787
-		});
788
-
789
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
790
-		/** @deprecated 19.0.0 */
791
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
792
-
793
-		$this->registerService(Router::class, function (Server $c) {
794
-			$cacheFactory = $c->get(ICacheFactory::class);
795
-			$logger = $c->get(ILogger::class);
796
-			if ($cacheFactory->isLocalCacheAvailable()) {
797
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
798
-			} else {
799
-				$router = new \OC\Route\Router($logger);
800
-			}
801
-			return $router;
802
-		});
803
-		$this->registerAlias(IRouter::class, Router::class);
804
-		/** @deprecated 19.0.0 */
805
-		$this->registerDeprecatedAlias('Router', IRouter::class);
806
-
807
-		$this->registerAlias(ISearch::class, Search::class);
808
-		/** @deprecated 19.0.0 */
809
-		$this->registerDeprecatedAlias('Search', ISearch::class);
810
-
811
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
812
-			$cacheFactory = $c->get(ICacheFactory::class);
813
-			if ($cacheFactory->isAvailable()) {
814
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
815
-					$this->get(ICacheFactory::class),
816
-					new \OC\AppFramework\Utility\TimeFactory()
817
-				);
818
-			} else {
819
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
820
-					$c->get(IDBConnection::class),
821
-					new \OC\AppFramework\Utility\TimeFactory()
822
-				);
823
-			}
824
-
825
-			return $backend;
826
-		});
827
-
828
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
829
-		/** @deprecated 19.0.0 */
830
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
831
-
832
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
833
-
834
-		$this->registerAlias(ICrypto::class, Crypto::class);
835
-		/** @deprecated 19.0.0 */
836
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
837
-
838
-		$this->registerAlias(IHasher::class, Hasher::class);
839
-		/** @deprecated 19.0.0 */
840
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
841
-
842
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
843
-		/** @deprecated 19.0.0 */
844
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
845
-
846
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
847
-		$this->registerService(Connection::class, function (Server $c) {
848
-			$systemConfig = $c->get(SystemConfig::class);
849
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
850
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
851
-			if (!$factory->isValidType($type)) {
852
-				throw new \OC\DatabaseException('Invalid database type');
853
-			}
854
-			$connectionParams = $factory->createConnectionParams();
855
-			$connection = $factory->getConnection($type, $connectionParams);
856
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
857
-			return $connection;
858
-		});
859
-		/** @deprecated 19.0.0 */
860
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
861
-
862
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
863
-		$this->registerAlias(IClientService::class, ClientService::class);
864
-		$this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
865
-			return new LocalAddressChecker(
866
-				$c->get(ILogger::class),
867
-			);
868
-		});
869
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
870
-			return new NegativeDnsCache(
871
-				$c->get(ICacheFactory::class),
872
-			);
873
-		});
874
-		$this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
875
-			return new DnsPinMiddleware(
876
-				$c->get(NegativeDnsCache::class),
877
-				$c->get(LocalAddressChecker::class)
878
-			);
879
-		});
880
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
881
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
882
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
883
-		});
884
-		/** @deprecated 19.0.0 */
885
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
886
-
887
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
888
-			$queryLogger = new QueryLogger();
889
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
890
-				// In debug mode, module is being activated by default
891
-				$queryLogger->activate();
892
-			}
893
-			return $queryLogger;
894
-		});
895
-		/** @deprecated 19.0.0 */
896
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
897
-
898
-		/** @deprecated 19.0.0 */
899
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
900
-		$this->registerAlias(ITempManager::class, TempManager::class);
901
-
902
-		$this->registerService(AppManager::class, function (ContainerInterface $c) {
903
-			// TODO: use auto-wiring
904
-			return new \OC\App\AppManager(
905
-				$c->get(IUserSession::class),
906
-				$c->get(\OCP\IConfig::class),
907
-				$c->get(\OC\AppConfig::class),
908
-				$c->get(IGroupManager::class),
909
-				$c->get(ICacheFactory::class),
910
-				$c->get(SymfonyAdapter::class),
911
-				$c->get(LoggerInterface::class)
912
-			);
913
-		});
914
-		/** @deprecated 19.0.0 */
915
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
916
-		$this->registerAlias(IAppManager::class, AppManager::class);
917
-
918
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
919
-		/** @deprecated 19.0.0 */
920
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
921
-
922
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
923
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
924
-
925
-			return new DateTimeFormatter(
926
-				$c->get(IDateTimeZone::class)->getTimeZone(),
927
-				$c->getL10N('lib', $language)
928
-			);
929
-		});
930
-		/** @deprecated 19.0.0 */
931
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
932
-
933
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
934
-			$mountCache = new UserMountCache(
935
-				$c->get(IDBConnection::class),
936
-				$c->get(IUserManager::class),
937
-				$c->get(ILogger::class)
938
-			);
939
-			$listener = new UserMountCacheListener($mountCache);
940
-			$listener->listen($c->get(IUserManager::class));
941
-			return $mountCache;
942
-		});
943
-		/** @deprecated 19.0.0 */
944
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
945
-
946
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
947
-			$loader = \OC\Files\Filesystem::getLoader();
948
-			$mountCache = $c->get(IUserMountCache::class);
949
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
950
-
951
-			// builtin providers
952
-
953
-			$config = $c->get(\OCP\IConfig::class);
954
-			$logger = $c->get(ILogger::class);
955
-			$manager->registerProvider(new CacheMountProvider($config));
956
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
957
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
958
-			$manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
959
-			$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
960
-
961
-			return $manager;
962
-		});
963
-		/** @deprecated 19.0.0 */
964
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
965
-
966
-		/** @deprecated 20.0.0 */
967
-		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
968
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
969
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
970
-			if ($busClass) {
971
-				[$app, $class] = explode('::', $busClass, 2);
972
-				if ($c->get(IAppManager::class)->isInstalled($app)) {
973
-					\OC_App::loadApp($app);
974
-					return $c->get($class);
975
-				} else {
976
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
977
-				}
978
-			} else {
979
-				$jobList = $c->get(IJobList::class);
980
-				return new CronBus($jobList);
981
-			}
982
-		});
983
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
984
-		/** @deprecated 20.0.0 */
985
-		$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
986
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
987
-		/** @deprecated 19.0.0 */
988
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
989
-		$this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
990
-			// IConfig and IAppManager requires a working database. This code
991
-			// might however be called when ownCloud is not yet setup.
992
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
993
-				$config = $c->get(\OCP\IConfig::class);
994
-				$appManager = $c->get(IAppManager::class);
995
-			} else {
996
-				$config = null;
997
-				$appManager = null;
998
-			}
999
-
1000
-			return new Checker(
1001
-				new EnvironmentHelper(),
1002
-				new FileAccessHelper(),
1003
-				new AppLocator(),
1004
-				$config,
1005
-				$c->get(ICacheFactory::class),
1006
-				$appManager,
1007
-				$c->get(IMimeTypeDetector::class)
1008
-			);
1009
-		});
1010
-		$this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1011
-			if (isset($this['urlParams'])) {
1012
-				$urlParams = $this['urlParams'];
1013
-			} else {
1014
-				$urlParams = [];
1015
-			}
1016
-
1017
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1018
-				&& in_array('fakeinput', stream_get_wrappers())
1019
-			) {
1020
-				$stream = 'fakeinput://data';
1021
-			} else {
1022
-				$stream = 'php://input';
1023
-			}
1024
-
1025
-			return new Request(
1026
-				[
1027
-					'get' => $_GET,
1028
-					'post' => $_POST,
1029
-					'files' => $_FILES,
1030
-					'server' => $_SERVER,
1031
-					'env' => $_ENV,
1032
-					'cookies' => $_COOKIE,
1033
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1034
-						? $_SERVER['REQUEST_METHOD']
1035
-						: '',
1036
-					'urlParams' => $urlParams,
1037
-				],
1038
-				$this->get(IRequestId::class),
1039
-				$this->get(\OCP\IConfig::class),
1040
-				$this->get(CsrfTokenManager::class),
1041
-				$stream
1042
-			);
1043
-		});
1044
-		/** @deprecated 19.0.0 */
1045
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1046
-
1047
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
1048
-			return new RequestId(
1049
-				$_SERVER['UNIQUE_ID'] ?? '',
1050
-				$this->get(ISecureRandom::class)
1051
-			);
1052
-		});
1053
-
1054
-		$this->registerService(IMailer::class, function (Server $c) {
1055
-			return new Mailer(
1056
-				$c->get(\OCP\IConfig::class),
1057
-				$c->get(ILogger::class),
1058
-				$c->get(Defaults::class),
1059
-				$c->get(IURLGenerator::class),
1060
-				$c->getL10N('lib'),
1061
-				$c->get(IEventDispatcher::class),
1062
-				$c->get(IFactory::class)
1063
-			);
1064
-		});
1065
-		/** @deprecated 19.0.0 */
1066
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1067
-
1068
-		/** @deprecated 21.0.0 */
1069
-		$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1070
-
1071
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1072
-			$config = $c->get(\OCP\IConfig::class);
1073
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1074
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
1075
-				return new NullLDAPProviderFactory($this);
1076
-			}
1077
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1078
-			return new $factoryClass($this);
1079
-		});
1080
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1081
-			$factory = $c->get(ILDAPProviderFactory::class);
1082
-			return $factory->getLDAPProvider();
1083
-		});
1084
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1085
-			$ini = $c->get(IniGetWrapper::class);
1086
-			$config = $c->get(\OCP\IConfig::class);
1087
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1088
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1089
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1090
-				$memcacheFactory = $c->get(ICacheFactory::class);
1091
-				$memcache = $memcacheFactory->createLocking('lock');
1092
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1093
-					return new MemcacheLockingProvider($memcache, $ttl);
1094
-				}
1095
-				return new DBLockingProvider(
1096
-					$c->get(IDBConnection::class),
1097
-					$c->get(ILogger::class),
1098
-					new TimeFactory(),
1099
-					$ttl,
1100
-					!\OC::$CLI
1101
-				);
1102
-			}
1103
-			return new NoopLockingProvider();
1104
-		});
1105
-		/** @deprecated 19.0.0 */
1106
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1107
-
1108
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
1109
-		$this->registerService(SetupManager::class, function ($c) {
1110
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
1111
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1112
-		});
1113
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1114
-		/** @deprecated 19.0.0 */
1115
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1116
-
1117
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1118
-			return new \OC\Files\Type\Detection(
1119
-				$c->get(IURLGenerator::class),
1120
-				$c->get(ILogger::class),
1121
-				\OC::$configDir,
1122
-				\OC::$SERVERROOT . '/resources/config/'
1123
-			);
1124
-		});
1125
-		/** @deprecated 19.0.0 */
1126
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1127
-
1128
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1129
-		/** @deprecated 19.0.0 */
1130
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1131
-		$this->registerService(BundleFetcher::class, function () {
1132
-			return new BundleFetcher($this->getL10N('lib'));
1133
-		});
1134
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1135
-		/** @deprecated 19.0.0 */
1136
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1137
-
1138
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1139
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1140
-			$manager->registerCapability(function () use ($c) {
1141
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1142
-			});
1143
-			$manager->registerCapability(function () use ($c) {
1144
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1145
-			});
1146
-			return $manager;
1147
-		});
1148
-		/** @deprecated 19.0.0 */
1149
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1150
-
1151
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1152
-			$config = $c->get(\OCP\IConfig::class);
1153
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1154
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1155
-			$factory = new $factoryClass($this);
1156
-			$manager = $factory->getManager();
1157
-
1158
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1159
-				$manager = $c->get(IUserManager::class);
1160
-				$user = $manager->get($id);
1161
-				if (is_null($user)) {
1162
-					$l = $c->getL10N('core');
1163
-					$displayName = $l->t('Unknown user');
1164
-				} else {
1165
-					$displayName = $user->getDisplayName();
1166
-				}
1167
-				return $displayName;
1168
-			});
1169
-
1170
-			return $manager;
1171
-		});
1172
-		/** @deprecated 19.0.0 */
1173
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1174
-
1175
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1176
-		$this->registerService('ThemingDefaults', function (Server $c) {
1177
-			/*
273
+    /** @var string */
274
+    private $webRoot;
275
+
276
+    /**
277
+     * @param string $webRoot
278
+     * @param \OC\Config $config
279
+     */
280
+    public function __construct($webRoot, \OC\Config $config) {
281
+        parent::__construct();
282
+        $this->webRoot = $webRoot;
283
+
284
+        // To find out if we are running from CLI or not
285
+        $this->registerParameter('isCLI', \OC::$CLI);
286
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
287
+
288
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
289
+            return $c;
290
+        });
291
+        $this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
292
+            return $c;
293
+        });
294
+
295
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
296
+        /** @deprecated 19.0.0 */
297
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
298
+
299
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
300
+        /** @deprecated 19.0.0 */
301
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
302
+
303
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
304
+        /** @deprecated 19.0.0 */
305
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
306
+
307
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
308
+        /** @deprecated 19.0.0 */
309
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
310
+
311
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
312
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
313
+
314
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
315
+
316
+        $this->registerService(View::class, function (Server $c) {
317
+            return new View();
318
+        }, false);
319
+
320
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
321
+            return new PreviewManager(
322
+                $c->get(\OCP\IConfig::class),
323
+                $c->get(IRootFolder::class),
324
+                new \OC\Preview\Storage\Root(
325
+                    $c->get(IRootFolder::class),
326
+                    $c->get(SystemConfig::class)
327
+                ),
328
+                $c->get(SymfonyAdapter::class),
329
+                $c->get(GeneratorHelper::class),
330
+                $c->get(ISession::class)->get('user_id'),
331
+                $c->get(Coordinator::class),
332
+                $c->get(IServerContainer::class)
333
+            );
334
+        });
335
+        /** @deprecated 19.0.0 */
336
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
337
+
338
+        $this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
339
+            return new \OC\Preview\Watcher(
340
+                new \OC\Preview\Storage\Root(
341
+                    $c->get(IRootFolder::class),
342
+                    $c->get(SystemConfig::class)
343
+                )
344
+            );
345
+        });
346
+
347
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
348
+            $view = new View();
349
+            $util = new Encryption\Util(
350
+                $view,
351
+                $c->get(IUserManager::class),
352
+                $c->get(IGroupManager::class),
353
+                $c->get(\OCP\IConfig::class)
354
+            );
355
+            return new Encryption\Manager(
356
+                $c->get(\OCP\IConfig::class),
357
+                $c->get(ILogger::class),
358
+                $c->getL10N('core'),
359
+                new View(),
360
+                $util,
361
+                new ArrayCache()
362
+            );
363
+        });
364
+        /** @deprecated 19.0.0 */
365
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
366
+
367
+        /** @deprecated 21.0.0 */
368
+        $this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
369
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
370
+            $util = new Encryption\Util(
371
+                new View(),
372
+                $c->get(IUserManager::class),
373
+                $c->get(IGroupManager::class),
374
+                $c->get(\OCP\IConfig::class)
375
+            );
376
+            return new Encryption\File(
377
+                $util,
378
+                $c->get(IRootFolder::class),
379
+                $c->get(\OCP\Share\IManager::class)
380
+            );
381
+        });
382
+
383
+        /** @deprecated 21.0.0 */
384
+        $this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
385
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
386
+            $view = new View();
387
+            $util = new Encryption\Util(
388
+                $view,
389
+                $c->get(IUserManager::class),
390
+                $c->get(IGroupManager::class),
391
+                $c->get(\OCP\IConfig::class)
392
+            );
393
+
394
+            return new Encryption\Keys\Storage(
395
+                $view,
396
+                $util,
397
+                $c->get(ICrypto::class),
398
+                $c->get(\OCP\IConfig::class)
399
+            );
400
+        });
401
+        /** @deprecated 20.0.0 */
402
+        $this->registerDeprecatedAlias('TagMapper', TagMapper::class);
403
+
404
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
405
+        /** @deprecated 19.0.0 */
406
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
407
+
408
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
409
+            /** @var \OCP\IConfig $config */
410
+            $config = $c->get(\OCP\IConfig::class);
411
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
412
+            return new $factoryClass($this);
413
+        });
414
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
415
+            return $c->get('SystemTagManagerFactory')->getManager();
416
+        });
417
+        /** @deprecated 19.0.0 */
418
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
419
+
420
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
421
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
422
+        });
423
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
424
+            $manager = \OC\Files\Filesystem::getMountManager(null);
425
+            $view = new View();
426
+            $root = new Root(
427
+                $manager,
428
+                $view,
429
+                null,
430
+                $c->get(IUserMountCache::class),
431
+                $this->get(ILogger::class),
432
+                $this->get(IUserManager::class),
433
+                $this->get(IEventDispatcher::class),
434
+            );
435
+
436
+            $previewConnector = new \OC\Preview\WatcherConnector(
437
+                $root,
438
+                $c->get(SystemConfig::class)
439
+            );
440
+            $previewConnector->connectWatcher();
441
+
442
+            return $root;
443
+        });
444
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
445
+            return new HookConnector(
446
+                $c->get(IRootFolder::class),
447
+                new View(),
448
+                $c->get(\OC\EventDispatcher\SymfonyAdapter::class),
449
+                $c->get(IEventDispatcher::class)
450
+            );
451
+        });
452
+
453
+        /** @deprecated 19.0.0 */
454
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
455
+
456
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
457
+            return new LazyRoot(function () use ($c) {
458
+                return $c->get('RootFolder');
459
+            });
460
+        });
461
+        /** @deprecated 19.0.0 */
462
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
463
+
464
+        /** @deprecated 19.0.0 */
465
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
466
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
467
+
468
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
469
+            $groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
470
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
471
+                /** @var IEventDispatcher $dispatcher */
472
+                $dispatcher = $this->get(IEventDispatcher::class);
473
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
474
+            });
475
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
476
+                /** @var IEventDispatcher $dispatcher */
477
+                $dispatcher = $this->get(IEventDispatcher::class);
478
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
479
+            });
480
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
481
+                /** @var IEventDispatcher $dispatcher */
482
+                $dispatcher = $this->get(IEventDispatcher::class);
483
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
484
+            });
485
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
486
+                /** @var IEventDispatcher $dispatcher */
487
+                $dispatcher = $this->get(IEventDispatcher::class);
488
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
489
+            });
490
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
491
+                /** @var IEventDispatcher $dispatcher */
492
+                $dispatcher = $this->get(IEventDispatcher::class);
493
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
494
+            });
495
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
496
+                /** @var IEventDispatcher $dispatcher */
497
+                $dispatcher = $this->get(IEventDispatcher::class);
498
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
499
+            });
500
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
501
+                /** @var IEventDispatcher $dispatcher */
502
+                $dispatcher = $this->get(IEventDispatcher::class);
503
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
504
+            });
505
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
506
+                /** @var IEventDispatcher $dispatcher */
507
+                $dispatcher = $this->get(IEventDispatcher::class);
508
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
509
+            });
510
+            return $groupManager;
511
+        });
512
+        /** @deprecated 19.0.0 */
513
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
514
+
515
+        $this->registerService(Store::class, function (ContainerInterface $c) {
516
+            $session = $c->get(ISession::class);
517
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
518
+                $tokenProvider = $c->get(IProvider::class);
519
+            } else {
520
+                $tokenProvider = null;
521
+            }
522
+            $logger = $c->get(LoggerInterface::class);
523
+            return new Store($session, $logger, $tokenProvider);
524
+        });
525
+        $this->registerAlias(IStore::class, Store::class);
526
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
527
+
528
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
529
+            $manager = $c->get(IUserManager::class);
530
+            $session = new \OC\Session\Memory('');
531
+            $timeFactory = new TimeFactory();
532
+            // Token providers might require a working database. This code
533
+            // might however be called when Nextcloud is not yet setup.
534
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
535
+                $provider = $c->get(IProvider::class);
536
+            } else {
537
+                $provider = null;
538
+            }
539
+
540
+            $legacyDispatcher = $c->get(SymfonyAdapter::class);
541
+
542
+            $userSession = new \OC\User\Session(
543
+                $manager,
544
+                $session,
545
+                $timeFactory,
546
+                $provider,
547
+                $c->get(\OCP\IConfig::class),
548
+                $c->get(ISecureRandom::class),
549
+                $c->getLockdownManager(),
550
+                $c->get(ILogger::class),
551
+                $c->get(IEventDispatcher::class)
552
+            );
553
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
554
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
555
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
556
+            });
557
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
558
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
559
+                /** @var \OC\User\User $user */
560
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
561
+            });
562
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
563
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
564
+                /** @var \OC\User\User $user */
565
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
566
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
567
+            });
568
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
569
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
570
+                /** @var \OC\User\User $user */
571
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
572
+            });
573
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
574
+                /** @var \OC\User\User $user */
575
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
576
+
577
+                /** @var IEventDispatcher $dispatcher */
578
+                $dispatcher = $this->get(IEventDispatcher::class);
579
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
580
+            });
581
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
582
+                /** @var \OC\User\User $user */
583
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
584
+
585
+                /** @var IEventDispatcher $dispatcher */
586
+                $dispatcher = $this->get(IEventDispatcher::class);
587
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
588
+            });
589
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
590
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
591
+
592
+                /** @var IEventDispatcher $dispatcher */
593
+                $dispatcher = $this->get(IEventDispatcher::class);
594
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
595
+            });
596
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
597
+                /** @var \OC\User\User $user */
598
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
599
+
600
+                /** @var IEventDispatcher $dispatcher */
601
+                $dispatcher = $this->get(IEventDispatcher::class);
602
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
603
+            });
604
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
605
+                /** @var IEventDispatcher $dispatcher */
606
+                $dispatcher = $this->get(IEventDispatcher::class);
607
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
608
+            });
609
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
610
+                /** @var \OC\User\User $user */
611
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
612
+
613
+                /** @var IEventDispatcher $dispatcher */
614
+                $dispatcher = $this->get(IEventDispatcher::class);
615
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
616
+            });
617
+            $userSession->listen('\OC\User', 'logout', function ($user) {
618
+                \OC_Hook::emit('OC_User', 'logout', []);
619
+
620
+                /** @var IEventDispatcher $dispatcher */
621
+                $dispatcher = $this->get(IEventDispatcher::class);
622
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
623
+            });
624
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
625
+                /** @var IEventDispatcher $dispatcher */
626
+                $dispatcher = $this->get(IEventDispatcher::class);
627
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
628
+            });
629
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
630
+                /** @var \OC\User\User $user */
631
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
632
+
633
+                /** @var IEventDispatcher $dispatcher */
634
+                $dispatcher = $this->get(IEventDispatcher::class);
635
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
636
+            });
637
+            return $userSession;
638
+        });
639
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
640
+        /** @deprecated 19.0.0 */
641
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
642
+
643
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
644
+
645
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
646
+        /** @deprecated 19.0.0 */
647
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
648
+
649
+        /** @deprecated 19.0.0 */
650
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
651
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
652
+
653
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
654
+            return new \OC\SystemConfig($config);
655
+        });
656
+        /** @deprecated 19.0.0 */
657
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
658
+
659
+        /** @deprecated 19.0.0 */
660
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
661
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
662
+
663
+        $this->registerService(IFactory::class, function (Server $c) {
664
+            return new \OC\L10N\Factory(
665
+                $c->get(\OCP\IConfig::class),
666
+                $c->getRequest(),
667
+                $c->get(IUserSession::class),
668
+                \OC::$SERVERROOT
669
+            );
670
+        });
671
+        /** @deprecated 19.0.0 */
672
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
673
+
674
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
675
+        /** @deprecated 19.0.0 */
676
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
677
+
678
+        /** @deprecated 19.0.0 */
679
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
680
+        /** @deprecated 19.0.0 */
681
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
682
+
683
+        $this->registerService(ICache::class, function ($c) {
684
+            return new Cache\File();
685
+        });
686
+        /** @deprecated 19.0.0 */
687
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
688
+
689
+        $this->registerService(Factory::class, function (Server $c) {
690
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
691
+                ArrayCache::class,
692
+                ArrayCache::class,
693
+                ArrayCache::class
694
+            );
695
+            /** @var \OCP\IConfig $config */
696
+            $config = $c->get(\OCP\IConfig::class);
697
+
698
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
699
+                if (!$config->getSystemValueBool('log_query')) {
700
+                    $v = \OC_App::getAppVersions();
701
+                } else {
702
+                    // If the log_query is enabled, we can not get the app versions
703
+                    // as that does a query, which will be logged and the logging
704
+                    // depends on redis and here we are back again in the same function.
705
+                    $v = [
706
+                        'log_query' => 'enabled',
707
+                    ];
708
+                }
709
+                $v['core'] = implode(',', \OC_Util::getVersion());
710
+                $version = implode(',', $v);
711
+                $instanceId = \OC_Util::getInstanceId();
712
+                $path = \OC::$SERVERROOT;
713
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
714
+                return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
715
+                    $config->getSystemValue('memcache.local', null),
716
+                    $config->getSystemValue('memcache.distributed', null),
717
+                    $config->getSystemValue('memcache.locking', null),
718
+                    $config->getSystemValueString('redis_log_file')
719
+                );
720
+            }
721
+            return $arrayCacheFactory;
722
+        });
723
+        /** @deprecated 19.0.0 */
724
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
725
+        $this->registerAlias(ICacheFactory::class, Factory::class);
726
+
727
+        $this->registerService('RedisFactory', function (Server $c) {
728
+            $systemConfig = $c->get(SystemConfig::class);
729
+            return new RedisFactory($systemConfig, $c->getEventLogger());
730
+        });
731
+
732
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
733
+            $l10n = $this->get(IFactory::class)->get('lib');
734
+            return new \OC\Activity\Manager(
735
+                $c->getRequest(),
736
+                $c->get(IUserSession::class),
737
+                $c->get(\OCP\IConfig::class),
738
+                $c->get(IValidator::class),
739
+                $l10n
740
+            );
741
+        });
742
+        /** @deprecated 19.0.0 */
743
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
744
+
745
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
746
+            return new \OC\Activity\EventMerger(
747
+                $c->getL10N('lib')
748
+            );
749
+        });
750
+        $this->registerAlias(IValidator::class, Validator::class);
751
+
752
+        $this->registerService(AvatarManager::class, function (Server $c) {
753
+            return new AvatarManager(
754
+                $c->get(IUserSession::class),
755
+                $c->get(\OC\User\Manager::class),
756
+                $c->getAppDataDir('avatar'),
757
+                $c->getL10N('lib'),
758
+                $c->get(LoggerInterface::class),
759
+                $c->get(\OCP\IConfig::class),
760
+                $c->get(IAccountManager::class),
761
+                $c->get(KnownUserService::class)
762
+            );
763
+        });
764
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
765
+        /** @deprecated 19.0.0 */
766
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
767
+
768
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
769
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
770
+
771
+        $this->registerService(\OC\Log::class, function (Server $c) {
772
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
773
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
774
+            $logger = $factory->get($logType);
775
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
776
+
777
+            return new Log($logger, $this->get(SystemConfig::class), null, $registry);
778
+        });
779
+        $this->registerAlias(ILogger::class, \OC\Log::class);
780
+        /** @deprecated 19.0.0 */
781
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
782
+        // PSR-3 logger
783
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
784
+
785
+        $this->registerService(ILogFactory::class, function (Server $c) {
786
+            return new LogFactory($c, $this->get(SystemConfig::class));
787
+        });
788
+
789
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
790
+        /** @deprecated 19.0.0 */
791
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
792
+
793
+        $this->registerService(Router::class, function (Server $c) {
794
+            $cacheFactory = $c->get(ICacheFactory::class);
795
+            $logger = $c->get(ILogger::class);
796
+            if ($cacheFactory->isLocalCacheAvailable()) {
797
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
798
+            } else {
799
+                $router = new \OC\Route\Router($logger);
800
+            }
801
+            return $router;
802
+        });
803
+        $this->registerAlias(IRouter::class, Router::class);
804
+        /** @deprecated 19.0.0 */
805
+        $this->registerDeprecatedAlias('Router', IRouter::class);
806
+
807
+        $this->registerAlias(ISearch::class, Search::class);
808
+        /** @deprecated 19.0.0 */
809
+        $this->registerDeprecatedAlias('Search', ISearch::class);
810
+
811
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
812
+            $cacheFactory = $c->get(ICacheFactory::class);
813
+            if ($cacheFactory->isAvailable()) {
814
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
815
+                    $this->get(ICacheFactory::class),
816
+                    new \OC\AppFramework\Utility\TimeFactory()
817
+                );
818
+            } else {
819
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
820
+                    $c->get(IDBConnection::class),
821
+                    new \OC\AppFramework\Utility\TimeFactory()
822
+                );
823
+            }
824
+
825
+            return $backend;
826
+        });
827
+
828
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
829
+        /** @deprecated 19.0.0 */
830
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
831
+
832
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
833
+
834
+        $this->registerAlias(ICrypto::class, Crypto::class);
835
+        /** @deprecated 19.0.0 */
836
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
837
+
838
+        $this->registerAlias(IHasher::class, Hasher::class);
839
+        /** @deprecated 19.0.0 */
840
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
841
+
842
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
843
+        /** @deprecated 19.0.0 */
844
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
845
+
846
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
847
+        $this->registerService(Connection::class, function (Server $c) {
848
+            $systemConfig = $c->get(SystemConfig::class);
849
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
850
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
851
+            if (!$factory->isValidType($type)) {
852
+                throw new \OC\DatabaseException('Invalid database type');
853
+            }
854
+            $connectionParams = $factory->createConnectionParams();
855
+            $connection = $factory->getConnection($type, $connectionParams);
856
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
857
+            return $connection;
858
+        });
859
+        /** @deprecated 19.0.0 */
860
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
861
+
862
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
863
+        $this->registerAlias(IClientService::class, ClientService::class);
864
+        $this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
865
+            return new LocalAddressChecker(
866
+                $c->get(ILogger::class),
867
+            );
868
+        });
869
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
870
+            return new NegativeDnsCache(
871
+                $c->get(ICacheFactory::class),
872
+            );
873
+        });
874
+        $this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
875
+            return new DnsPinMiddleware(
876
+                $c->get(NegativeDnsCache::class),
877
+                $c->get(LocalAddressChecker::class)
878
+            );
879
+        });
880
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
881
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
882
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
883
+        });
884
+        /** @deprecated 19.0.0 */
885
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
886
+
887
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
888
+            $queryLogger = new QueryLogger();
889
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
890
+                // In debug mode, module is being activated by default
891
+                $queryLogger->activate();
892
+            }
893
+            return $queryLogger;
894
+        });
895
+        /** @deprecated 19.0.0 */
896
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
897
+
898
+        /** @deprecated 19.0.0 */
899
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
900
+        $this->registerAlias(ITempManager::class, TempManager::class);
901
+
902
+        $this->registerService(AppManager::class, function (ContainerInterface $c) {
903
+            // TODO: use auto-wiring
904
+            return new \OC\App\AppManager(
905
+                $c->get(IUserSession::class),
906
+                $c->get(\OCP\IConfig::class),
907
+                $c->get(\OC\AppConfig::class),
908
+                $c->get(IGroupManager::class),
909
+                $c->get(ICacheFactory::class),
910
+                $c->get(SymfonyAdapter::class),
911
+                $c->get(LoggerInterface::class)
912
+            );
913
+        });
914
+        /** @deprecated 19.0.0 */
915
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
916
+        $this->registerAlias(IAppManager::class, AppManager::class);
917
+
918
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
919
+        /** @deprecated 19.0.0 */
920
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
921
+
922
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
923
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
924
+
925
+            return new DateTimeFormatter(
926
+                $c->get(IDateTimeZone::class)->getTimeZone(),
927
+                $c->getL10N('lib', $language)
928
+            );
929
+        });
930
+        /** @deprecated 19.0.0 */
931
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
932
+
933
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
934
+            $mountCache = new UserMountCache(
935
+                $c->get(IDBConnection::class),
936
+                $c->get(IUserManager::class),
937
+                $c->get(ILogger::class)
938
+            );
939
+            $listener = new UserMountCacheListener($mountCache);
940
+            $listener->listen($c->get(IUserManager::class));
941
+            return $mountCache;
942
+        });
943
+        /** @deprecated 19.0.0 */
944
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
945
+
946
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
947
+            $loader = \OC\Files\Filesystem::getLoader();
948
+            $mountCache = $c->get(IUserMountCache::class);
949
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
950
+
951
+            // builtin providers
952
+
953
+            $config = $c->get(\OCP\IConfig::class);
954
+            $logger = $c->get(ILogger::class);
955
+            $manager->registerProvider(new CacheMountProvider($config));
956
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
957
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
958
+            $manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
959
+            $manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
960
+
961
+            return $manager;
962
+        });
963
+        /** @deprecated 19.0.0 */
964
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
965
+
966
+        /** @deprecated 20.0.0 */
967
+        $this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
968
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
969
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
970
+            if ($busClass) {
971
+                [$app, $class] = explode('::', $busClass, 2);
972
+                if ($c->get(IAppManager::class)->isInstalled($app)) {
973
+                    \OC_App::loadApp($app);
974
+                    return $c->get($class);
975
+                } else {
976
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
977
+                }
978
+            } else {
979
+                $jobList = $c->get(IJobList::class);
980
+                return new CronBus($jobList);
981
+            }
982
+        });
983
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
984
+        /** @deprecated 20.0.0 */
985
+        $this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
986
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
987
+        /** @deprecated 19.0.0 */
988
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
989
+        $this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
990
+            // IConfig and IAppManager requires a working database. This code
991
+            // might however be called when ownCloud is not yet setup.
992
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
993
+                $config = $c->get(\OCP\IConfig::class);
994
+                $appManager = $c->get(IAppManager::class);
995
+            } else {
996
+                $config = null;
997
+                $appManager = null;
998
+            }
999
+
1000
+            return new Checker(
1001
+                new EnvironmentHelper(),
1002
+                new FileAccessHelper(),
1003
+                new AppLocator(),
1004
+                $config,
1005
+                $c->get(ICacheFactory::class),
1006
+                $appManager,
1007
+                $c->get(IMimeTypeDetector::class)
1008
+            );
1009
+        });
1010
+        $this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1011
+            if (isset($this['urlParams'])) {
1012
+                $urlParams = $this['urlParams'];
1013
+            } else {
1014
+                $urlParams = [];
1015
+            }
1016
+
1017
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1018
+                && in_array('fakeinput', stream_get_wrappers())
1019
+            ) {
1020
+                $stream = 'fakeinput://data';
1021
+            } else {
1022
+                $stream = 'php://input';
1023
+            }
1024
+
1025
+            return new Request(
1026
+                [
1027
+                    'get' => $_GET,
1028
+                    'post' => $_POST,
1029
+                    'files' => $_FILES,
1030
+                    'server' => $_SERVER,
1031
+                    'env' => $_ENV,
1032
+                    'cookies' => $_COOKIE,
1033
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1034
+                        ? $_SERVER['REQUEST_METHOD']
1035
+                        : '',
1036
+                    'urlParams' => $urlParams,
1037
+                ],
1038
+                $this->get(IRequestId::class),
1039
+                $this->get(\OCP\IConfig::class),
1040
+                $this->get(CsrfTokenManager::class),
1041
+                $stream
1042
+            );
1043
+        });
1044
+        /** @deprecated 19.0.0 */
1045
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1046
+
1047
+        $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
1048
+            return new RequestId(
1049
+                $_SERVER['UNIQUE_ID'] ?? '',
1050
+                $this->get(ISecureRandom::class)
1051
+            );
1052
+        });
1053
+
1054
+        $this->registerService(IMailer::class, function (Server $c) {
1055
+            return new Mailer(
1056
+                $c->get(\OCP\IConfig::class),
1057
+                $c->get(ILogger::class),
1058
+                $c->get(Defaults::class),
1059
+                $c->get(IURLGenerator::class),
1060
+                $c->getL10N('lib'),
1061
+                $c->get(IEventDispatcher::class),
1062
+                $c->get(IFactory::class)
1063
+            );
1064
+        });
1065
+        /** @deprecated 19.0.0 */
1066
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1067
+
1068
+        /** @deprecated 21.0.0 */
1069
+        $this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1070
+
1071
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1072
+            $config = $c->get(\OCP\IConfig::class);
1073
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1074
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
1075
+                return new NullLDAPProviderFactory($this);
1076
+            }
1077
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1078
+            return new $factoryClass($this);
1079
+        });
1080
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1081
+            $factory = $c->get(ILDAPProviderFactory::class);
1082
+            return $factory->getLDAPProvider();
1083
+        });
1084
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1085
+            $ini = $c->get(IniGetWrapper::class);
1086
+            $config = $c->get(\OCP\IConfig::class);
1087
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1088
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1089
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1090
+                $memcacheFactory = $c->get(ICacheFactory::class);
1091
+                $memcache = $memcacheFactory->createLocking('lock');
1092
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1093
+                    return new MemcacheLockingProvider($memcache, $ttl);
1094
+                }
1095
+                return new DBLockingProvider(
1096
+                    $c->get(IDBConnection::class),
1097
+                    $c->get(ILogger::class),
1098
+                    new TimeFactory(),
1099
+                    $ttl,
1100
+                    !\OC::$CLI
1101
+                );
1102
+            }
1103
+            return new NoopLockingProvider();
1104
+        });
1105
+        /** @deprecated 19.0.0 */
1106
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1107
+
1108
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
1109
+        $this->registerService(SetupManager::class, function ($c) {
1110
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
1111
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1112
+        });
1113
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1114
+        /** @deprecated 19.0.0 */
1115
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1116
+
1117
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1118
+            return new \OC\Files\Type\Detection(
1119
+                $c->get(IURLGenerator::class),
1120
+                $c->get(ILogger::class),
1121
+                \OC::$configDir,
1122
+                \OC::$SERVERROOT . '/resources/config/'
1123
+            );
1124
+        });
1125
+        /** @deprecated 19.0.0 */
1126
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1127
+
1128
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
1129
+        /** @deprecated 19.0.0 */
1130
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1131
+        $this->registerService(BundleFetcher::class, function () {
1132
+            return new BundleFetcher($this->getL10N('lib'));
1133
+        });
1134
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1135
+        /** @deprecated 19.0.0 */
1136
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1137
+
1138
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1139
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1140
+            $manager->registerCapability(function () use ($c) {
1141
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1142
+            });
1143
+            $manager->registerCapability(function () use ($c) {
1144
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1145
+            });
1146
+            return $manager;
1147
+        });
1148
+        /** @deprecated 19.0.0 */
1149
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1150
+
1151
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1152
+            $config = $c->get(\OCP\IConfig::class);
1153
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1154
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1155
+            $factory = new $factoryClass($this);
1156
+            $manager = $factory->getManager();
1157
+
1158
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1159
+                $manager = $c->get(IUserManager::class);
1160
+                $user = $manager->get($id);
1161
+                if (is_null($user)) {
1162
+                    $l = $c->getL10N('core');
1163
+                    $displayName = $l->t('Unknown user');
1164
+                } else {
1165
+                    $displayName = $user->getDisplayName();
1166
+                }
1167
+                return $displayName;
1168
+            });
1169
+
1170
+            return $manager;
1171
+        });
1172
+        /** @deprecated 19.0.0 */
1173
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1174
+
1175
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1176
+        $this->registerService('ThemingDefaults', function (Server $c) {
1177
+            /*
1178 1178
 			 * Dark magic for autoloader.
1179 1179
 			 * If we do a class_exists it will try to load the class which will
1180 1180
 			 * make composer cache the result. Resulting in errors when enabling
1181 1181
 			 * the theming app.
1182 1182
 			 */
1183
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1184
-			if (isset($prefixes['OCA\\Theming\\'])) {
1185
-				$classExists = true;
1186
-			} else {
1187
-				$classExists = false;
1188
-			}
1189
-
1190
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1191
-				return new ThemingDefaults(
1192
-					$c->get(\OCP\IConfig::class),
1193
-					$c->getL10N('theming'),
1194
-					$c->get(IURLGenerator::class),
1195
-					$c->get(ICacheFactory::class),
1196
-					new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming')),
1197
-					new ImageManager(
1198
-						$c->get(\OCP\IConfig::class),
1199
-						$c->getAppDataDir('theming'),
1200
-						$c->get(IURLGenerator::class),
1201
-						$this->get(ICacheFactory::class),
1202
-						$this->get(ILogger::class),
1203
-						$this->get(ITempManager::class)
1204
-					),
1205
-					$c->get(IAppManager::class),
1206
-					$c->get(INavigationManager::class)
1207
-				);
1208
-			}
1209
-			return new \OC_Defaults();
1210
-		});
1211
-		$this->registerService(JSCombiner::class, function (Server $c) {
1212
-			return new JSCombiner(
1213
-				$c->getAppDataDir('js'),
1214
-				$c->get(IURLGenerator::class),
1215
-				$this->get(ICacheFactory::class),
1216
-				$c->get(SystemConfig::class),
1217
-				$c->get(ILogger::class)
1218
-			);
1219
-		});
1220
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1221
-		/** @deprecated 19.0.0 */
1222
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1223
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1224
-
1225
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1226
-			// FIXME: Instantiated here due to cyclic dependency
1227
-			$request = new Request(
1228
-				[
1229
-					'get' => $_GET,
1230
-					'post' => $_POST,
1231
-					'files' => $_FILES,
1232
-					'server' => $_SERVER,
1233
-					'env' => $_ENV,
1234
-					'cookies' => $_COOKIE,
1235
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1236
-						? $_SERVER['REQUEST_METHOD']
1237
-						: null,
1238
-				],
1239
-				$c->get(IRequestId::class),
1240
-				$c->get(\OCP\IConfig::class)
1241
-			);
1242
-
1243
-			return new CryptoWrapper(
1244
-				$c->get(\OCP\IConfig::class),
1245
-				$c->get(ICrypto::class),
1246
-				$c->get(ISecureRandom::class),
1247
-				$request
1248
-			);
1249
-		});
1250
-		/** @deprecated 19.0.0 */
1251
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1252
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1253
-			return new SessionStorage($c->get(ISession::class));
1254
-		});
1255
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1256
-		/** @deprecated 19.0.0 */
1257
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1258
-
1259
-		$this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1260
-			$config = $c->get(\OCP\IConfig::class);
1261
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1262
-			/** @var \OCP\Share\IProviderFactory $factory */
1263
-			$factory = new $factoryClass($this);
1264
-
1265
-			$manager = new \OC\Share20\Manager(
1266
-				$c->get(ILogger::class),
1267
-				$c->get(\OCP\IConfig::class),
1268
-				$c->get(ISecureRandom::class),
1269
-				$c->get(IHasher::class),
1270
-				$c->get(IMountManager::class),
1271
-				$c->get(IGroupManager::class),
1272
-				$c->getL10N('lib'),
1273
-				$c->get(IFactory::class),
1274
-				$factory,
1275
-				$c->get(IUserManager::class),
1276
-				$c->get(IRootFolder::class),
1277
-				$c->get(SymfonyAdapter::class),
1278
-				$c->get(IMailer::class),
1279
-				$c->get(IURLGenerator::class),
1280
-				$c->get('ThemingDefaults'),
1281
-				$c->get(IEventDispatcher::class),
1282
-				$c->get(IUserSession::class),
1283
-				$c->get(KnownUserService::class)
1284
-			);
1285
-
1286
-			return $manager;
1287
-		});
1288
-		/** @deprecated 19.0.0 */
1289
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1290
-
1291
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1292
-			$instance = new Collaboration\Collaborators\Search($c);
1293
-
1294
-			// register default plugins
1295
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1296
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1297
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1298
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1299
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1300
-
1301
-			return $instance;
1302
-		});
1303
-		/** @deprecated 19.0.0 */
1304
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1305
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1306
-
1307
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1308
-
1309
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1310
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1311
-
1312
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1313
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1314
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1315
-			return new \OC\Files\AppData\Factory(
1316
-				$c->get(IRootFolder::class),
1317
-				$c->get(SystemConfig::class)
1318
-			);
1319
-		});
1320
-
1321
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1322
-			return new LockdownManager(function () use ($c) {
1323
-				return $c->get(ISession::class);
1324
-			});
1325
-		});
1326
-
1327
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1328
-			return new DiscoveryService(
1329
-				$c->get(ICacheFactory::class),
1330
-				$c->get(IClientService::class)
1331
-			);
1332
-		});
1333
-
1334
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1335
-			return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1336
-		});
1337
-
1338
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1339
-
1340
-		$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1341
-			return new CloudFederationProviderManager(
1342
-				$c->get(IAppManager::class),
1343
-				$c->get(IClientService::class),
1344
-				$c->get(ICloudIdManager::class),
1345
-				$c->get(ILogger::class)
1346
-			);
1347
-		});
1348
-
1349
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1350
-			return new CloudFederationFactory();
1351
-		});
1352
-
1353
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1354
-		/** @deprecated 19.0.0 */
1355
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1356
-
1357
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1358
-		/** @deprecated 19.0.0 */
1359
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1360
-
1361
-		$this->registerService(Defaults::class, function (Server $c) {
1362
-			return new Defaults(
1363
-				$c->getThemingDefaults()
1364
-			);
1365
-		});
1366
-		/** @deprecated 19.0.0 */
1367
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1368
-
1369
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1370
-			return $c->get(\OCP\IUserSession::class)->getSession();
1371
-		}, false);
1372
-
1373
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1374
-			return new ShareHelper(
1375
-				$c->get(\OCP\Share\IManager::class)
1376
-			);
1377
-		});
1378
-
1379
-		$this->registerService(Installer::class, function (ContainerInterface $c) {
1380
-			return new Installer(
1381
-				$c->get(AppFetcher::class),
1382
-				$c->get(IClientService::class),
1383
-				$c->get(ITempManager::class),
1384
-				$c->get(LoggerInterface::class),
1385
-				$c->get(\OCP\IConfig::class),
1386
-				\OC::$CLI
1387
-			);
1388
-		});
1389
-
1390
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1391
-			return new ApiFactory($c->get(IClientService::class));
1392
-		});
1393
-
1394
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1395
-			$memcacheFactory = $c->get(ICacheFactory::class);
1396
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1397
-		});
1398
-
1399
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1400
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1401
-
1402
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1403
-
1404
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1405
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1406
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1407
-
1408
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1409
-
1410
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1411
-
1412
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1413
-
1414
-		$this->registerAlias(IBroker::class, Broker::class);
1415
-
1416
-		$this->connectDispatcher();
1417
-	}
1418
-
1419
-	public function boot() {
1420
-		/** @var HookConnector $hookConnector */
1421
-		$hookConnector = $this->get(HookConnector::class);
1422
-		$hookConnector->viewToNode();
1423
-	}
1424
-
1425
-	/**
1426
-	 * @return \OCP\Calendar\IManager
1427
-	 * @deprecated 20.0.0
1428
-	 */
1429
-	public function getCalendarManager() {
1430
-		return $this->get(\OC\Calendar\Manager::class);
1431
-	}
1432
-
1433
-	/**
1434
-	 * @return \OCP\Calendar\Resource\IManager
1435
-	 * @deprecated 20.0.0
1436
-	 */
1437
-	public function getCalendarResourceBackendManager() {
1438
-		return $this->get(\OC\Calendar\Resource\Manager::class);
1439
-	}
1440
-
1441
-	/**
1442
-	 * @return \OCP\Calendar\Room\IManager
1443
-	 * @deprecated 20.0.0
1444
-	 */
1445
-	public function getCalendarRoomBackendManager() {
1446
-		return $this->get(\OC\Calendar\Room\Manager::class);
1447
-	}
1448
-
1449
-	private function connectDispatcher() {
1450
-		$dispatcher = $this->get(SymfonyAdapter::class);
1451
-
1452
-		// Delete avatar on user deletion
1453
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1454
-			$logger = $this->get(ILogger::class);
1455
-			$manager = $this->getAvatarManager();
1456
-			/** @var IUser $user */
1457
-			$user = $e->getSubject();
1458
-
1459
-			try {
1460
-				$avatar = $manager->getAvatar($user->getUID());
1461
-				$avatar->remove();
1462
-			} catch (NotFoundException $e) {
1463
-				// no avatar to remove
1464
-			} catch (\Exception $e) {
1465
-				// Ignore exceptions
1466
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1467
-			}
1468
-		});
1469
-
1470
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1471
-			$manager = $this->getAvatarManager();
1472
-			/** @var IUser $user */
1473
-			$user = $e->getSubject();
1474
-			$feature = $e->getArgument('feature');
1475
-			$oldValue = $e->getArgument('oldValue');
1476
-			$value = $e->getArgument('value');
1477
-
1478
-			// We only change the avatar on display name changes
1479
-			if ($feature !== 'displayName') {
1480
-				return;
1481
-			}
1482
-
1483
-			try {
1484
-				$avatar = $manager->getAvatar($user->getUID());
1485
-				$avatar->userChanged($feature, $oldValue, $value);
1486
-			} catch (NotFoundException $e) {
1487
-				// no avatar to remove
1488
-			}
1489
-		});
1490
-
1491
-		/** @var IEventDispatcher $eventDispatched */
1492
-		$eventDispatched = $this->get(IEventDispatcher::class);
1493
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1494
-		$eventDispatched->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1495
-	}
1496
-
1497
-	/**
1498
-	 * @return \OCP\Contacts\IManager
1499
-	 * @deprecated 20.0.0
1500
-	 */
1501
-	public function getContactsManager() {
1502
-		return $this->get(\OCP\Contacts\IManager::class);
1503
-	}
1504
-
1505
-	/**
1506
-	 * @return \OC\Encryption\Manager
1507
-	 * @deprecated 20.0.0
1508
-	 */
1509
-	public function getEncryptionManager() {
1510
-		return $this->get(\OCP\Encryption\IManager::class);
1511
-	}
1512
-
1513
-	/**
1514
-	 * @return \OC\Encryption\File
1515
-	 * @deprecated 20.0.0
1516
-	 */
1517
-	public function getEncryptionFilesHelper() {
1518
-		return $this->get(IFile::class);
1519
-	}
1520
-
1521
-	/**
1522
-	 * @return \OCP\Encryption\Keys\IStorage
1523
-	 * @deprecated 20.0.0
1524
-	 */
1525
-	public function getEncryptionKeyStorage() {
1526
-		return $this->get(IStorage::class);
1527
-	}
1528
-
1529
-	/**
1530
-	 * The current request object holding all information about the request
1531
-	 * currently being processed is returned from this method.
1532
-	 * In case the current execution was not initiated by a web request null is returned
1533
-	 *
1534
-	 * @return \OCP\IRequest
1535
-	 * @deprecated 20.0.0
1536
-	 */
1537
-	public function getRequest() {
1538
-		return $this->get(IRequest::class);
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns the preview manager which can create preview images for a given file
1543
-	 *
1544
-	 * @return IPreview
1545
-	 * @deprecated 20.0.0
1546
-	 */
1547
-	public function getPreviewManager() {
1548
-		return $this->get(IPreview::class);
1549
-	}
1550
-
1551
-	/**
1552
-	 * Returns the tag manager which can get and set tags for different object types
1553
-	 *
1554
-	 * @see \OCP\ITagManager::load()
1555
-	 * @return ITagManager
1556
-	 * @deprecated 20.0.0
1557
-	 */
1558
-	public function getTagManager() {
1559
-		return $this->get(ITagManager::class);
1560
-	}
1561
-
1562
-	/**
1563
-	 * Returns the system-tag manager
1564
-	 *
1565
-	 * @return ISystemTagManager
1566
-	 *
1567
-	 * @since 9.0.0
1568
-	 * @deprecated 20.0.0
1569
-	 */
1570
-	public function getSystemTagManager() {
1571
-		return $this->get(ISystemTagManager::class);
1572
-	}
1573
-
1574
-	/**
1575
-	 * Returns the system-tag object mapper
1576
-	 *
1577
-	 * @return ISystemTagObjectMapper
1578
-	 *
1579
-	 * @since 9.0.0
1580
-	 * @deprecated 20.0.0
1581
-	 */
1582
-	public function getSystemTagObjectMapper() {
1583
-		return $this->get(ISystemTagObjectMapper::class);
1584
-	}
1585
-
1586
-	/**
1587
-	 * Returns the avatar manager, used for avatar functionality
1588
-	 *
1589
-	 * @return IAvatarManager
1590
-	 * @deprecated 20.0.0
1591
-	 */
1592
-	public function getAvatarManager() {
1593
-		return $this->get(IAvatarManager::class);
1594
-	}
1595
-
1596
-	/**
1597
-	 * Returns the root folder of ownCloud's data directory
1598
-	 *
1599
-	 * @return IRootFolder
1600
-	 * @deprecated 20.0.0
1601
-	 */
1602
-	public function getRootFolder() {
1603
-		return $this->get(IRootFolder::class);
1604
-	}
1605
-
1606
-	/**
1607
-	 * Returns the root folder of ownCloud's data directory
1608
-	 * This is the lazy variant so this gets only initialized once it
1609
-	 * is actually used.
1610
-	 *
1611
-	 * @return IRootFolder
1612
-	 * @deprecated 20.0.0
1613
-	 */
1614
-	public function getLazyRootFolder() {
1615
-		return $this->get(IRootFolder::class);
1616
-	}
1617
-
1618
-	/**
1619
-	 * Returns a view to ownCloud's files folder
1620
-	 *
1621
-	 * @param string $userId user ID
1622
-	 * @return \OCP\Files\Folder|null
1623
-	 * @deprecated 20.0.0
1624
-	 */
1625
-	public function getUserFolder($userId = null) {
1626
-		if ($userId === null) {
1627
-			$user = $this->get(IUserSession::class)->getUser();
1628
-			if (!$user) {
1629
-				return null;
1630
-			}
1631
-			$userId = $user->getUID();
1632
-		}
1633
-		$root = $this->get(IRootFolder::class);
1634
-		return $root->getUserFolder($userId);
1635
-	}
1636
-
1637
-	/**
1638
-	 * @return \OC\User\Manager
1639
-	 * @deprecated 20.0.0
1640
-	 */
1641
-	public function getUserManager() {
1642
-		return $this->get(IUserManager::class);
1643
-	}
1644
-
1645
-	/**
1646
-	 * @return \OC\Group\Manager
1647
-	 * @deprecated 20.0.0
1648
-	 */
1649
-	public function getGroupManager() {
1650
-		return $this->get(IGroupManager::class);
1651
-	}
1652
-
1653
-	/**
1654
-	 * @return \OC\User\Session
1655
-	 * @deprecated 20.0.0
1656
-	 */
1657
-	public function getUserSession() {
1658
-		return $this->get(IUserSession::class);
1659
-	}
1660
-
1661
-	/**
1662
-	 * @return \OCP\ISession
1663
-	 * @deprecated 20.0.0
1664
-	 */
1665
-	public function getSession() {
1666
-		return $this->get(IUserSession::class)->getSession();
1667
-	}
1668
-
1669
-	/**
1670
-	 * @param \OCP\ISession $session
1671
-	 */
1672
-	public function setSession(\OCP\ISession $session) {
1673
-		$this->get(SessionStorage::class)->setSession($session);
1674
-		$this->get(IUserSession::class)->setSession($session);
1675
-		$this->get(Store::class)->setSession($session);
1676
-	}
1677
-
1678
-	/**
1679
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1680
-	 * @deprecated 20.0.0
1681
-	 */
1682
-	public function getTwoFactorAuthManager() {
1683
-		return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1684
-	}
1685
-
1686
-	/**
1687
-	 * @return \OC\NavigationManager
1688
-	 * @deprecated 20.0.0
1689
-	 */
1690
-	public function getNavigationManager() {
1691
-		return $this->get(INavigationManager::class);
1692
-	}
1693
-
1694
-	/**
1695
-	 * @return \OCP\IConfig
1696
-	 * @deprecated 20.0.0
1697
-	 */
1698
-	public function getConfig() {
1699
-		return $this->get(AllConfig::class);
1700
-	}
1701
-
1702
-	/**
1703
-	 * @return \OC\SystemConfig
1704
-	 * @deprecated 20.0.0
1705
-	 */
1706
-	public function getSystemConfig() {
1707
-		return $this->get(SystemConfig::class);
1708
-	}
1709
-
1710
-	/**
1711
-	 * Returns the app config manager
1712
-	 *
1713
-	 * @return IAppConfig
1714
-	 * @deprecated 20.0.0
1715
-	 */
1716
-	public function getAppConfig() {
1717
-		return $this->get(IAppConfig::class);
1718
-	}
1719
-
1720
-	/**
1721
-	 * @return IFactory
1722
-	 * @deprecated 20.0.0
1723
-	 */
1724
-	public function getL10NFactory() {
1725
-		return $this->get(IFactory::class);
1726
-	}
1727
-
1728
-	/**
1729
-	 * get an L10N instance
1730
-	 *
1731
-	 * @param string $app appid
1732
-	 * @param string $lang
1733
-	 * @return IL10N
1734
-	 * @deprecated 20.0.0
1735
-	 */
1736
-	public function getL10N($app, $lang = null) {
1737
-		return $this->get(IFactory::class)->get($app, $lang);
1738
-	}
1739
-
1740
-	/**
1741
-	 * @return IURLGenerator
1742
-	 * @deprecated 20.0.0
1743
-	 */
1744
-	public function getURLGenerator() {
1745
-		return $this->get(IURLGenerator::class);
1746
-	}
1747
-
1748
-	/**
1749
-	 * @return AppFetcher
1750
-	 * @deprecated 20.0.0
1751
-	 */
1752
-	public function getAppFetcher() {
1753
-		return $this->get(AppFetcher::class);
1754
-	}
1755
-
1756
-	/**
1757
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1758
-	 * getMemCacheFactory() instead.
1759
-	 *
1760
-	 * @return ICache
1761
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1762
-	 */
1763
-	public function getCache() {
1764
-		return $this->get(ICache::class);
1765
-	}
1766
-
1767
-	/**
1768
-	 * Returns an \OCP\CacheFactory instance
1769
-	 *
1770
-	 * @return \OCP\ICacheFactory
1771
-	 * @deprecated 20.0.0
1772
-	 */
1773
-	public function getMemCacheFactory() {
1774
-		return $this->get(ICacheFactory::class);
1775
-	}
1776
-
1777
-	/**
1778
-	 * Returns an \OC\RedisFactory instance
1779
-	 *
1780
-	 * @return \OC\RedisFactory
1781
-	 * @deprecated 20.0.0
1782
-	 */
1783
-	public function getGetRedisFactory() {
1784
-		return $this->get('RedisFactory');
1785
-	}
1786
-
1787
-
1788
-	/**
1789
-	 * Returns the current session
1790
-	 *
1791
-	 * @return \OCP\IDBConnection
1792
-	 * @deprecated 20.0.0
1793
-	 */
1794
-	public function getDatabaseConnection() {
1795
-		return $this->get(IDBConnection::class);
1796
-	}
1797
-
1798
-	/**
1799
-	 * Returns the activity manager
1800
-	 *
1801
-	 * @return \OCP\Activity\IManager
1802
-	 * @deprecated 20.0.0
1803
-	 */
1804
-	public function getActivityManager() {
1805
-		return $this->get(\OCP\Activity\IManager::class);
1806
-	}
1807
-
1808
-	/**
1809
-	 * Returns an job list for controlling background jobs
1810
-	 *
1811
-	 * @return IJobList
1812
-	 * @deprecated 20.0.0
1813
-	 */
1814
-	public function getJobList() {
1815
-		return $this->get(IJobList::class);
1816
-	}
1817
-
1818
-	/**
1819
-	 * Returns a logger instance
1820
-	 *
1821
-	 * @return ILogger
1822
-	 * @deprecated 20.0.0
1823
-	 */
1824
-	public function getLogger() {
1825
-		return $this->get(ILogger::class);
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return ILogFactory
1830
-	 * @throws \OCP\AppFramework\QueryException
1831
-	 * @deprecated 20.0.0
1832
-	 */
1833
-	public function getLogFactory() {
1834
-		return $this->get(ILogFactory::class);
1835
-	}
1836
-
1837
-	/**
1838
-	 * Returns a router for generating and matching urls
1839
-	 *
1840
-	 * @return IRouter
1841
-	 * @deprecated 20.0.0
1842
-	 */
1843
-	public function getRouter() {
1844
-		return $this->get(IRouter::class);
1845
-	}
1846
-
1847
-	/**
1848
-	 * Returns a search instance
1849
-	 *
1850
-	 * @return ISearch
1851
-	 * @deprecated 20.0.0
1852
-	 */
1853
-	public function getSearch() {
1854
-		return $this->get(ISearch::class);
1855
-	}
1856
-
1857
-	/**
1858
-	 * Returns a SecureRandom instance
1859
-	 *
1860
-	 * @return \OCP\Security\ISecureRandom
1861
-	 * @deprecated 20.0.0
1862
-	 */
1863
-	public function getSecureRandom() {
1864
-		return $this->get(ISecureRandom::class);
1865
-	}
1866
-
1867
-	/**
1868
-	 * Returns a Crypto instance
1869
-	 *
1870
-	 * @return ICrypto
1871
-	 * @deprecated 20.0.0
1872
-	 */
1873
-	public function getCrypto() {
1874
-		return $this->get(ICrypto::class);
1875
-	}
1876
-
1877
-	/**
1878
-	 * Returns a Hasher instance
1879
-	 *
1880
-	 * @return IHasher
1881
-	 * @deprecated 20.0.0
1882
-	 */
1883
-	public function getHasher() {
1884
-		return $this->get(IHasher::class);
1885
-	}
1886
-
1887
-	/**
1888
-	 * Returns a CredentialsManager instance
1889
-	 *
1890
-	 * @return ICredentialsManager
1891
-	 * @deprecated 20.0.0
1892
-	 */
1893
-	public function getCredentialsManager() {
1894
-		return $this->get(ICredentialsManager::class);
1895
-	}
1896
-
1897
-	/**
1898
-	 * Get the certificate manager
1899
-	 *
1900
-	 * @return \OCP\ICertificateManager
1901
-	 */
1902
-	public function getCertificateManager() {
1903
-		return $this->get(ICertificateManager::class);
1904
-	}
1905
-
1906
-	/**
1907
-	 * Returns an instance of the HTTP client service
1908
-	 *
1909
-	 * @return IClientService
1910
-	 * @deprecated 20.0.0
1911
-	 */
1912
-	public function getHTTPClientService() {
1913
-		return $this->get(IClientService::class);
1914
-	}
1915
-
1916
-	/**
1917
-	 * Create a new event source
1918
-	 *
1919
-	 * @return \OCP\IEventSource
1920
-	 * @deprecated 20.0.0
1921
-	 */
1922
-	public function createEventSource() {
1923
-		return new \OC_EventSource();
1924
-	}
1925
-
1926
-	/**
1927
-	 * Get the active event logger
1928
-	 *
1929
-	 * The returned logger only logs data when debug mode is enabled
1930
-	 *
1931
-	 * @return IEventLogger
1932
-	 * @deprecated 20.0.0
1933
-	 */
1934
-	public function getEventLogger() {
1935
-		return $this->get(IEventLogger::class);
1936
-	}
1937
-
1938
-	/**
1939
-	 * Get the active query logger
1940
-	 *
1941
-	 * The returned logger only logs data when debug mode is enabled
1942
-	 *
1943
-	 * @return IQueryLogger
1944
-	 * @deprecated 20.0.0
1945
-	 */
1946
-	public function getQueryLogger() {
1947
-		return $this->get(IQueryLogger::class);
1948
-	}
1949
-
1950
-	/**
1951
-	 * Get the manager for temporary files and folders
1952
-	 *
1953
-	 * @return \OCP\ITempManager
1954
-	 * @deprecated 20.0.0
1955
-	 */
1956
-	public function getTempManager() {
1957
-		return $this->get(ITempManager::class);
1958
-	}
1959
-
1960
-	/**
1961
-	 * Get the app manager
1962
-	 *
1963
-	 * @return \OCP\App\IAppManager
1964
-	 * @deprecated 20.0.0
1965
-	 */
1966
-	public function getAppManager() {
1967
-		return $this->get(IAppManager::class);
1968
-	}
1969
-
1970
-	/**
1971
-	 * Creates a new mailer
1972
-	 *
1973
-	 * @return IMailer
1974
-	 * @deprecated 20.0.0
1975
-	 */
1976
-	public function getMailer() {
1977
-		return $this->get(IMailer::class);
1978
-	}
1979
-
1980
-	/**
1981
-	 * Get the webroot
1982
-	 *
1983
-	 * @return string
1984
-	 * @deprecated 20.0.0
1985
-	 */
1986
-	public function getWebRoot() {
1987
-		return $this->webRoot;
1988
-	}
1989
-
1990
-	/**
1991
-	 * @return \OC\OCSClient
1992
-	 * @deprecated 20.0.0
1993
-	 */
1994
-	public function getOcsClient() {
1995
-		return $this->get('OcsClient');
1996
-	}
1997
-
1998
-	/**
1999
-	 * @return IDateTimeZone
2000
-	 * @deprecated 20.0.0
2001
-	 */
2002
-	public function getDateTimeZone() {
2003
-		return $this->get(IDateTimeZone::class);
2004
-	}
2005
-
2006
-	/**
2007
-	 * @return IDateTimeFormatter
2008
-	 * @deprecated 20.0.0
2009
-	 */
2010
-	public function getDateTimeFormatter() {
2011
-		return $this->get(IDateTimeFormatter::class);
2012
-	}
2013
-
2014
-	/**
2015
-	 * @return IMountProviderCollection
2016
-	 * @deprecated 20.0.0
2017
-	 */
2018
-	public function getMountProviderCollection() {
2019
-		return $this->get(IMountProviderCollection::class);
2020
-	}
2021
-
2022
-	/**
2023
-	 * Get the IniWrapper
2024
-	 *
2025
-	 * @return IniGetWrapper
2026
-	 * @deprecated 20.0.0
2027
-	 */
2028
-	public function getIniWrapper() {
2029
-		return $this->get(IniGetWrapper::class);
2030
-	}
2031
-
2032
-	/**
2033
-	 * @return \OCP\Command\IBus
2034
-	 * @deprecated 20.0.0
2035
-	 */
2036
-	public function getCommandBus() {
2037
-		return $this->get(IBus::class);
2038
-	}
2039
-
2040
-	/**
2041
-	 * Get the trusted domain helper
2042
-	 *
2043
-	 * @return TrustedDomainHelper
2044
-	 * @deprecated 20.0.0
2045
-	 */
2046
-	public function getTrustedDomainHelper() {
2047
-		return $this->get(TrustedDomainHelper::class);
2048
-	}
2049
-
2050
-	/**
2051
-	 * Get the locking provider
2052
-	 *
2053
-	 * @return ILockingProvider
2054
-	 * @since 8.1.0
2055
-	 * @deprecated 20.0.0
2056
-	 */
2057
-	public function getLockingProvider() {
2058
-		return $this->get(ILockingProvider::class);
2059
-	}
2060
-
2061
-	/**
2062
-	 * @return IMountManager
2063
-	 * @deprecated 20.0.0
2064
-	 **/
2065
-	public function getMountManager() {
2066
-		return $this->get(IMountManager::class);
2067
-	}
2068
-
2069
-	/**
2070
-	 * @return IUserMountCache
2071
-	 * @deprecated 20.0.0
2072
-	 */
2073
-	public function getUserMountCache() {
2074
-		return $this->get(IUserMountCache::class);
2075
-	}
2076
-
2077
-	/**
2078
-	 * Get the MimeTypeDetector
2079
-	 *
2080
-	 * @return IMimeTypeDetector
2081
-	 * @deprecated 20.0.0
2082
-	 */
2083
-	public function getMimeTypeDetector() {
2084
-		return $this->get(IMimeTypeDetector::class);
2085
-	}
2086
-
2087
-	/**
2088
-	 * Get the MimeTypeLoader
2089
-	 *
2090
-	 * @return IMimeTypeLoader
2091
-	 * @deprecated 20.0.0
2092
-	 */
2093
-	public function getMimeTypeLoader() {
2094
-		return $this->get(IMimeTypeLoader::class);
2095
-	}
2096
-
2097
-	/**
2098
-	 * Get the manager of all the capabilities
2099
-	 *
2100
-	 * @return CapabilitiesManager
2101
-	 * @deprecated 20.0.0
2102
-	 */
2103
-	public function getCapabilitiesManager() {
2104
-		return $this->get(CapabilitiesManager::class);
2105
-	}
2106
-
2107
-	/**
2108
-	 * Get the EventDispatcher
2109
-	 *
2110
-	 * @return EventDispatcherInterface
2111
-	 * @since 8.2.0
2112
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2113
-	 */
2114
-	public function getEventDispatcher() {
2115
-		return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2116
-	}
2117
-
2118
-	/**
2119
-	 * Get the Notification Manager
2120
-	 *
2121
-	 * @return \OCP\Notification\IManager
2122
-	 * @since 8.2.0
2123
-	 * @deprecated 20.0.0
2124
-	 */
2125
-	public function getNotificationManager() {
2126
-		return $this->get(\OCP\Notification\IManager::class);
2127
-	}
2128
-
2129
-	/**
2130
-	 * @return ICommentsManager
2131
-	 * @deprecated 20.0.0
2132
-	 */
2133
-	public function getCommentsManager() {
2134
-		return $this->get(ICommentsManager::class);
2135
-	}
2136
-
2137
-	/**
2138
-	 * @return \OCA\Theming\ThemingDefaults
2139
-	 * @deprecated 20.0.0
2140
-	 */
2141
-	public function getThemingDefaults() {
2142
-		return $this->get('ThemingDefaults');
2143
-	}
2144
-
2145
-	/**
2146
-	 * @return \OC\IntegrityCheck\Checker
2147
-	 * @deprecated 20.0.0
2148
-	 */
2149
-	public function getIntegrityCodeChecker() {
2150
-		return $this->get('IntegrityCodeChecker');
2151
-	}
2152
-
2153
-	/**
2154
-	 * @return \OC\Session\CryptoWrapper
2155
-	 * @deprecated 20.0.0
2156
-	 */
2157
-	public function getSessionCryptoWrapper() {
2158
-		return $this->get('CryptoWrapper');
2159
-	}
2160
-
2161
-	/**
2162
-	 * @return CsrfTokenManager
2163
-	 * @deprecated 20.0.0
2164
-	 */
2165
-	public function getCsrfTokenManager() {
2166
-		return $this->get(CsrfTokenManager::class);
2167
-	}
2168
-
2169
-	/**
2170
-	 * @return Throttler
2171
-	 * @deprecated 20.0.0
2172
-	 */
2173
-	public function getBruteForceThrottler() {
2174
-		return $this->get(Throttler::class);
2175
-	}
2176
-
2177
-	/**
2178
-	 * @return IContentSecurityPolicyManager
2179
-	 * @deprecated 20.0.0
2180
-	 */
2181
-	public function getContentSecurityPolicyManager() {
2182
-		return $this->get(ContentSecurityPolicyManager::class);
2183
-	}
2184
-
2185
-	/**
2186
-	 * @return ContentSecurityPolicyNonceManager
2187
-	 * @deprecated 20.0.0
2188
-	 */
2189
-	public function getContentSecurityPolicyNonceManager() {
2190
-		return $this->get(ContentSecurityPolicyNonceManager::class);
2191
-	}
2192
-
2193
-	/**
2194
-	 * Not a public API as of 8.2, wait for 9.0
2195
-	 *
2196
-	 * @return \OCA\Files_External\Service\BackendService
2197
-	 * @deprecated 20.0.0
2198
-	 */
2199
-	public function getStoragesBackendService() {
2200
-		return $this->get(BackendService::class);
2201
-	}
2202
-
2203
-	/**
2204
-	 * Not a public API as of 8.2, wait for 9.0
2205
-	 *
2206
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2207
-	 * @deprecated 20.0.0
2208
-	 */
2209
-	public function getGlobalStoragesService() {
2210
-		return $this->get(GlobalStoragesService::class);
2211
-	}
2212
-
2213
-	/**
2214
-	 * Not a public API as of 8.2, wait for 9.0
2215
-	 *
2216
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2217
-	 * @deprecated 20.0.0
2218
-	 */
2219
-	public function getUserGlobalStoragesService() {
2220
-		return $this->get(UserGlobalStoragesService::class);
2221
-	}
2222
-
2223
-	/**
2224
-	 * Not a public API as of 8.2, wait for 9.0
2225
-	 *
2226
-	 * @return \OCA\Files_External\Service\UserStoragesService
2227
-	 * @deprecated 20.0.0
2228
-	 */
2229
-	public function getUserStoragesService() {
2230
-		return $this->get(UserStoragesService::class);
2231
-	}
2232
-
2233
-	/**
2234
-	 * @return \OCP\Share\IManager
2235
-	 * @deprecated 20.0.0
2236
-	 */
2237
-	public function getShareManager() {
2238
-		return $this->get(\OCP\Share\IManager::class);
2239
-	}
2240
-
2241
-	/**
2242
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2243
-	 * @deprecated 20.0.0
2244
-	 */
2245
-	public function getCollaboratorSearch() {
2246
-		return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2247
-	}
2248
-
2249
-	/**
2250
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2251
-	 * @deprecated 20.0.0
2252
-	 */
2253
-	public function getAutoCompleteManager() {
2254
-		return $this->get(IManager::class);
2255
-	}
2256
-
2257
-	/**
2258
-	 * Returns the LDAP Provider
2259
-	 *
2260
-	 * @return \OCP\LDAP\ILDAPProvider
2261
-	 * @deprecated 20.0.0
2262
-	 */
2263
-	public function getLDAPProvider() {
2264
-		return $this->get('LDAPProvider');
2265
-	}
2266
-
2267
-	/**
2268
-	 * @return \OCP\Settings\IManager
2269
-	 * @deprecated 20.0.0
2270
-	 */
2271
-	public function getSettingsManager() {
2272
-		return $this->get(\OC\Settings\Manager::class);
2273
-	}
2274
-
2275
-	/**
2276
-	 * @return \OCP\Files\IAppData
2277
-	 * @deprecated 20.0.0
2278
-	 */
2279
-	public function getAppDataDir($app) {
2280
-		/** @var \OC\Files\AppData\Factory $factory */
2281
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
2282
-		return $factory->get($app);
2283
-	}
2284
-
2285
-	/**
2286
-	 * @return \OCP\Lockdown\ILockdownManager
2287
-	 * @deprecated 20.0.0
2288
-	 */
2289
-	public function getLockdownManager() {
2290
-		return $this->get('LockdownManager');
2291
-	}
2292
-
2293
-	/**
2294
-	 * @return \OCP\Federation\ICloudIdManager
2295
-	 * @deprecated 20.0.0
2296
-	 */
2297
-	public function getCloudIdManager() {
2298
-		return $this->get(ICloudIdManager::class);
2299
-	}
2300
-
2301
-	/**
2302
-	 * @return \OCP\GlobalScale\IConfig
2303
-	 * @deprecated 20.0.0
2304
-	 */
2305
-	public function getGlobalScaleConfig() {
2306
-		return $this->get(IConfig::class);
2307
-	}
2308
-
2309
-	/**
2310
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2311
-	 * @deprecated 20.0.0
2312
-	 */
2313
-	public function getCloudFederationProviderManager() {
2314
-		return $this->get(ICloudFederationProviderManager::class);
2315
-	}
2316
-
2317
-	/**
2318
-	 * @return \OCP\Remote\Api\IApiFactory
2319
-	 * @deprecated 20.0.0
2320
-	 */
2321
-	public function getRemoteApiFactory() {
2322
-		return $this->get(IApiFactory::class);
2323
-	}
2324
-
2325
-	/**
2326
-	 * @return \OCP\Federation\ICloudFederationFactory
2327
-	 * @deprecated 20.0.0
2328
-	 */
2329
-	public function getCloudFederationFactory() {
2330
-		return $this->get(ICloudFederationFactory::class);
2331
-	}
2332
-
2333
-	/**
2334
-	 * @return \OCP\Remote\IInstanceFactory
2335
-	 * @deprecated 20.0.0
2336
-	 */
2337
-	public function getRemoteInstanceFactory() {
2338
-		return $this->get(IInstanceFactory::class);
2339
-	}
2340
-
2341
-	/**
2342
-	 * @return IStorageFactory
2343
-	 * @deprecated 20.0.0
2344
-	 */
2345
-	public function getStorageFactory() {
2346
-		return $this->get(IStorageFactory::class);
2347
-	}
2348
-
2349
-	/**
2350
-	 * Get the Preview GeneratorHelper
2351
-	 *
2352
-	 * @return GeneratorHelper
2353
-	 * @since 17.0.0
2354
-	 * @deprecated 20.0.0
2355
-	 */
2356
-	public function getGeneratorHelper() {
2357
-		return $this->get(\OC\Preview\GeneratorHelper::class);
2358
-	}
2359
-
2360
-	private function registerDeprecatedAlias(string $alias, string $target) {
2361
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2362
-			try {
2363
-				/** @var ILogger $logger */
2364
-				$logger = $container->get(ILogger::class);
2365
-				$logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2366
-			} catch (ContainerExceptionInterface $e) {
2367
-				// Could not get logger. Continue
2368
-			}
2369
-
2370
-			return $container->get($target);
2371
-		}, false);
2372
-	}
1183
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1184
+            if (isset($prefixes['OCA\\Theming\\'])) {
1185
+                $classExists = true;
1186
+            } else {
1187
+                $classExists = false;
1188
+            }
1189
+
1190
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1191
+                return new ThemingDefaults(
1192
+                    $c->get(\OCP\IConfig::class),
1193
+                    $c->getL10N('theming'),
1194
+                    $c->get(IURLGenerator::class),
1195
+                    $c->get(ICacheFactory::class),
1196
+                    new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming')),
1197
+                    new ImageManager(
1198
+                        $c->get(\OCP\IConfig::class),
1199
+                        $c->getAppDataDir('theming'),
1200
+                        $c->get(IURLGenerator::class),
1201
+                        $this->get(ICacheFactory::class),
1202
+                        $this->get(ILogger::class),
1203
+                        $this->get(ITempManager::class)
1204
+                    ),
1205
+                    $c->get(IAppManager::class),
1206
+                    $c->get(INavigationManager::class)
1207
+                );
1208
+            }
1209
+            return new \OC_Defaults();
1210
+        });
1211
+        $this->registerService(JSCombiner::class, function (Server $c) {
1212
+            return new JSCombiner(
1213
+                $c->getAppDataDir('js'),
1214
+                $c->get(IURLGenerator::class),
1215
+                $this->get(ICacheFactory::class),
1216
+                $c->get(SystemConfig::class),
1217
+                $c->get(ILogger::class)
1218
+            );
1219
+        });
1220
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1221
+        /** @deprecated 19.0.0 */
1222
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1223
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1224
+
1225
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1226
+            // FIXME: Instantiated here due to cyclic dependency
1227
+            $request = new Request(
1228
+                [
1229
+                    'get' => $_GET,
1230
+                    'post' => $_POST,
1231
+                    'files' => $_FILES,
1232
+                    'server' => $_SERVER,
1233
+                    'env' => $_ENV,
1234
+                    'cookies' => $_COOKIE,
1235
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1236
+                        ? $_SERVER['REQUEST_METHOD']
1237
+                        : null,
1238
+                ],
1239
+                $c->get(IRequestId::class),
1240
+                $c->get(\OCP\IConfig::class)
1241
+            );
1242
+
1243
+            return new CryptoWrapper(
1244
+                $c->get(\OCP\IConfig::class),
1245
+                $c->get(ICrypto::class),
1246
+                $c->get(ISecureRandom::class),
1247
+                $request
1248
+            );
1249
+        });
1250
+        /** @deprecated 19.0.0 */
1251
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1252
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1253
+            return new SessionStorage($c->get(ISession::class));
1254
+        });
1255
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1256
+        /** @deprecated 19.0.0 */
1257
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1258
+
1259
+        $this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1260
+            $config = $c->get(\OCP\IConfig::class);
1261
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1262
+            /** @var \OCP\Share\IProviderFactory $factory */
1263
+            $factory = new $factoryClass($this);
1264
+
1265
+            $manager = new \OC\Share20\Manager(
1266
+                $c->get(ILogger::class),
1267
+                $c->get(\OCP\IConfig::class),
1268
+                $c->get(ISecureRandom::class),
1269
+                $c->get(IHasher::class),
1270
+                $c->get(IMountManager::class),
1271
+                $c->get(IGroupManager::class),
1272
+                $c->getL10N('lib'),
1273
+                $c->get(IFactory::class),
1274
+                $factory,
1275
+                $c->get(IUserManager::class),
1276
+                $c->get(IRootFolder::class),
1277
+                $c->get(SymfonyAdapter::class),
1278
+                $c->get(IMailer::class),
1279
+                $c->get(IURLGenerator::class),
1280
+                $c->get('ThemingDefaults'),
1281
+                $c->get(IEventDispatcher::class),
1282
+                $c->get(IUserSession::class),
1283
+                $c->get(KnownUserService::class)
1284
+            );
1285
+
1286
+            return $manager;
1287
+        });
1288
+        /** @deprecated 19.0.0 */
1289
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1290
+
1291
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1292
+            $instance = new Collaboration\Collaborators\Search($c);
1293
+
1294
+            // register default plugins
1295
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1296
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1297
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1298
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1299
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1300
+
1301
+            return $instance;
1302
+        });
1303
+        /** @deprecated 19.0.0 */
1304
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1305
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1306
+
1307
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1308
+
1309
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1310
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1311
+
1312
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1313
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1314
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1315
+            return new \OC\Files\AppData\Factory(
1316
+                $c->get(IRootFolder::class),
1317
+                $c->get(SystemConfig::class)
1318
+            );
1319
+        });
1320
+
1321
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1322
+            return new LockdownManager(function () use ($c) {
1323
+                return $c->get(ISession::class);
1324
+            });
1325
+        });
1326
+
1327
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1328
+            return new DiscoveryService(
1329
+                $c->get(ICacheFactory::class),
1330
+                $c->get(IClientService::class)
1331
+            );
1332
+        });
1333
+
1334
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1335
+            return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1336
+        });
1337
+
1338
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1339
+
1340
+        $this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1341
+            return new CloudFederationProviderManager(
1342
+                $c->get(IAppManager::class),
1343
+                $c->get(IClientService::class),
1344
+                $c->get(ICloudIdManager::class),
1345
+                $c->get(ILogger::class)
1346
+            );
1347
+        });
1348
+
1349
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1350
+            return new CloudFederationFactory();
1351
+        });
1352
+
1353
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1354
+        /** @deprecated 19.0.0 */
1355
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1356
+
1357
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1358
+        /** @deprecated 19.0.0 */
1359
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1360
+
1361
+        $this->registerService(Defaults::class, function (Server $c) {
1362
+            return new Defaults(
1363
+                $c->getThemingDefaults()
1364
+            );
1365
+        });
1366
+        /** @deprecated 19.0.0 */
1367
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1368
+
1369
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1370
+            return $c->get(\OCP\IUserSession::class)->getSession();
1371
+        }, false);
1372
+
1373
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1374
+            return new ShareHelper(
1375
+                $c->get(\OCP\Share\IManager::class)
1376
+            );
1377
+        });
1378
+
1379
+        $this->registerService(Installer::class, function (ContainerInterface $c) {
1380
+            return new Installer(
1381
+                $c->get(AppFetcher::class),
1382
+                $c->get(IClientService::class),
1383
+                $c->get(ITempManager::class),
1384
+                $c->get(LoggerInterface::class),
1385
+                $c->get(\OCP\IConfig::class),
1386
+                \OC::$CLI
1387
+            );
1388
+        });
1389
+
1390
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1391
+            return new ApiFactory($c->get(IClientService::class));
1392
+        });
1393
+
1394
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1395
+            $memcacheFactory = $c->get(ICacheFactory::class);
1396
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1397
+        });
1398
+
1399
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1400
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1401
+
1402
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1403
+
1404
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1405
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1406
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1407
+
1408
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1409
+
1410
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1411
+
1412
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1413
+
1414
+        $this->registerAlias(IBroker::class, Broker::class);
1415
+
1416
+        $this->connectDispatcher();
1417
+    }
1418
+
1419
+    public function boot() {
1420
+        /** @var HookConnector $hookConnector */
1421
+        $hookConnector = $this->get(HookConnector::class);
1422
+        $hookConnector->viewToNode();
1423
+    }
1424
+
1425
+    /**
1426
+     * @return \OCP\Calendar\IManager
1427
+     * @deprecated 20.0.0
1428
+     */
1429
+    public function getCalendarManager() {
1430
+        return $this->get(\OC\Calendar\Manager::class);
1431
+    }
1432
+
1433
+    /**
1434
+     * @return \OCP\Calendar\Resource\IManager
1435
+     * @deprecated 20.0.0
1436
+     */
1437
+    public function getCalendarResourceBackendManager() {
1438
+        return $this->get(\OC\Calendar\Resource\Manager::class);
1439
+    }
1440
+
1441
+    /**
1442
+     * @return \OCP\Calendar\Room\IManager
1443
+     * @deprecated 20.0.0
1444
+     */
1445
+    public function getCalendarRoomBackendManager() {
1446
+        return $this->get(\OC\Calendar\Room\Manager::class);
1447
+    }
1448
+
1449
+    private function connectDispatcher() {
1450
+        $dispatcher = $this->get(SymfonyAdapter::class);
1451
+
1452
+        // Delete avatar on user deletion
1453
+        $dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1454
+            $logger = $this->get(ILogger::class);
1455
+            $manager = $this->getAvatarManager();
1456
+            /** @var IUser $user */
1457
+            $user = $e->getSubject();
1458
+
1459
+            try {
1460
+                $avatar = $manager->getAvatar($user->getUID());
1461
+                $avatar->remove();
1462
+            } catch (NotFoundException $e) {
1463
+                // no avatar to remove
1464
+            } catch (\Exception $e) {
1465
+                // Ignore exceptions
1466
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1467
+            }
1468
+        });
1469
+
1470
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1471
+            $manager = $this->getAvatarManager();
1472
+            /** @var IUser $user */
1473
+            $user = $e->getSubject();
1474
+            $feature = $e->getArgument('feature');
1475
+            $oldValue = $e->getArgument('oldValue');
1476
+            $value = $e->getArgument('value');
1477
+
1478
+            // We only change the avatar on display name changes
1479
+            if ($feature !== 'displayName') {
1480
+                return;
1481
+            }
1482
+
1483
+            try {
1484
+                $avatar = $manager->getAvatar($user->getUID());
1485
+                $avatar->userChanged($feature, $oldValue, $value);
1486
+            } catch (NotFoundException $e) {
1487
+                // no avatar to remove
1488
+            }
1489
+        });
1490
+
1491
+        /** @var IEventDispatcher $eventDispatched */
1492
+        $eventDispatched = $this->get(IEventDispatcher::class);
1493
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1494
+        $eventDispatched->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1495
+    }
1496
+
1497
+    /**
1498
+     * @return \OCP\Contacts\IManager
1499
+     * @deprecated 20.0.0
1500
+     */
1501
+    public function getContactsManager() {
1502
+        return $this->get(\OCP\Contacts\IManager::class);
1503
+    }
1504
+
1505
+    /**
1506
+     * @return \OC\Encryption\Manager
1507
+     * @deprecated 20.0.0
1508
+     */
1509
+    public function getEncryptionManager() {
1510
+        return $this->get(\OCP\Encryption\IManager::class);
1511
+    }
1512
+
1513
+    /**
1514
+     * @return \OC\Encryption\File
1515
+     * @deprecated 20.0.0
1516
+     */
1517
+    public function getEncryptionFilesHelper() {
1518
+        return $this->get(IFile::class);
1519
+    }
1520
+
1521
+    /**
1522
+     * @return \OCP\Encryption\Keys\IStorage
1523
+     * @deprecated 20.0.0
1524
+     */
1525
+    public function getEncryptionKeyStorage() {
1526
+        return $this->get(IStorage::class);
1527
+    }
1528
+
1529
+    /**
1530
+     * The current request object holding all information about the request
1531
+     * currently being processed is returned from this method.
1532
+     * In case the current execution was not initiated by a web request null is returned
1533
+     *
1534
+     * @return \OCP\IRequest
1535
+     * @deprecated 20.0.0
1536
+     */
1537
+    public function getRequest() {
1538
+        return $this->get(IRequest::class);
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns the preview manager which can create preview images for a given file
1543
+     *
1544
+     * @return IPreview
1545
+     * @deprecated 20.0.0
1546
+     */
1547
+    public function getPreviewManager() {
1548
+        return $this->get(IPreview::class);
1549
+    }
1550
+
1551
+    /**
1552
+     * Returns the tag manager which can get and set tags for different object types
1553
+     *
1554
+     * @see \OCP\ITagManager::load()
1555
+     * @return ITagManager
1556
+     * @deprecated 20.0.0
1557
+     */
1558
+    public function getTagManager() {
1559
+        return $this->get(ITagManager::class);
1560
+    }
1561
+
1562
+    /**
1563
+     * Returns the system-tag manager
1564
+     *
1565
+     * @return ISystemTagManager
1566
+     *
1567
+     * @since 9.0.0
1568
+     * @deprecated 20.0.0
1569
+     */
1570
+    public function getSystemTagManager() {
1571
+        return $this->get(ISystemTagManager::class);
1572
+    }
1573
+
1574
+    /**
1575
+     * Returns the system-tag object mapper
1576
+     *
1577
+     * @return ISystemTagObjectMapper
1578
+     *
1579
+     * @since 9.0.0
1580
+     * @deprecated 20.0.0
1581
+     */
1582
+    public function getSystemTagObjectMapper() {
1583
+        return $this->get(ISystemTagObjectMapper::class);
1584
+    }
1585
+
1586
+    /**
1587
+     * Returns the avatar manager, used for avatar functionality
1588
+     *
1589
+     * @return IAvatarManager
1590
+     * @deprecated 20.0.0
1591
+     */
1592
+    public function getAvatarManager() {
1593
+        return $this->get(IAvatarManager::class);
1594
+    }
1595
+
1596
+    /**
1597
+     * Returns the root folder of ownCloud's data directory
1598
+     *
1599
+     * @return IRootFolder
1600
+     * @deprecated 20.0.0
1601
+     */
1602
+    public function getRootFolder() {
1603
+        return $this->get(IRootFolder::class);
1604
+    }
1605
+
1606
+    /**
1607
+     * Returns the root folder of ownCloud's data directory
1608
+     * This is the lazy variant so this gets only initialized once it
1609
+     * is actually used.
1610
+     *
1611
+     * @return IRootFolder
1612
+     * @deprecated 20.0.0
1613
+     */
1614
+    public function getLazyRootFolder() {
1615
+        return $this->get(IRootFolder::class);
1616
+    }
1617
+
1618
+    /**
1619
+     * Returns a view to ownCloud's files folder
1620
+     *
1621
+     * @param string $userId user ID
1622
+     * @return \OCP\Files\Folder|null
1623
+     * @deprecated 20.0.0
1624
+     */
1625
+    public function getUserFolder($userId = null) {
1626
+        if ($userId === null) {
1627
+            $user = $this->get(IUserSession::class)->getUser();
1628
+            if (!$user) {
1629
+                return null;
1630
+            }
1631
+            $userId = $user->getUID();
1632
+        }
1633
+        $root = $this->get(IRootFolder::class);
1634
+        return $root->getUserFolder($userId);
1635
+    }
1636
+
1637
+    /**
1638
+     * @return \OC\User\Manager
1639
+     * @deprecated 20.0.0
1640
+     */
1641
+    public function getUserManager() {
1642
+        return $this->get(IUserManager::class);
1643
+    }
1644
+
1645
+    /**
1646
+     * @return \OC\Group\Manager
1647
+     * @deprecated 20.0.0
1648
+     */
1649
+    public function getGroupManager() {
1650
+        return $this->get(IGroupManager::class);
1651
+    }
1652
+
1653
+    /**
1654
+     * @return \OC\User\Session
1655
+     * @deprecated 20.0.0
1656
+     */
1657
+    public function getUserSession() {
1658
+        return $this->get(IUserSession::class);
1659
+    }
1660
+
1661
+    /**
1662
+     * @return \OCP\ISession
1663
+     * @deprecated 20.0.0
1664
+     */
1665
+    public function getSession() {
1666
+        return $this->get(IUserSession::class)->getSession();
1667
+    }
1668
+
1669
+    /**
1670
+     * @param \OCP\ISession $session
1671
+     */
1672
+    public function setSession(\OCP\ISession $session) {
1673
+        $this->get(SessionStorage::class)->setSession($session);
1674
+        $this->get(IUserSession::class)->setSession($session);
1675
+        $this->get(Store::class)->setSession($session);
1676
+    }
1677
+
1678
+    /**
1679
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1680
+     * @deprecated 20.0.0
1681
+     */
1682
+    public function getTwoFactorAuthManager() {
1683
+        return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1684
+    }
1685
+
1686
+    /**
1687
+     * @return \OC\NavigationManager
1688
+     * @deprecated 20.0.0
1689
+     */
1690
+    public function getNavigationManager() {
1691
+        return $this->get(INavigationManager::class);
1692
+    }
1693
+
1694
+    /**
1695
+     * @return \OCP\IConfig
1696
+     * @deprecated 20.0.0
1697
+     */
1698
+    public function getConfig() {
1699
+        return $this->get(AllConfig::class);
1700
+    }
1701
+
1702
+    /**
1703
+     * @return \OC\SystemConfig
1704
+     * @deprecated 20.0.0
1705
+     */
1706
+    public function getSystemConfig() {
1707
+        return $this->get(SystemConfig::class);
1708
+    }
1709
+
1710
+    /**
1711
+     * Returns the app config manager
1712
+     *
1713
+     * @return IAppConfig
1714
+     * @deprecated 20.0.0
1715
+     */
1716
+    public function getAppConfig() {
1717
+        return $this->get(IAppConfig::class);
1718
+    }
1719
+
1720
+    /**
1721
+     * @return IFactory
1722
+     * @deprecated 20.0.0
1723
+     */
1724
+    public function getL10NFactory() {
1725
+        return $this->get(IFactory::class);
1726
+    }
1727
+
1728
+    /**
1729
+     * get an L10N instance
1730
+     *
1731
+     * @param string $app appid
1732
+     * @param string $lang
1733
+     * @return IL10N
1734
+     * @deprecated 20.0.0
1735
+     */
1736
+    public function getL10N($app, $lang = null) {
1737
+        return $this->get(IFactory::class)->get($app, $lang);
1738
+    }
1739
+
1740
+    /**
1741
+     * @return IURLGenerator
1742
+     * @deprecated 20.0.0
1743
+     */
1744
+    public function getURLGenerator() {
1745
+        return $this->get(IURLGenerator::class);
1746
+    }
1747
+
1748
+    /**
1749
+     * @return AppFetcher
1750
+     * @deprecated 20.0.0
1751
+     */
1752
+    public function getAppFetcher() {
1753
+        return $this->get(AppFetcher::class);
1754
+    }
1755
+
1756
+    /**
1757
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1758
+     * getMemCacheFactory() instead.
1759
+     *
1760
+     * @return ICache
1761
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1762
+     */
1763
+    public function getCache() {
1764
+        return $this->get(ICache::class);
1765
+    }
1766
+
1767
+    /**
1768
+     * Returns an \OCP\CacheFactory instance
1769
+     *
1770
+     * @return \OCP\ICacheFactory
1771
+     * @deprecated 20.0.0
1772
+     */
1773
+    public function getMemCacheFactory() {
1774
+        return $this->get(ICacheFactory::class);
1775
+    }
1776
+
1777
+    /**
1778
+     * Returns an \OC\RedisFactory instance
1779
+     *
1780
+     * @return \OC\RedisFactory
1781
+     * @deprecated 20.0.0
1782
+     */
1783
+    public function getGetRedisFactory() {
1784
+        return $this->get('RedisFactory');
1785
+    }
1786
+
1787
+
1788
+    /**
1789
+     * Returns the current session
1790
+     *
1791
+     * @return \OCP\IDBConnection
1792
+     * @deprecated 20.0.0
1793
+     */
1794
+    public function getDatabaseConnection() {
1795
+        return $this->get(IDBConnection::class);
1796
+    }
1797
+
1798
+    /**
1799
+     * Returns the activity manager
1800
+     *
1801
+     * @return \OCP\Activity\IManager
1802
+     * @deprecated 20.0.0
1803
+     */
1804
+    public function getActivityManager() {
1805
+        return $this->get(\OCP\Activity\IManager::class);
1806
+    }
1807
+
1808
+    /**
1809
+     * Returns an job list for controlling background jobs
1810
+     *
1811
+     * @return IJobList
1812
+     * @deprecated 20.0.0
1813
+     */
1814
+    public function getJobList() {
1815
+        return $this->get(IJobList::class);
1816
+    }
1817
+
1818
+    /**
1819
+     * Returns a logger instance
1820
+     *
1821
+     * @return ILogger
1822
+     * @deprecated 20.0.0
1823
+     */
1824
+    public function getLogger() {
1825
+        return $this->get(ILogger::class);
1826
+    }
1827
+
1828
+    /**
1829
+     * @return ILogFactory
1830
+     * @throws \OCP\AppFramework\QueryException
1831
+     * @deprecated 20.0.0
1832
+     */
1833
+    public function getLogFactory() {
1834
+        return $this->get(ILogFactory::class);
1835
+    }
1836
+
1837
+    /**
1838
+     * Returns a router for generating and matching urls
1839
+     *
1840
+     * @return IRouter
1841
+     * @deprecated 20.0.0
1842
+     */
1843
+    public function getRouter() {
1844
+        return $this->get(IRouter::class);
1845
+    }
1846
+
1847
+    /**
1848
+     * Returns a search instance
1849
+     *
1850
+     * @return ISearch
1851
+     * @deprecated 20.0.0
1852
+     */
1853
+    public function getSearch() {
1854
+        return $this->get(ISearch::class);
1855
+    }
1856
+
1857
+    /**
1858
+     * Returns a SecureRandom instance
1859
+     *
1860
+     * @return \OCP\Security\ISecureRandom
1861
+     * @deprecated 20.0.0
1862
+     */
1863
+    public function getSecureRandom() {
1864
+        return $this->get(ISecureRandom::class);
1865
+    }
1866
+
1867
+    /**
1868
+     * Returns a Crypto instance
1869
+     *
1870
+     * @return ICrypto
1871
+     * @deprecated 20.0.0
1872
+     */
1873
+    public function getCrypto() {
1874
+        return $this->get(ICrypto::class);
1875
+    }
1876
+
1877
+    /**
1878
+     * Returns a Hasher instance
1879
+     *
1880
+     * @return IHasher
1881
+     * @deprecated 20.0.0
1882
+     */
1883
+    public function getHasher() {
1884
+        return $this->get(IHasher::class);
1885
+    }
1886
+
1887
+    /**
1888
+     * Returns a CredentialsManager instance
1889
+     *
1890
+     * @return ICredentialsManager
1891
+     * @deprecated 20.0.0
1892
+     */
1893
+    public function getCredentialsManager() {
1894
+        return $this->get(ICredentialsManager::class);
1895
+    }
1896
+
1897
+    /**
1898
+     * Get the certificate manager
1899
+     *
1900
+     * @return \OCP\ICertificateManager
1901
+     */
1902
+    public function getCertificateManager() {
1903
+        return $this->get(ICertificateManager::class);
1904
+    }
1905
+
1906
+    /**
1907
+     * Returns an instance of the HTTP client service
1908
+     *
1909
+     * @return IClientService
1910
+     * @deprecated 20.0.0
1911
+     */
1912
+    public function getHTTPClientService() {
1913
+        return $this->get(IClientService::class);
1914
+    }
1915
+
1916
+    /**
1917
+     * Create a new event source
1918
+     *
1919
+     * @return \OCP\IEventSource
1920
+     * @deprecated 20.0.0
1921
+     */
1922
+    public function createEventSource() {
1923
+        return new \OC_EventSource();
1924
+    }
1925
+
1926
+    /**
1927
+     * Get the active event logger
1928
+     *
1929
+     * The returned logger only logs data when debug mode is enabled
1930
+     *
1931
+     * @return IEventLogger
1932
+     * @deprecated 20.0.0
1933
+     */
1934
+    public function getEventLogger() {
1935
+        return $this->get(IEventLogger::class);
1936
+    }
1937
+
1938
+    /**
1939
+     * Get the active query logger
1940
+     *
1941
+     * The returned logger only logs data when debug mode is enabled
1942
+     *
1943
+     * @return IQueryLogger
1944
+     * @deprecated 20.0.0
1945
+     */
1946
+    public function getQueryLogger() {
1947
+        return $this->get(IQueryLogger::class);
1948
+    }
1949
+
1950
+    /**
1951
+     * Get the manager for temporary files and folders
1952
+     *
1953
+     * @return \OCP\ITempManager
1954
+     * @deprecated 20.0.0
1955
+     */
1956
+    public function getTempManager() {
1957
+        return $this->get(ITempManager::class);
1958
+    }
1959
+
1960
+    /**
1961
+     * Get the app manager
1962
+     *
1963
+     * @return \OCP\App\IAppManager
1964
+     * @deprecated 20.0.0
1965
+     */
1966
+    public function getAppManager() {
1967
+        return $this->get(IAppManager::class);
1968
+    }
1969
+
1970
+    /**
1971
+     * Creates a new mailer
1972
+     *
1973
+     * @return IMailer
1974
+     * @deprecated 20.0.0
1975
+     */
1976
+    public function getMailer() {
1977
+        return $this->get(IMailer::class);
1978
+    }
1979
+
1980
+    /**
1981
+     * Get the webroot
1982
+     *
1983
+     * @return string
1984
+     * @deprecated 20.0.0
1985
+     */
1986
+    public function getWebRoot() {
1987
+        return $this->webRoot;
1988
+    }
1989
+
1990
+    /**
1991
+     * @return \OC\OCSClient
1992
+     * @deprecated 20.0.0
1993
+     */
1994
+    public function getOcsClient() {
1995
+        return $this->get('OcsClient');
1996
+    }
1997
+
1998
+    /**
1999
+     * @return IDateTimeZone
2000
+     * @deprecated 20.0.0
2001
+     */
2002
+    public function getDateTimeZone() {
2003
+        return $this->get(IDateTimeZone::class);
2004
+    }
2005
+
2006
+    /**
2007
+     * @return IDateTimeFormatter
2008
+     * @deprecated 20.0.0
2009
+     */
2010
+    public function getDateTimeFormatter() {
2011
+        return $this->get(IDateTimeFormatter::class);
2012
+    }
2013
+
2014
+    /**
2015
+     * @return IMountProviderCollection
2016
+     * @deprecated 20.0.0
2017
+     */
2018
+    public function getMountProviderCollection() {
2019
+        return $this->get(IMountProviderCollection::class);
2020
+    }
2021
+
2022
+    /**
2023
+     * Get the IniWrapper
2024
+     *
2025
+     * @return IniGetWrapper
2026
+     * @deprecated 20.0.0
2027
+     */
2028
+    public function getIniWrapper() {
2029
+        return $this->get(IniGetWrapper::class);
2030
+    }
2031
+
2032
+    /**
2033
+     * @return \OCP\Command\IBus
2034
+     * @deprecated 20.0.0
2035
+     */
2036
+    public function getCommandBus() {
2037
+        return $this->get(IBus::class);
2038
+    }
2039
+
2040
+    /**
2041
+     * Get the trusted domain helper
2042
+     *
2043
+     * @return TrustedDomainHelper
2044
+     * @deprecated 20.0.0
2045
+     */
2046
+    public function getTrustedDomainHelper() {
2047
+        return $this->get(TrustedDomainHelper::class);
2048
+    }
2049
+
2050
+    /**
2051
+     * Get the locking provider
2052
+     *
2053
+     * @return ILockingProvider
2054
+     * @since 8.1.0
2055
+     * @deprecated 20.0.0
2056
+     */
2057
+    public function getLockingProvider() {
2058
+        return $this->get(ILockingProvider::class);
2059
+    }
2060
+
2061
+    /**
2062
+     * @return IMountManager
2063
+     * @deprecated 20.0.0
2064
+     **/
2065
+    public function getMountManager() {
2066
+        return $this->get(IMountManager::class);
2067
+    }
2068
+
2069
+    /**
2070
+     * @return IUserMountCache
2071
+     * @deprecated 20.0.0
2072
+     */
2073
+    public function getUserMountCache() {
2074
+        return $this->get(IUserMountCache::class);
2075
+    }
2076
+
2077
+    /**
2078
+     * Get the MimeTypeDetector
2079
+     *
2080
+     * @return IMimeTypeDetector
2081
+     * @deprecated 20.0.0
2082
+     */
2083
+    public function getMimeTypeDetector() {
2084
+        return $this->get(IMimeTypeDetector::class);
2085
+    }
2086
+
2087
+    /**
2088
+     * Get the MimeTypeLoader
2089
+     *
2090
+     * @return IMimeTypeLoader
2091
+     * @deprecated 20.0.0
2092
+     */
2093
+    public function getMimeTypeLoader() {
2094
+        return $this->get(IMimeTypeLoader::class);
2095
+    }
2096
+
2097
+    /**
2098
+     * Get the manager of all the capabilities
2099
+     *
2100
+     * @return CapabilitiesManager
2101
+     * @deprecated 20.0.0
2102
+     */
2103
+    public function getCapabilitiesManager() {
2104
+        return $this->get(CapabilitiesManager::class);
2105
+    }
2106
+
2107
+    /**
2108
+     * Get the EventDispatcher
2109
+     *
2110
+     * @return EventDispatcherInterface
2111
+     * @since 8.2.0
2112
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2113
+     */
2114
+    public function getEventDispatcher() {
2115
+        return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2116
+    }
2117
+
2118
+    /**
2119
+     * Get the Notification Manager
2120
+     *
2121
+     * @return \OCP\Notification\IManager
2122
+     * @since 8.2.0
2123
+     * @deprecated 20.0.0
2124
+     */
2125
+    public function getNotificationManager() {
2126
+        return $this->get(\OCP\Notification\IManager::class);
2127
+    }
2128
+
2129
+    /**
2130
+     * @return ICommentsManager
2131
+     * @deprecated 20.0.0
2132
+     */
2133
+    public function getCommentsManager() {
2134
+        return $this->get(ICommentsManager::class);
2135
+    }
2136
+
2137
+    /**
2138
+     * @return \OCA\Theming\ThemingDefaults
2139
+     * @deprecated 20.0.0
2140
+     */
2141
+    public function getThemingDefaults() {
2142
+        return $this->get('ThemingDefaults');
2143
+    }
2144
+
2145
+    /**
2146
+     * @return \OC\IntegrityCheck\Checker
2147
+     * @deprecated 20.0.0
2148
+     */
2149
+    public function getIntegrityCodeChecker() {
2150
+        return $this->get('IntegrityCodeChecker');
2151
+    }
2152
+
2153
+    /**
2154
+     * @return \OC\Session\CryptoWrapper
2155
+     * @deprecated 20.0.0
2156
+     */
2157
+    public function getSessionCryptoWrapper() {
2158
+        return $this->get('CryptoWrapper');
2159
+    }
2160
+
2161
+    /**
2162
+     * @return CsrfTokenManager
2163
+     * @deprecated 20.0.0
2164
+     */
2165
+    public function getCsrfTokenManager() {
2166
+        return $this->get(CsrfTokenManager::class);
2167
+    }
2168
+
2169
+    /**
2170
+     * @return Throttler
2171
+     * @deprecated 20.0.0
2172
+     */
2173
+    public function getBruteForceThrottler() {
2174
+        return $this->get(Throttler::class);
2175
+    }
2176
+
2177
+    /**
2178
+     * @return IContentSecurityPolicyManager
2179
+     * @deprecated 20.0.0
2180
+     */
2181
+    public function getContentSecurityPolicyManager() {
2182
+        return $this->get(ContentSecurityPolicyManager::class);
2183
+    }
2184
+
2185
+    /**
2186
+     * @return ContentSecurityPolicyNonceManager
2187
+     * @deprecated 20.0.0
2188
+     */
2189
+    public function getContentSecurityPolicyNonceManager() {
2190
+        return $this->get(ContentSecurityPolicyNonceManager::class);
2191
+    }
2192
+
2193
+    /**
2194
+     * Not a public API as of 8.2, wait for 9.0
2195
+     *
2196
+     * @return \OCA\Files_External\Service\BackendService
2197
+     * @deprecated 20.0.0
2198
+     */
2199
+    public function getStoragesBackendService() {
2200
+        return $this->get(BackendService::class);
2201
+    }
2202
+
2203
+    /**
2204
+     * Not a public API as of 8.2, wait for 9.0
2205
+     *
2206
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2207
+     * @deprecated 20.0.0
2208
+     */
2209
+    public function getGlobalStoragesService() {
2210
+        return $this->get(GlobalStoragesService::class);
2211
+    }
2212
+
2213
+    /**
2214
+     * Not a public API as of 8.2, wait for 9.0
2215
+     *
2216
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2217
+     * @deprecated 20.0.0
2218
+     */
2219
+    public function getUserGlobalStoragesService() {
2220
+        return $this->get(UserGlobalStoragesService::class);
2221
+    }
2222
+
2223
+    /**
2224
+     * Not a public API as of 8.2, wait for 9.0
2225
+     *
2226
+     * @return \OCA\Files_External\Service\UserStoragesService
2227
+     * @deprecated 20.0.0
2228
+     */
2229
+    public function getUserStoragesService() {
2230
+        return $this->get(UserStoragesService::class);
2231
+    }
2232
+
2233
+    /**
2234
+     * @return \OCP\Share\IManager
2235
+     * @deprecated 20.0.0
2236
+     */
2237
+    public function getShareManager() {
2238
+        return $this->get(\OCP\Share\IManager::class);
2239
+    }
2240
+
2241
+    /**
2242
+     * @return \OCP\Collaboration\Collaborators\ISearch
2243
+     * @deprecated 20.0.0
2244
+     */
2245
+    public function getCollaboratorSearch() {
2246
+        return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2247
+    }
2248
+
2249
+    /**
2250
+     * @return \OCP\Collaboration\AutoComplete\IManager
2251
+     * @deprecated 20.0.0
2252
+     */
2253
+    public function getAutoCompleteManager() {
2254
+        return $this->get(IManager::class);
2255
+    }
2256
+
2257
+    /**
2258
+     * Returns the LDAP Provider
2259
+     *
2260
+     * @return \OCP\LDAP\ILDAPProvider
2261
+     * @deprecated 20.0.0
2262
+     */
2263
+    public function getLDAPProvider() {
2264
+        return $this->get('LDAPProvider');
2265
+    }
2266
+
2267
+    /**
2268
+     * @return \OCP\Settings\IManager
2269
+     * @deprecated 20.0.0
2270
+     */
2271
+    public function getSettingsManager() {
2272
+        return $this->get(\OC\Settings\Manager::class);
2273
+    }
2274
+
2275
+    /**
2276
+     * @return \OCP\Files\IAppData
2277
+     * @deprecated 20.0.0
2278
+     */
2279
+    public function getAppDataDir($app) {
2280
+        /** @var \OC\Files\AppData\Factory $factory */
2281
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
2282
+        return $factory->get($app);
2283
+    }
2284
+
2285
+    /**
2286
+     * @return \OCP\Lockdown\ILockdownManager
2287
+     * @deprecated 20.0.0
2288
+     */
2289
+    public function getLockdownManager() {
2290
+        return $this->get('LockdownManager');
2291
+    }
2292
+
2293
+    /**
2294
+     * @return \OCP\Federation\ICloudIdManager
2295
+     * @deprecated 20.0.0
2296
+     */
2297
+    public function getCloudIdManager() {
2298
+        return $this->get(ICloudIdManager::class);
2299
+    }
2300
+
2301
+    /**
2302
+     * @return \OCP\GlobalScale\IConfig
2303
+     * @deprecated 20.0.0
2304
+     */
2305
+    public function getGlobalScaleConfig() {
2306
+        return $this->get(IConfig::class);
2307
+    }
2308
+
2309
+    /**
2310
+     * @return \OCP\Federation\ICloudFederationProviderManager
2311
+     * @deprecated 20.0.0
2312
+     */
2313
+    public function getCloudFederationProviderManager() {
2314
+        return $this->get(ICloudFederationProviderManager::class);
2315
+    }
2316
+
2317
+    /**
2318
+     * @return \OCP\Remote\Api\IApiFactory
2319
+     * @deprecated 20.0.0
2320
+     */
2321
+    public function getRemoteApiFactory() {
2322
+        return $this->get(IApiFactory::class);
2323
+    }
2324
+
2325
+    /**
2326
+     * @return \OCP\Federation\ICloudFederationFactory
2327
+     * @deprecated 20.0.0
2328
+     */
2329
+    public function getCloudFederationFactory() {
2330
+        return $this->get(ICloudFederationFactory::class);
2331
+    }
2332
+
2333
+    /**
2334
+     * @return \OCP\Remote\IInstanceFactory
2335
+     * @deprecated 20.0.0
2336
+     */
2337
+    public function getRemoteInstanceFactory() {
2338
+        return $this->get(IInstanceFactory::class);
2339
+    }
2340
+
2341
+    /**
2342
+     * @return IStorageFactory
2343
+     * @deprecated 20.0.0
2344
+     */
2345
+    public function getStorageFactory() {
2346
+        return $this->get(IStorageFactory::class);
2347
+    }
2348
+
2349
+    /**
2350
+     * Get the Preview GeneratorHelper
2351
+     *
2352
+     * @return GeneratorHelper
2353
+     * @since 17.0.0
2354
+     * @deprecated 20.0.0
2355
+     */
2356
+    public function getGeneratorHelper() {
2357
+        return $this->get(\OC\Preview\GeneratorHelper::class);
2358
+    }
2359
+
2360
+    private function registerDeprecatedAlias(string $alias, string $target) {
2361
+        $this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2362
+            try {
2363
+                /** @var ILogger $logger */
2364
+                $logger = $container->get(ILogger::class);
2365
+                $logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2366
+            } catch (ContainerExceptionInterface $e) {
2367
+                // Could not get logger. Continue
2368
+            }
2369
+
2370
+            return $container->get($target);
2371
+        }, false);
2372
+    }
2373 2373
 }
Please login to merge, or discard this patch.
Spacing   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -285,10 +285,10 @@  discard block
 block discarded – undo
285 285
 		$this->registerParameter('isCLI', \OC::$CLI);
286 286
 		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
287 287
 
288
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
288
+		$this->registerService(ContainerInterface::class, function(ContainerInterface $c) {
289 289
 			return $c;
290 290
 		});
291
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
291
+		$this->registerService(\OCP\IServerContainer::class, function(ContainerInterface $c) {
292 292
 			return $c;
293 293
 		});
294 294
 
@@ -313,11 +313,11 @@  discard block
 block discarded – undo
313 313
 
314 314
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
315 315
 
316
-		$this->registerService(View::class, function (Server $c) {
316
+		$this->registerService(View::class, function(Server $c) {
317 317
 			return new View();
318 318
 		}, false);
319 319
 
320
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
320
+		$this->registerService(IPreview::class, function(ContainerInterface $c) {
321 321
 			return new PreviewManager(
322 322
 				$c->get(\OCP\IConfig::class),
323 323
 				$c->get(IRootFolder::class),
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
 		/** @deprecated 19.0.0 */
336 336
 		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
337 337
 
338
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
338
+		$this->registerService(\OC\Preview\Watcher::class, function(ContainerInterface $c) {
339 339
 			return new \OC\Preview\Watcher(
340 340
 				new \OC\Preview\Storage\Root(
341 341
 					$c->get(IRootFolder::class),
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 			);
345 345
 		});
346 346
 
347
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
347
+		$this->registerService(\OCP\Encryption\IManager::class, function(Server $c) {
348 348
 			$view = new View();
349 349
 			$util = new Encryption\Util(
350 350
 				$view,
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 
367 367
 		/** @deprecated 21.0.0 */
368 368
 		$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
369
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
369
+		$this->registerService(IFile::class, function(ContainerInterface $c) {
370 370
 			$util = new Encryption\Util(
371 371
 				new View(),
372 372
 				$c->get(IUserManager::class),
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 
383 383
 		/** @deprecated 21.0.0 */
384 384
 		$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
385
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
385
+		$this->registerService(IStorage::class, function(ContainerInterface $c) {
386 386
 			$view = new View();
387 387
 			$util = new Encryption\Util(
388 388
 				$view,
@@ -405,22 +405,22 @@  discard block
 block discarded – undo
405 405
 		/** @deprecated 19.0.0 */
406 406
 		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
407 407
 
408
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
408
+		$this->registerService('SystemTagManagerFactory', function(ContainerInterface $c) {
409 409
 			/** @var \OCP\IConfig $config */
410 410
 			$config = $c->get(\OCP\IConfig::class);
411 411
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
412 412
 			return new $factoryClass($this);
413 413
 		});
414
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
414
+		$this->registerService(ISystemTagManager::class, function(ContainerInterface $c) {
415 415
 			return $c->get('SystemTagManagerFactory')->getManager();
416 416
 		});
417 417
 		/** @deprecated 19.0.0 */
418 418
 		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
419 419
 
420
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
420
+		$this->registerService(ISystemTagObjectMapper::class, function(ContainerInterface $c) {
421 421
 			return $c->get('SystemTagManagerFactory')->getObjectMapper();
422 422
 		});
423
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
423
+		$this->registerService('RootFolder', function(ContainerInterface $c) {
424 424
 			$manager = \OC\Files\Filesystem::getMountManager(null);
425 425
 			$view = new View();
426 426
 			$root = new Root(
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 
442 442
 			return $root;
443 443
 		});
444
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
444
+		$this->registerService(HookConnector::class, function(ContainerInterface $c) {
445 445
 			return new HookConnector(
446 446
 				$c->get(IRootFolder::class),
447 447
 				new View(),
@@ -453,8 +453,8 @@  discard block
 block discarded – undo
453 453
 		/** @deprecated 19.0.0 */
454 454
 		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
455 455
 
456
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
457
-			return new LazyRoot(function () use ($c) {
456
+		$this->registerService(IRootFolder::class, function(ContainerInterface $c) {
457
+			return new LazyRoot(function() use ($c) {
458 458
 				return $c->get('RootFolder');
459 459
 			});
460 460
 		});
@@ -465,44 +465,44 @@  discard block
 block discarded – undo
465 465
 		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
466 466
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
467 467
 
468
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
468
+		$this->registerService(\OCP\IGroupManager::class, function(ContainerInterface $c) {
469 469
 			$groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
470
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
470
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
471 471
 				/** @var IEventDispatcher $dispatcher */
472 472
 				$dispatcher = $this->get(IEventDispatcher::class);
473 473
 				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
474 474
 			});
475
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
475
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $group) {
476 476
 				/** @var IEventDispatcher $dispatcher */
477 477
 				$dispatcher = $this->get(IEventDispatcher::class);
478 478
 				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
479 479
 			});
480
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
480
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
481 481
 				/** @var IEventDispatcher $dispatcher */
482 482
 				$dispatcher = $this->get(IEventDispatcher::class);
483 483
 				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
484 484
 			});
485
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
485
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
486 486
 				/** @var IEventDispatcher $dispatcher */
487 487
 				$dispatcher = $this->get(IEventDispatcher::class);
488 488
 				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
489 489
 			});
490
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
490
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
491 491
 				/** @var IEventDispatcher $dispatcher */
492 492
 				$dispatcher = $this->get(IEventDispatcher::class);
493 493
 				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
494 494
 			});
495
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
495
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
496 496
 				/** @var IEventDispatcher $dispatcher */
497 497
 				$dispatcher = $this->get(IEventDispatcher::class);
498 498
 				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
499 499
 			});
500
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
500
+			$groupManager->listen('\OC\Group', 'preRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
501 501
 				/** @var IEventDispatcher $dispatcher */
502 502
 				$dispatcher = $this->get(IEventDispatcher::class);
503 503
 				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
504 504
 			});
505
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
505
+			$groupManager->listen('\OC\Group', 'postRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
506 506
 				/** @var IEventDispatcher $dispatcher */
507 507
 				$dispatcher = $this->get(IEventDispatcher::class);
508 508
 				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 		/** @deprecated 19.0.0 */
513 513
 		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
514 514
 
515
-		$this->registerService(Store::class, function (ContainerInterface $c) {
515
+		$this->registerService(Store::class, function(ContainerInterface $c) {
516 516
 			$session = $c->get(ISession::class);
517 517
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
518 518
 				$tokenProvider = $c->get(IProvider::class);
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
 		$this->registerAlias(IStore::class, Store::class);
526 526
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
527 527
 
528
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
528
+		$this->registerService(\OC\User\Session::class, function(Server $c) {
529 529
 			$manager = $c->get(IUserManager::class);
530 530
 			$session = new \OC\Session\Memory('');
531 531
 			$timeFactory = new TimeFactory();
@@ -551,26 +551,26 @@  discard block
 block discarded – undo
551 551
 				$c->get(IEventDispatcher::class)
552 552
 			);
553 553
 			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
554
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
554
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
555 555
 				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
556 556
 			});
557 557
 			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
558
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
558
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
559 559
 				/** @var \OC\User\User $user */
560 560
 				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
561 561
 			});
562 562
 			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
563
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
563
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($legacyDispatcher) {
564 564
 				/** @var \OC\User\User $user */
565 565
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
566 566
 				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
567 567
 			});
568 568
 			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
569
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
569
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
570 570
 				/** @var \OC\User\User $user */
571 571
 				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
572 572
 			});
573
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
573
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
574 574
 				/** @var \OC\User\User $user */
575 575
 				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
576 576
 
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
 				$dispatcher = $this->get(IEventDispatcher::class);
579 579
 				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
580 580
 			});
581
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
581
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
582 582
 				/** @var \OC\User\User $user */
583 583
 				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
584 584
 
@@ -586,14 +586,14 @@  discard block
 block discarded – undo
586 586
 				$dispatcher = $this->get(IEventDispatcher::class);
587 587
 				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
588 588
 			});
589
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
589
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
590 590
 				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
591 591
 
592 592
 				/** @var IEventDispatcher $dispatcher */
593 593
 				$dispatcher = $this->get(IEventDispatcher::class);
594 594
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
595 595
 			});
596
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
596
+			$userSession->listen('\OC\User', 'postLogin', function($user, $loginName, $password, $isTokenLogin) {
597 597
 				/** @var \OC\User\User $user */
598 598
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
599 599
 
@@ -601,12 +601,12 @@  discard block
 block discarded – undo
601 601
 				$dispatcher = $this->get(IEventDispatcher::class);
602 602
 				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
603 603
 			});
604
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
604
+			$userSession->listen('\OC\User', 'preRememberedLogin', function($uid) {
605 605
 				/** @var IEventDispatcher $dispatcher */
606 606
 				$dispatcher = $this->get(IEventDispatcher::class);
607 607
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
608 608
 			});
609
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
609
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
610 610
 				/** @var \OC\User\User $user */
611 611
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
612 612
 
@@ -614,19 +614,19 @@  discard block
 block discarded – undo
614 614
 				$dispatcher = $this->get(IEventDispatcher::class);
615 615
 				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
616 616
 			});
617
-			$userSession->listen('\OC\User', 'logout', function ($user) {
617
+			$userSession->listen('\OC\User', 'logout', function($user) {
618 618
 				\OC_Hook::emit('OC_User', 'logout', []);
619 619
 
620 620
 				/** @var IEventDispatcher $dispatcher */
621 621
 				$dispatcher = $this->get(IEventDispatcher::class);
622 622
 				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
623 623
 			});
624
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
624
+			$userSession->listen('\OC\User', 'postLogout', function($user) {
625 625
 				/** @var IEventDispatcher $dispatcher */
626 626
 				$dispatcher = $this->get(IEventDispatcher::class);
627 627
 				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
628 628
 			});
629
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
629
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
630 630
 				/** @var \OC\User\User $user */
631 631
 				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
632 632
 
@@ -650,7 +650,7 @@  discard block
 block discarded – undo
650 650
 		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
651 651
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
652 652
 
653
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
653
+		$this->registerService(\OC\SystemConfig::class, function($c) use ($config) {
654 654
 			return new \OC\SystemConfig($config);
655 655
 		});
656 656
 		/** @deprecated 19.0.0 */
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
 		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
661 661
 		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
662 662
 
663
-		$this->registerService(IFactory::class, function (Server $c) {
663
+		$this->registerService(IFactory::class, function(Server $c) {
664 664
 			return new \OC\L10N\Factory(
665 665
 				$c->get(\OCP\IConfig::class),
666 666
 				$c->getRequest(),
@@ -680,13 +680,13 @@  discard block
 block discarded – undo
680 680
 		/** @deprecated 19.0.0 */
681 681
 		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
682 682
 
683
-		$this->registerService(ICache::class, function ($c) {
683
+		$this->registerService(ICache::class, function($c) {
684 684
 			return new Cache\File();
685 685
 		});
686 686
 		/** @deprecated 19.0.0 */
687 687
 		$this->registerDeprecatedAlias('UserCache', ICache::class);
688 688
 
689
-		$this->registerService(Factory::class, function (Server $c) {
689
+		$this->registerService(Factory::class, function(Server $c) {
690 690
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
691 691
 				ArrayCache::class,
692 692
 				ArrayCache::class,
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
 				$version = implode(',', $v);
711 711
 				$instanceId = \OC_Util::getInstanceId();
712 712
 				$path = \OC::$SERVERROOT;
713
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
713
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
714 714
 				return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
715 715
 					$config->getSystemValue('memcache.local', null),
716 716
 					$config->getSystemValue('memcache.distributed', null),
@@ -724,12 +724,12 @@  discard block
 block discarded – undo
724 724
 		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
725 725
 		$this->registerAlias(ICacheFactory::class, Factory::class);
726 726
 
727
-		$this->registerService('RedisFactory', function (Server $c) {
727
+		$this->registerService('RedisFactory', function(Server $c) {
728 728
 			$systemConfig = $c->get(SystemConfig::class);
729 729
 			return new RedisFactory($systemConfig, $c->getEventLogger());
730 730
 		});
731 731
 
732
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
732
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
733 733
 			$l10n = $this->get(IFactory::class)->get('lib');
734 734
 			return new \OC\Activity\Manager(
735 735
 				$c->getRequest(),
@@ -742,14 +742,14 @@  discard block
 block discarded – undo
742 742
 		/** @deprecated 19.0.0 */
743 743
 		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
744 744
 
745
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
745
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
746 746
 			return new \OC\Activity\EventMerger(
747 747
 				$c->getL10N('lib')
748 748
 			);
749 749
 		});
750 750
 		$this->registerAlias(IValidator::class, Validator::class);
751 751
 
752
-		$this->registerService(AvatarManager::class, function (Server $c) {
752
+		$this->registerService(AvatarManager::class, function(Server $c) {
753 753
 			return new AvatarManager(
754 754
 				$c->get(IUserSession::class),
755 755
 				$c->get(\OC\User\Manager::class),
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
769 769
 		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
770 770
 
771
-		$this->registerService(\OC\Log::class, function (Server $c) {
771
+		$this->registerService(\OC\Log::class, function(Server $c) {
772 772
 			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
773 773
 			$factory = new LogFactory($c, $this->get(SystemConfig::class));
774 774
 			$logger = $factory->get($logType);
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
 		// PSR-3 logger
783 783
 		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
784 784
 
785
-		$this->registerService(ILogFactory::class, function (Server $c) {
785
+		$this->registerService(ILogFactory::class, function(Server $c) {
786 786
 			return new LogFactory($c, $this->get(SystemConfig::class));
787 787
 		});
788 788
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
 		/** @deprecated 19.0.0 */
791 791
 		$this->registerDeprecatedAlias('JobList', IJobList::class);
792 792
 
793
-		$this->registerService(Router::class, function (Server $c) {
793
+		$this->registerService(Router::class, function(Server $c) {
794 794
 			$cacheFactory = $c->get(ICacheFactory::class);
795 795
 			$logger = $c->get(ILogger::class);
796 796
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 		/** @deprecated 19.0.0 */
809 809
 		$this->registerDeprecatedAlias('Search', ISearch::class);
810 810
 
811
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
811
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
812 812
 			$cacheFactory = $c->get(ICacheFactory::class);
813 813
 			if ($cacheFactory->isAvailable()) {
814 814
 				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
845 845
 
846 846
 		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
847
-		$this->registerService(Connection::class, function (Server $c) {
847
+		$this->registerService(Connection::class, function(Server $c) {
848 848
 			$systemConfig = $c->get(SystemConfig::class);
849 849
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
850 850
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -861,30 +861,30 @@  discard block
 block discarded – undo
861 861
 
862 862
 		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
863 863
 		$this->registerAlias(IClientService::class, ClientService::class);
864
-		$this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
864
+		$this->registerService(LocalAddressChecker::class, function(ContainerInterface $c) {
865 865
 			return new LocalAddressChecker(
866 866
 				$c->get(ILogger::class),
867 867
 			);
868 868
 		});
869
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
869
+		$this->registerService(NegativeDnsCache::class, function(ContainerInterface $c) {
870 870
 			return new NegativeDnsCache(
871 871
 				$c->get(ICacheFactory::class),
872 872
 			);
873 873
 		});
874
-		$this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
874
+		$this->registerService(DnsPinMiddleware::class, function(ContainerInterface $c) {
875 875
 			return new DnsPinMiddleware(
876 876
 				$c->get(NegativeDnsCache::class),
877 877
 				$c->get(LocalAddressChecker::class)
878 878
 			);
879 879
 		});
880 880
 		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
881
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
881
+		$this->registerService(IEventLogger::class, function(ContainerInterface $c) {
882 882
 			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
883 883
 		});
884 884
 		/** @deprecated 19.0.0 */
885 885
 		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
886 886
 
887
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
887
+		$this->registerService(IQueryLogger::class, function(ContainerInterface $c) {
888 888
 			$queryLogger = new QueryLogger();
889 889
 			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
890 890
 				// In debug mode, module is being activated by default
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 		$this->registerDeprecatedAlias('TempManager', TempManager::class);
900 900
 		$this->registerAlias(ITempManager::class, TempManager::class);
901 901
 
902
-		$this->registerService(AppManager::class, function (ContainerInterface $c) {
902
+		$this->registerService(AppManager::class, function(ContainerInterface $c) {
903 903
 			// TODO: use auto-wiring
904 904
 			return new \OC\App\AppManager(
905 905
 				$c->get(IUserSession::class),
@@ -919,7 +919,7 @@  discard block
 block discarded – undo
919 919
 		/** @deprecated 19.0.0 */
920 920
 		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
921 921
 
922
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
922
+		$this->registerService(IDateTimeFormatter::class, function(Server $c) {
923 923
 			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
924 924
 
925 925
 			return new DateTimeFormatter(
@@ -930,7 +930,7 @@  discard block
 block discarded – undo
930 930
 		/** @deprecated 19.0.0 */
931 931
 		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
932 932
 
933
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
933
+		$this->registerService(IUserMountCache::class, function(ContainerInterface $c) {
934 934
 			$mountCache = new UserMountCache(
935 935
 				$c->get(IDBConnection::class),
936 936
 				$c->get(IUserManager::class),
@@ -943,7 +943,7 @@  discard block
 block discarded – undo
943 943
 		/** @deprecated 19.0.0 */
944 944
 		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
945 945
 
946
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
946
+		$this->registerService(IMountProviderCollection::class, function(ContainerInterface $c) {
947 947
 			$loader = \OC\Files\Filesystem::getLoader();
948 948
 			$mountCache = $c->get(IUserMountCache::class);
949 949
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -965,7 +965,7 @@  discard block
 block discarded – undo
965 965
 
966 966
 		/** @deprecated 20.0.0 */
967 967
 		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
968
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
968
+		$this->registerService(IBus::class, function(ContainerInterface $c) {
969 969
 			$busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
970 970
 			if ($busClass) {
971 971
 				[$app, $class] = explode('::', $busClass, 2);
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
 		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
987 987
 		/** @deprecated 19.0.0 */
988 988
 		$this->registerDeprecatedAlias('Throttler', Throttler::class);
989
-		$this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
989
+		$this->registerService('IntegrityCodeChecker', function(ContainerInterface $c) {
990 990
 			// IConfig and IAppManager requires a working database. This code
991 991
 			// might however be called when ownCloud is not yet setup.
992 992
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
@@ -1007,7 +1007,7 @@  discard block
 block discarded – undo
1007 1007
 				$c->get(IMimeTypeDetector::class)
1008 1008
 			);
1009 1009
 		});
1010
-		$this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1010
+		$this->registerService(\OCP\IRequest::class, function(ContainerInterface $c) {
1011 1011
 			if (isset($this['urlParams'])) {
1012 1012
 				$urlParams = $this['urlParams'];
1013 1013
 			} else {
@@ -1044,14 +1044,14 @@  discard block
 block discarded – undo
1044 1044
 		/** @deprecated 19.0.0 */
1045 1045
 		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1046 1046
 
1047
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
1047
+		$this->registerService(IRequestId::class, function(ContainerInterface $c): IRequestId {
1048 1048
 			return new RequestId(
1049 1049
 				$_SERVER['UNIQUE_ID'] ?? '',
1050 1050
 				$this->get(ISecureRandom::class)
1051 1051
 			);
1052 1052
 		});
1053 1053
 
1054
-		$this->registerService(IMailer::class, function (Server $c) {
1054
+		$this->registerService(IMailer::class, function(Server $c) {
1055 1055
 			return new Mailer(
1056 1056
 				$c->get(\OCP\IConfig::class),
1057 1057
 				$c->get(ILogger::class),
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
 		/** @deprecated 21.0.0 */
1069 1069
 		$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1070 1070
 
1071
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1071
+		$this->registerService(ILDAPProviderFactory::class, function(ContainerInterface $c) {
1072 1072
 			$config = $c->get(\OCP\IConfig::class);
1073 1073
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1074 1074
 			if (is_null($factoryClass) || !class_exists($factoryClass)) {
@@ -1077,11 +1077,11 @@  discard block
 block discarded – undo
1077 1077
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1078 1078
 			return new $factoryClass($this);
1079 1079
 		});
1080
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1080
+		$this->registerService(ILDAPProvider::class, function(ContainerInterface $c) {
1081 1081
 			$factory = $c->get(ILDAPProviderFactory::class);
1082 1082
 			return $factory->getLDAPProvider();
1083 1083
 		});
1084
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1084
+		$this->registerService(ILockingProvider::class, function(ContainerInterface $c) {
1085 1085
 			$ini = $c->get(IniGetWrapper::class);
1086 1086
 			$config = $c->get(\OCP\IConfig::class);
1087 1087
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
 		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1107 1107
 
1108 1108
 		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
1109
-		$this->registerService(SetupManager::class, function ($c) {
1109
+		$this->registerService(SetupManager::class, function($c) {
1110 1110
 			// create the setupmanager through the mount manager to resolve the cyclic dependency
1111 1111
 			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1112 1112
 		});
@@ -1114,12 +1114,12 @@  discard block
 block discarded – undo
1114 1114
 		/** @deprecated 19.0.0 */
1115 1115
 		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1116 1116
 
1117
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1117
+		$this->registerService(IMimeTypeDetector::class, function(ContainerInterface $c) {
1118 1118
 			return new \OC\Files\Type\Detection(
1119 1119
 				$c->get(IURLGenerator::class),
1120 1120
 				$c->get(ILogger::class),
1121 1121
 				\OC::$configDir,
1122
-				\OC::$SERVERROOT . '/resources/config/'
1122
+				\OC::$SERVERROOT.'/resources/config/'
1123 1123
 			);
1124 1124
 		});
1125 1125
 		/** @deprecated 19.0.0 */
@@ -1128,19 +1128,19 @@  discard block
 block discarded – undo
1128 1128
 		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1129 1129
 		/** @deprecated 19.0.0 */
1130 1130
 		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1131
-		$this->registerService(BundleFetcher::class, function () {
1131
+		$this->registerService(BundleFetcher::class, function() {
1132 1132
 			return new BundleFetcher($this->getL10N('lib'));
1133 1133
 		});
1134 1134
 		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1135 1135
 		/** @deprecated 19.0.0 */
1136 1136
 		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1137 1137
 
1138
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1138
+		$this->registerService(CapabilitiesManager::class, function(ContainerInterface $c) {
1139 1139
 			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1140
-			$manager->registerCapability(function () use ($c) {
1140
+			$manager->registerCapability(function() use ($c) {
1141 1141
 				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1142 1142
 			});
1143
-			$manager->registerCapability(function () use ($c) {
1143
+			$manager->registerCapability(function() use ($c) {
1144 1144
 				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1145 1145
 			});
1146 1146
 			return $manager;
@@ -1148,14 +1148,14 @@  discard block
 block discarded – undo
1148 1148
 		/** @deprecated 19.0.0 */
1149 1149
 		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1150 1150
 
1151
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1151
+		$this->registerService(ICommentsManager::class, function(Server $c) {
1152 1152
 			$config = $c->get(\OCP\IConfig::class);
1153 1153
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1154 1154
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1155 1155
 			$factory = new $factoryClass($this);
1156 1156
 			$manager = $factory->getManager();
1157 1157
 
1158
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1158
+			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
1159 1159
 				$manager = $c->get(IUserManager::class);
1160 1160
 				$user = $manager->get($id);
1161 1161
 				if (is_null($user)) {
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1174 1174
 
1175 1175
 		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1176
-		$this->registerService('ThemingDefaults', function (Server $c) {
1176
+		$this->registerService('ThemingDefaults', function(Server $c) {
1177 1177
 			/*
1178 1178
 			 * Dark magic for autoloader.
1179 1179
 			 * If we do a class_exists it will try to load the class which will
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
 			}
1209 1209
 			return new \OC_Defaults();
1210 1210
 		});
1211
-		$this->registerService(JSCombiner::class, function (Server $c) {
1211
+		$this->registerService(JSCombiner::class, function(Server $c) {
1212 1212
 			return new JSCombiner(
1213 1213
 				$c->getAppDataDir('js'),
1214 1214
 				$c->get(IURLGenerator::class),
@@ -1222,7 +1222,7 @@  discard block
 block discarded – undo
1222 1222
 		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1223 1223
 		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1224 1224
 
1225
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1225
+		$this->registerService('CryptoWrapper', function(ContainerInterface $c) {
1226 1226
 			// FIXME: Instantiated here due to cyclic dependency
1227 1227
 			$request = new Request(
1228 1228
 				[
@@ -1249,14 +1249,14 @@  discard block
 block discarded – undo
1249 1249
 		});
1250 1250
 		/** @deprecated 19.0.0 */
1251 1251
 		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1252
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1252
+		$this->registerService(SessionStorage::class, function(ContainerInterface $c) {
1253 1253
 			return new SessionStorage($c->get(ISession::class));
1254 1254
 		});
1255 1255
 		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1256 1256
 		/** @deprecated 19.0.0 */
1257 1257
 		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1258 1258
 
1259
-		$this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1259
+		$this->registerService(\OCP\Share\IManager::class, function(IServerContainer $c) {
1260 1260
 			$config = $c->get(\OCP\IConfig::class);
1261 1261
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1262 1262
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1288,7 +1288,7 @@  discard block
 block discarded – undo
1288 1288
 		/** @deprecated 19.0.0 */
1289 1289
 		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1290 1290
 
1291
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1291
+		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1292 1292
 			$instance = new Collaboration\Collaborators\Search($c);
1293 1293
 
1294 1294
 			// register default plugins
@@ -1311,33 +1311,33 @@  discard block
 block discarded – undo
1311 1311
 
1312 1312
 		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1313 1313
 		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1314
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1314
+		$this->registerService(\OC\Files\AppData\Factory::class, function(ContainerInterface $c) {
1315 1315
 			return new \OC\Files\AppData\Factory(
1316 1316
 				$c->get(IRootFolder::class),
1317 1317
 				$c->get(SystemConfig::class)
1318 1318
 			);
1319 1319
 		});
1320 1320
 
1321
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1322
-			return new LockdownManager(function () use ($c) {
1321
+		$this->registerService('LockdownManager', function(ContainerInterface $c) {
1322
+			return new LockdownManager(function() use ($c) {
1323 1323
 				return $c->get(ISession::class);
1324 1324
 			});
1325 1325
 		});
1326 1326
 
1327
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1327
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(ContainerInterface $c) {
1328 1328
 			return new DiscoveryService(
1329 1329
 				$c->get(ICacheFactory::class),
1330 1330
 				$c->get(IClientService::class)
1331 1331
 			);
1332 1332
 		});
1333 1333
 
1334
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1334
+		$this->registerService(ICloudIdManager::class, function(ContainerInterface $c) {
1335 1335
 			return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1336 1336
 		});
1337 1337
 
1338 1338
 		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1339 1339
 
1340
-		$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1340
+		$this->registerService(ICloudFederationProviderManager::class, function(ContainerInterface $c) {
1341 1341
 			return new CloudFederationProviderManager(
1342 1342
 				$c->get(IAppManager::class),
1343 1343
 				$c->get(IClientService::class),
@@ -1346,7 +1346,7 @@  discard block
 block discarded – undo
1346 1346
 			);
1347 1347
 		});
1348 1348
 
1349
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1349
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1350 1350
 			return new CloudFederationFactory();
1351 1351
 		});
1352 1352
 
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
 		/** @deprecated 19.0.0 */
1359 1359
 		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1360 1360
 
1361
-		$this->registerService(Defaults::class, function (Server $c) {
1361
+		$this->registerService(Defaults::class, function(Server $c) {
1362 1362
 			return new Defaults(
1363 1363
 				$c->getThemingDefaults()
1364 1364
 			);
@@ -1366,17 +1366,17 @@  discard block
 block discarded – undo
1366 1366
 		/** @deprecated 19.0.0 */
1367 1367
 		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1368 1368
 
1369
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1369
+		$this->registerService(\OCP\ISession::class, function(ContainerInterface $c) {
1370 1370
 			return $c->get(\OCP\IUserSession::class)->getSession();
1371 1371
 		}, false);
1372 1372
 
1373
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1373
+		$this->registerService(IShareHelper::class, function(ContainerInterface $c) {
1374 1374
 			return new ShareHelper(
1375 1375
 				$c->get(\OCP\Share\IManager::class)
1376 1376
 			);
1377 1377
 		});
1378 1378
 
1379
-		$this->registerService(Installer::class, function (ContainerInterface $c) {
1379
+		$this->registerService(Installer::class, function(ContainerInterface $c) {
1380 1380
 			return new Installer(
1381 1381
 				$c->get(AppFetcher::class),
1382 1382
 				$c->get(IClientService::class),
@@ -1387,11 +1387,11 @@  discard block
 block discarded – undo
1387 1387
 			);
1388 1388
 		});
1389 1389
 
1390
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1390
+		$this->registerService(IApiFactory::class, function(ContainerInterface $c) {
1391 1391
 			return new ApiFactory($c->get(IClientService::class));
1392 1392
 		});
1393 1393
 
1394
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1394
+		$this->registerService(IInstanceFactory::class, function(ContainerInterface $c) {
1395 1395
 			$memcacheFactory = $c->get(ICacheFactory::class);
1396 1396
 			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1397 1397
 		});
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
 		$dispatcher = $this->get(SymfonyAdapter::class);
1451 1451
 
1452 1452
 		// Delete avatar on user deletion
1453
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1453
+		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1454 1454
 			$logger = $this->get(ILogger::class);
1455 1455
 			$manager = $this->getAvatarManager();
1456 1456
 			/** @var IUser $user */
@@ -1463,11 +1463,11 @@  discard block
 block discarded – undo
1463 1463
 				// no avatar to remove
1464 1464
 			} catch (\Exception $e) {
1465 1465
 				// Ignore exceptions
1466
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1466
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1467 1467
 			}
1468 1468
 		});
1469 1469
 
1470
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1470
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1471 1471
 			$manager = $this->getAvatarManager();
1472 1472
 			/** @var IUser $user */
1473 1473
 			$user = $e->getSubject();
@@ -2358,11 +2358,11 @@  discard block
 block discarded – undo
2358 2358
 	}
2359 2359
 
2360 2360
 	private function registerDeprecatedAlias(string $alias, string $target) {
2361
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2361
+		$this->registerService($alias, function(ContainerInterface $container) use ($target, $alias) {
2362 2362
 			try {
2363 2363
 				/** @var ILogger $logger */
2364 2364
 				$logger = $container->get(ILogger::class);
2365
-				$logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2365
+				$logger->debug('The requested alias "'.$alias.'" is deprecated. Please request "'.$target.'" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2366 2366
 			} catch (ContainerExceptionInterface $e) {
2367 2367
 				// Could not get logger. Continue
2368 2368
 			}
Please login to merge, or discard this patch.
lib/public/IRequestId.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -28,12 +28,12 @@
 block discarded – undo
28 28
  * @since 24.0.0
29 29
  */
30 30
 interface IRequestId {
31
-	/**
32
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
33
-	 * If `mod_unique_id` is installed this value will be taken.
34
-	 *
35
-	 * @return string
36
-	 * @since 24.0.0
37
-	 */
38
-	public function getId(): string;
31
+    /**
32
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
33
+     * If `mod_unique_id` is installed this value will be taken.
34
+     *
35
+     * @return string
36
+     * @since 24.0.0
37
+     */
38
+    public function getId(): string;
39 39
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1019 added lines, -1019 removed lines patch added patch discarded remove patch
@@ -79,1025 +79,1025 @@
 block discarded – undo
79 79
  * OC_autoload!
80 80
  */
81 81
 class OC {
82
-	/**
83
-	 * Associative array for autoloading. classname => filename
84
-	 */
85
-	public static $CLASSPATH = [];
86
-	/**
87
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
88
-	 */
89
-	public static $SERVERROOT = '';
90
-	/**
91
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
92
-	 */
93
-	private static $SUBURI = '';
94
-	/**
95
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
96
-	 */
97
-	public static $WEBROOT = '';
98
-	/**
99
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
100
-	 * web path in 'url'
101
-	 */
102
-	public static $APPSROOTS = [];
103
-
104
-	/**
105
-	 * @var string
106
-	 */
107
-	public static $configDir;
108
-
109
-	/**
110
-	 * requested app
111
-	 */
112
-	public static $REQUESTEDAPP = '';
113
-
114
-	/**
115
-	 * check if Nextcloud runs in cli mode
116
-	 */
117
-	public static $CLI = false;
118
-
119
-	/**
120
-	 * @var \OC\Autoloader $loader
121
-	 */
122
-	public static $loader = null;
123
-
124
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
125
-	public static $composerAutoloader = null;
126
-
127
-	/**
128
-	 * @var \OC\Server
129
-	 */
130
-	public static $server = null;
131
-
132
-	/**
133
-	 * @var \OC\Config
134
-	 */
135
-	private static $config = null;
136
-
137
-	/**
138
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
139
-	 * the app path list is empty or contains an invalid path
140
-	 */
141
-	public static function initPaths() {
142
-		if (defined('PHPUNIT_CONFIG_DIR')) {
143
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
144
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
145
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
146
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
147
-			self::$configDir = rtrim($dir, '/') . '/';
148
-		} else {
149
-			self::$configDir = OC::$SERVERROOT . '/config/';
150
-		}
151
-		self::$config = new \OC\Config(self::$configDir);
152
-
153
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
154
-		/**
155
-		 * FIXME: The following lines are required because we can't yet instantiate
156
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
157
-		 */
158
-		$params = [
159
-			'server' => [
160
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
161
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
162
-			],
163
-		];
164
-		$fakeRequest = new \OC\AppFramework\Http\Request(
165
-			$params,
166
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
167
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
168
-		);
169
-		$scriptName = $fakeRequest->getScriptName();
170
-		if (substr($scriptName, -1) == '/') {
171
-			$scriptName .= 'index.php';
172
-			//make sure suburi follows the same rules as scriptName
173
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
174
-				if (substr(OC::$SUBURI, -1) != '/') {
175
-					OC::$SUBURI = OC::$SUBURI . '/';
176
-				}
177
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
178
-			}
179
-		}
180
-
181
-
182
-		if (OC::$CLI) {
183
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
184
-		} else {
185
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
186
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
187
-
188
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
189
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
190
-				}
191
-			} else {
192
-				// The scriptName is not ending with OC::$SUBURI
193
-				// This most likely means that we are calling from CLI.
194
-				// However some cron jobs still need to generate
195
-				// a web URL, so we use overwritewebroot as a fallback.
196
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
197
-			}
198
-
199
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
200
-			// slash which is required by URL generation.
201
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
202
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
203
-				header('Location: '.\OC::$WEBROOT.'/');
204
-				exit();
205
-			}
206
-		}
207
-
208
-		// search the apps folder
209
-		$config_paths = self::$config->getValue('apps_paths', []);
210
-		if (!empty($config_paths)) {
211
-			foreach ($config_paths as $paths) {
212
-				if (isset($paths['url']) && isset($paths['path'])) {
213
-					$paths['url'] = rtrim($paths['url'], '/');
214
-					$paths['path'] = rtrim($paths['path'], '/');
215
-					OC::$APPSROOTS[] = $paths;
216
-				}
217
-			}
218
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
219
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
220
-		}
221
-
222
-		if (empty(OC::$APPSROOTS)) {
223
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
-				. '. You can also configure the location in the config.php file.');
225
-		}
226
-		$paths = [];
227
-		foreach (OC::$APPSROOTS as $path) {
228
-			$paths[] = $path['path'];
229
-			if (!is_dir($path['path'])) {
230
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
232
-			}
233
-		}
234
-
235
-		// set the right include path
236
-		set_include_path(
237
-			implode(PATH_SEPARATOR, $paths)
238
-		);
239
-	}
240
-
241
-	public static function checkConfig() {
242
-		$l = \OC::$server->getL10N('lib');
243
-
244
-		// Create config if it does not already exist
245
-		$configFilePath = self::$configDir .'/config.php';
246
-		if (!file_exists($configFilePath)) {
247
-			@touch($configFilePath);
248
-		}
249
-
250
-		// Check if config is writable
251
-		$configFileWritable = is_writable($configFilePath);
252
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
253
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
254
-			$urlGenerator = \OC::$server->getURLGenerator();
255
-
256
-			if (self::$CLI) {
257
-				echo $l->t('Cannot write into "config" directory!')."\n";
258
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
259
-				echo "\n";
260
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
261
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
262
-				exit;
263
-			} else {
264
-				OC_Template::printErrorPage(
265
-					$l->t('Cannot write into "config" directory!'),
266
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
267
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
268
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
269
-					503
270
-				);
271
-			}
272
-		}
273
-	}
274
-
275
-	public static function checkInstalled(\OC\SystemConfig $systemConfig) {
276
-		if (defined('OC_CONSOLE')) {
277
-			return;
278
-		}
279
-		// Redirect to installer if not installed
280
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
-			if (OC::$CLI) {
282
-				throw new Exception('Not installed');
283
-			} else {
284
-				$url = OC::$WEBROOT . '/index.php';
285
-				header('Location: ' . $url);
286
-			}
287
-			exit();
288
-		}
289
-	}
290
-
291
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
292
-		// Allow ajax update script to execute without being stopped
293
-		if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
-			// send http status 503
295
-			http_response_code(503);
296
-			header('Retry-After: 120');
297
-
298
-			// render error page
299
-			$template = new OC_Template('', 'update.user', 'guest');
300
-			OC_Util::addScript('maintenance');
301
-			OC_Util::addStyle('core', 'guest');
302
-			$template->printPage();
303
-			die();
304
-		}
305
-	}
306
-
307
-	/**
308
-	 * Prints the upgrade page
309
-	 *
310
-	 * @param \OC\SystemConfig $systemConfig
311
-	 */
312
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
-		$tooBig = false;
315
-		if (!$disableWebUpdater) {
316
-			$apps = \OC::$server->getAppManager();
317
-			if ($apps->isInstalled('user_ldap')) {
318
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
-
320
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
321
-					->from('ldap_user_mapping')
322
-					->execute();
323
-				$row = $result->fetch();
324
-				$result->closeCursor();
325
-
326
-				$tooBig = ($row['user_count'] > 50);
327
-			}
328
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
329
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
-
331
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
332
-					->from('user_saml_users')
333
-					->execute();
334
-				$row = $result->fetch();
335
-				$result->closeCursor();
336
-
337
-				$tooBig = ($row['user_count'] > 50);
338
-			}
339
-			if (!$tooBig) {
340
-				// count users
341
-				$stats = \OC::$server->getUserManager()->countUsers();
342
-				$totalUsers = array_sum($stats);
343
-				$tooBig = ($totalUsers > 50);
344
-			}
345
-		}
346
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
-
349
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
-			// send http status 503
351
-			http_response_code(503);
352
-			header('Retry-After: 120');
353
-
354
-			// render error page
355
-			$template = new OC_Template('', 'update.use-cli', 'guest');
356
-			$template->assign('productName', 'nextcloud'); // for now
357
-			$template->assign('version', OC_Util::getVersionString());
358
-			$template->assign('tooBig', $tooBig);
359
-
360
-			$template->printPage();
361
-			die();
362
-		}
363
-
364
-		// check whether this is a core update or apps update
365
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
366
-		$currentVersion = implode('.', \OCP\Util::getVersion());
367
-
368
-		// if not a core upgrade, then it's apps upgrade
369
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
-
371
-		$oldTheme = $systemConfig->getValue('theme');
372
-		$systemConfig->setValue('theme', '');
373
-		\OCP\Util::addScript('core', 'common');
374
-		\OCP\Util::addScript('core', 'main');
375
-		\OCP\Util::addTranslations('core');
376
-		\OCP\Util::addScript('core', 'update');
377
-
378
-		/** @var \OC\App\AppManager $appManager */
379
-		$appManager = \OC::$server->getAppManager();
380
-
381
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
382
-		$tmpl->assign('version', OC_Util::getVersionString());
383
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
384
-
385
-		// get third party apps
386
-		$ocVersion = \OCP\Util::getVersion();
387
-		$ocVersion = implode('.', $ocVersion);
388
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
389
-		$incompatibleShippedApps = [];
390
-		foreach ($incompatibleApps as $appInfo) {
391
-			if ($appManager->isShipped($appInfo['id'])) {
392
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
393
-			}
394
-		}
395
-
396
-		if (!empty($incompatibleShippedApps)) {
397
-			$l = \OC::$server->getL10N('core');
398
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
399
-			throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
400
-		}
401
-
402
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
403
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
404
-		try {
405
-			$defaults = new \OC_Defaults();
406
-			$tmpl->assign('productName', $defaults->getName());
407
-		} catch (Throwable $error) {
408
-			$tmpl->assign('productName', 'Nextcloud');
409
-		}
410
-		$tmpl->assign('oldTheme', $oldTheme);
411
-		$tmpl->printPage();
412
-	}
413
-
414
-	public static function initSession() {
415
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
416
-			ini_set('session.cookie_secure', 'true');
417
-		}
418
-
419
-		// prevents javascript from accessing php session cookies
420
-		ini_set('session.cookie_httponly', 'true');
421
-
422
-		// set the cookie path to the Nextcloud directory
423
-		$cookie_path = OC::$WEBROOT ? : '/';
424
-		ini_set('session.cookie_path', $cookie_path);
425
-
426
-		// Let the session name be changed in the initSession Hook
427
-		$sessionName = OC_Util::getInstanceId();
428
-
429
-		try {
430
-			// set the session name to the instance id - which is unique
431
-			$session = new \OC\Session\Internal($sessionName);
432
-
433
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
434
-			$session = $cryptoWrapper->wrapSession($session);
435
-			self::$server->setSession($session);
436
-
437
-			// if session can't be started break with http 500 error
438
-		} catch (Exception $e) {
439
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
440
-			//show the user a detailed error page
441
-			OC_Template::printExceptionErrorPage($e, 500);
442
-			die();
443
-		}
444
-
445
-		$sessionLifeTime = self::getSessionLifeTime();
446
-
447
-		// session timeout
448
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
449
-			if (isset($_COOKIE[session_name()])) {
450
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
451
-			}
452
-			\OC::$server->getUserSession()->logout();
453
-		}
454
-
455
-		$session->set('LAST_ACTIVITY', time());
456
-	}
457
-
458
-	/**
459
-	 * @return string
460
-	 */
461
-	private static function getSessionLifeTime() {
462
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
463
-	}
464
-
465
-	/**
466
-	 * Try to set some values to the required Nextcloud default
467
-	 */
468
-	public static function setRequiredIniValues() {
469
-		@ini_set('default_charset', 'UTF-8');
470
-		@ini_set('gd.jpeg_ignore_warning', '1');
471
-	}
472
-
473
-	/**
474
-	 * Send the same site cookies
475
-	 */
476
-	private static function sendSameSiteCookies() {
477
-		$cookieParams = session_get_cookie_params();
478
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
479
-		$policies = [
480
-			'lax',
481
-			'strict',
482
-		];
483
-
484
-		// Append __Host to the cookie if it meets the requirements
485
-		$cookiePrefix = '';
486
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
487
-			$cookiePrefix = '__Host-';
488
-		}
489
-
490
-		foreach ($policies as $policy) {
491
-			header(
492
-				sprintf(
493
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
494
-					$cookiePrefix,
495
-					$policy,
496
-					$cookieParams['path'],
497
-					$policy
498
-				),
499
-				false
500
-			);
501
-		}
502
-	}
503
-
504
-	/**
505
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
506
-	 * be set in every request if cookies are sent to add a second level of
507
-	 * defense against CSRF.
508
-	 *
509
-	 * If the cookie is not sent this will set the cookie and reload the page.
510
-	 * We use an additional cookie since we want to protect logout CSRF and
511
-	 * also we can't directly interfere with PHP's session mechanism.
512
-	 */
513
-	private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
514
-		$request = \OC::$server->getRequest();
515
-
516
-		// Some user agents are notorious and don't really properly follow HTTP
517
-		// specifications. For those, have an automated opt-out. Since the protection
518
-		// for remote.php is applied in base.php as starting point we need to opt out
519
-		// here.
520
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
521
-
522
-		// Fallback, if csrf.optout is unset
523
-		if (!is_array($incompatibleUserAgents)) {
524
-			$incompatibleUserAgents = [
525
-				// OS X Finder
526
-				'/^WebDAVFS/',
527
-				// Windows webdav drive
528
-				'/^Microsoft-WebDAV-MiniRedir/',
529
-			];
530
-		}
531
-
532
-		if ($request->isUserAgent($incompatibleUserAgents)) {
533
-			return;
534
-		}
535
-
536
-		if (count($_COOKIE) > 0) {
537
-			$requestUri = $request->getScriptName();
538
-			$processingScript = explode('/', $requestUri);
539
-			$processingScript = $processingScript[count($processingScript) - 1];
540
-
541
-			// index.php routes are handled in the middleware
542
-			if ($processingScript === 'index.php') {
543
-				return;
544
-			}
545
-
546
-			// All other endpoints require the lax and the strict cookie
547
-			if (!$request->passesStrictCookieCheck()) {
548
-				self::sendSameSiteCookies();
549
-				// Debug mode gets access to the resources without strict cookie
550
-				// due to the fact that the SabreDAV browser also lives there.
551
-				if (!$config->getSystemValue('debug', false)) {
552
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
553
-					exit();
554
-				}
555
-			}
556
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
557
-			self::sendSameSiteCookies();
558
-		}
559
-	}
560
-
561
-	public static function init() {
562
-		// calculate the root directories
563
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
564
-
565
-		// register autoloader
566
-		$loaderStart = microtime(true);
567
-		require_once __DIR__ . '/autoloader.php';
568
-		self::$loader = new \OC\Autoloader([
569
-			OC::$SERVERROOT . '/lib/private/legacy',
570
-		]);
571
-		if (defined('PHPUNIT_RUN')) {
572
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
573
-		}
574
-		spl_autoload_register([self::$loader, 'load']);
575
-		$loaderEnd = microtime(true);
576
-
577
-		self::$CLI = (php_sapi_name() == 'cli');
578
-
579
-		// Add default composer PSR-4 autoloader
580
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
581
-
582
-		try {
583
-			self::initPaths();
584
-			// setup 3rdparty autoloader
585
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
586
-			if (!file_exists($vendorAutoLoad)) {
587
-				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".');
588
-			}
589
-			require_once $vendorAutoLoad;
590
-		} catch (\RuntimeException $e) {
591
-			if (!self::$CLI) {
592
-				http_response_code(503);
593
-			}
594
-			// we can't use the template error page here, because this needs the
595
-			// DI container which isn't available yet
596
-			print($e->getMessage());
597
-			exit();
598
-		}
599
-
600
-		// setup the basic server
601
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
-		self::$server->boot();
603
-
604
-		$eventLogger = \OC::$server->getEventLogger();
605
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
606
-		$eventLogger->start('request', 'Full request after autoloading');
607
-		register_shutdown_function(function () use ($eventLogger) {
608
-			$eventLogger->end('request');
609
-		});
610
-		$eventLogger->start('boot', 'Initialize');
611
-
612
-		// Override php.ini and log everything if we're troubleshooting
613
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
614
-			error_reporting(E_ALL);
615
-		}
616
-
617
-		// Don't display errors and log them
618
-		@ini_set('display_errors', '0');
619
-		@ini_set('log_errors', '1');
620
-
621
-		if (!date_default_timezone_set('UTC')) {
622
-			throw new \RuntimeException('Could not set timezone to UTC');
623
-		}
624
-
625
-		//try to configure php to enable big file uploads.
626
-		//this doesn´t work always depending on the web server and php configuration.
627
-		//Let´s try to overwrite some defaults anyway
628
-
629
-		//try to set the maximum execution time to 60min
630
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
631
-			@set_time_limit(3600);
632
-		}
633
-		@ini_set('max_execution_time', '3600');
634
-		@ini_set('max_input_time', '3600');
635
-
636
-		self::setRequiredIniValues();
637
-		self::handleAuthHeaders();
638
-		$systemConfig = \OC::$server->get(\OC\SystemConfig::class);
639
-		self::registerAutoloaderCache($systemConfig);
640
-
641
-		// initialize intl fallback if necessary
642
-		OC_Util::isSetLocaleWorking();
643
-
644
-		$config = \OC::$server->get(\OCP\IConfig::class);
645
-		if (!defined('PHPUNIT_RUN')) {
646
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
647
-			$debug = $config->getSystemValue('debug', false);
648
-			OC\Log\ErrorHandler::register($debug);
649
-		}
650
-
651
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
652
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
653
-		$bootstrapCoordinator->runInitialRegistration();
654
-
655
-		$eventLogger->start('init_session', 'Initialize session');
656
-		OC_App::loadApps(['session']);
657
-		if (!self::$CLI) {
658
-			self::initSession();
659
-		}
660
-		$eventLogger->end('init_session');
661
-		self::checkConfig();
662
-		self::checkInstalled($systemConfig);
663
-
664
-		OC_Response::addSecurityHeaders();
665
-
666
-		self::performSameSiteCookieProtection($config);
667
-
668
-		if (!defined('OC_CONSOLE')) {
669
-			$errors = OC_Util::checkServer($systemConfig);
670
-			if (count($errors) > 0) {
671
-				if (!self::$CLI) {
672
-					http_response_code(503);
673
-					OC_Util::addStyle('guest');
674
-					try {
675
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
676
-						exit;
677
-					} catch (\Exception $e) {
678
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
679
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
680
-					}
681
-				}
682
-
683
-				// Convert l10n string into regular string for usage in database
684
-				$staticErrors = [];
685
-				foreach ($errors as $error) {
686
-					echo $error['error'] . "\n";
687
-					echo $error['hint'] . "\n\n";
688
-					$staticErrors[] = [
689
-						'error' => (string)$error['error'],
690
-						'hint' => (string)$error['hint'],
691
-					];
692
-				}
693
-
694
-				try {
695
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
696
-				} catch (\Exception $e) {
697
-					echo('Writing to database failed');
698
-				}
699
-				exit(1);
700
-			} elseif (self::$CLI && $config->getSystemValue('installed', false)) {
701
-				$config->deleteAppValue('core', 'cronErrors');
702
-			}
703
-		}
704
-		//try to set the session lifetime
705
-		$sessionLifeTime = self::getSessionLifeTime();
706
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
707
-
708
-		// User and Groups
709
-		if (!$systemConfig->getValue("installed", false)) {
710
-			self::$server->getSession()->set('user_id', '');
711
-		}
712
-
713
-		OC_User::useBackend(new \OC\User\Database());
714
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
715
-
716
-		// Subscribe to the hook
717
-		\OCP\Util::connectHook(
718
-			'\OCA\Files_Sharing\API\Server2Server',
719
-			'preLoginNameUsedAsUserName',
720
-			'\OC\User\Database',
721
-			'preLoginNameUsedAsUserName'
722
-		);
723
-
724
-		//setup extra user backends
725
-		if (!\OCP\Util::needUpgrade()) {
726
-			OC_User::setupBackends();
727
-		} else {
728
-			// Run upgrades in incognito mode
729
-			OC_User::setIncognitoMode(true);
730
-		}
731
-
732
-		self::registerCleanupHooks($systemConfig);
733
-		self::registerFilesystemHooks();
734
-		self::registerShareHooks($systemConfig);
735
-		self::registerEncryptionWrapperAndHooks();
736
-		self::registerAccountHooks();
737
-		self::registerResourceCollectionHooks();
738
-		self::registerAppRestrictionsHooks();
739
-
740
-		// Make sure that the application class is not loaded before the database is setup
741
-		if ($systemConfig->getValue("installed", false)) {
742
-			OC_App::loadApp('settings');
743
-			/* Build core application to make sure that listeners are registered */
744
-			self::$server->get(\OC\Core\Application::class);
745
-		}
746
-
747
-		//make sure temporary files are cleaned up
748
-		$tmpManager = \OC::$server->getTempManager();
749
-		register_shutdown_function([$tmpManager, 'clean']);
750
-		$lockProvider = \OC::$server->getLockingProvider();
751
-		register_shutdown_function([$lockProvider, 'releaseAll']);
752
-
753
-		// Check whether the sample configuration has been copied
754
-		if ($systemConfig->getValue('copied_sample_config', false)) {
755
-			$l = \OC::$server->getL10N('lib');
756
-			OC_Template::printErrorPage(
757
-				$l->t('Sample configuration detected'),
758
-				$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'),
759
-				503
760
-			);
761
-			return;
762
-		}
763
-
764
-		$request = \OC::$server->getRequest();
765
-		$host = $request->getInsecureServerHost();
766
-		/**
767
-		 * if the host passed in headers isn't trusted
768
-		 * FIXME: Should not be in here at all :see_no_evil:
769
-		 */
770
-		if (!OC::$CLI
771
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
772
-			&& $config->getSystemValue('installed', false)
773
-		) {
774
-			// Allow access to CSS resources
775
-			$isScssRequest = false;
776
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
777
-				$isScssRequest = true;
778
-			}
779
-
780
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
781
-				http_response_code(400);
782
-				header('Content-Type: application/json');
783
-				echo '{"error": "Trusted domain error.", "code": 15}';
784
-				exit();
785
-			}
786
-
787
-			if (!$isScssRequest) {
788
-				http_response_code(400);
789
-
790
-				\OC::$server->getLogger()->warning(
791
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
792
-					[
793
-						'app' => 'core',
794
-						'remoteAddress' => $request->getRemoteAddress(),
795
-						'host' => $host,
796
-					]
797
-				);
798
-
799
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
800
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
801
-				$tmpl->printPage();
802
-
803
-				exit();
804
-			}
805
-		}
806
-		$eventLogger->end('boot');
807
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
808
-	}
809
-
810
-	/**
811
-	 * register hooks for the cleanup of cache and bruteforce protection
812
-	 */
813
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
814
-		//don't try to do this before we are properly setup
815
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
816
-
817
-			// NOTE: This will be replaced to use OCP
818
-			$userSession = self::$server->getUserSession();
819
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
820
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
821
-					// reset brute force delay for this IP address and username
822
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
823
-					$request = \OC::$server->getRequest();
824
-					$throttler = \OC::$server->getBruteForceThrottler();
825
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
826
-				}
827
-
828
-				try {
829
-					$cache = new \OC\Cache\File();
830
-					$cache->gc();
831
-				} catch (\OC\ServerNotAvailableException $e) {
832
-					// not a GC exception, pass it on
833
-					throw $e;
834
-				} catch (\OC\ForbiddenException $e) {
835
-					// filesystem blocked for this request, ignore
836
-				} catch (\Exception $e) {
837
-					// a GC exception should not prevent users from using OC,
838
-					// so log the exception
839
-					\OC::$server->getLogger()->logException($e, [
840
-						'message' => 'Exception when running cache gc.',
841
-						'level' => ILogger::WARN,
842
-						'app' => 'core',
843
-					]);
844
-				}
845
-			});
846
-		}
847
-	}
848
-
849
-	private static function registerEncryptionWrapperAndHooks() {
850
-		$manager = self::$server->getEncryptionManager();
851
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
852
-
853
-		$enabled = $manager->isEnabled();
854
-		if ($enabled) {
855
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
856
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
857
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
858
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
859
-		}
860
-	}
861
-
862
-	private static function registerAccountHooks() {
863
-		/** @var IEventDispatcher $dispatcher */
864
-		$dispatcher = \OC::$server->get(IEventDispatcher::class);
865
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
866
-	}
867
-
868
-	private static function registerAppRestrictionsHooks() {
869
-		/** @var \OC\Group\Manager $groupManager */
870
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
871
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
872
-			$appManager = self::$server->getAppManager();
873
-			$apps = $appManager->getEnabledAppsForGroup($group);
874
-			foreach ($apps as $appId) {
875
-				$restrictions = $appManager->getAppRestriction($appId);
876
-				if (empty($restrictions)) {
877
-					continue;
878
-				}
879
-				$key = array_search($group->getGID(), $restrictions);
880
-				unset($restrictions[$key]);
881
-				$restrictions = array_values($restrictions);
882
-				if (empty($restrictions)) {
883
-					$appManager->disableApp($appId);
884
-				} else {
885
-					$appManager->enableAppForGroups($appId, $restrictions);
886
-				}
887
-			}
888
-		});
889
-	}
890
-
891
-	private static function registerResourceCollectionHooks() {
892
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
893
-	}
894
-
895
-	/**
896
-	 * register hooks for the filesystem
897
-	 */
898
-	public static function registerFilesystemHooks() {
899
-		// Check for blacklisted files
900
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
901
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
902
-	}
903
-
904
-	/**
905
-	 * register hooks for sharing
906
-	 */
907
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
908
-		if ($systemConfig->getValue('installed')) {
909
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
910
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
911
-
912
-			/** @var IEventDispatcher $dispatcher */
913
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
914
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
915
-		}
916
-	}
917
-
918
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
919
-		// The class loader takes an optional low-latency cache, which MUST be
920
-		// namespaced. The instanceid is used for namespacing, but might be
921
-		// unavailable at this point. Furthermore, it might not be possible to
922
-		// generate an instanceid via \OC_Util::getInstanceId() because the
923
-		// config file may not be writable. As such, we only register a class
924
-		// loader cache if instanceid is available without trying to create one.
925
-		$instanceId = $systemConfig->getValue('instanceid', null);
926
-		if ($instanceId) {
927
-			try {
928
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
929
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
930
-			} catch (\Exception $ex) {
931
-			}
932
-		}
933
-	}
934
-
935
-	/**
936
-	 * Handle the request
937
-	 */
938
-	public static function handleRequest() {
939
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
940
-		$systemConfig = \OC::$server->getSystemConfig();
941
-
942
-		// Check if Nextcloud is installed or in maintenance (update) mode
943
-		if (!$systemConfig->getValue('installed', false)) {
944
-			\OC::$server->getSession()->clear();
945
-			$setupHelper = new OC\Setup(
946
-				$systemConfig,
947
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
948
-				\OC::$server->getL10N('lib'),
949
-				\OC::$server->query(\OCP\Defaults::class),
950
-				\OC::$server->get(\Psr\Log\LoggerInterface::class),
951
-				\OC::$server->getSecureRandom(),
952
-				\OC::$server->query(\OC\Installer::class)
953
-			);
954
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
955
-			$controller->run($_POST);
956
-			exit();
957
-		}
958
-
959
-		$request = \OC::$server->getRequest();
960
-		$requestPath = $request->getRawPathInfo();
961
-		if ($requestPath === '/heartbeat') {
962
-			return;
963
-		}
964
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
965
-			self::checkMaintenanceMode($systemConfig);
966
-
967
-			if (\OCP\Util::needUpgrade()) {
968
-				if (function_exists('opcache_reset')) {
969
-					opcache_reset();
970
-				}
971
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
972
-					self::printUpgradePage($systemConfig);
973
-					exit();
974
-				}
975
-			}
976
-		}
977
-
978
-		// emergency app disabling
979
-		if ($requestPath === '/disableapp'
980
-			&& $request->getMethod() === 'POST'
981
-			&& ((array)$request->getParam('appid')) !== ''
982
-		) {
983
-			\OC_JSON::callCheck();
984
-			\OC_JSON::checkAdminUser();
985
-			$appIds = (array)$request->getParam('appid');
986
-			foreach ($appIds as $appId) {
987
-				$appId = \OC_App::cleanAppId($appId);
988
-				\OC::$server->getAppManager()->disableApp($appId);
989
-			}
990
-			\OC_JSON::success();
991
-			exit();
992
-		}
993
-
994
-		// Always load authentication apps
995
-		OC_App::loadApps(['authentication']);
996
-
997
-		// Load minimum set of apps
998
-		if (!\OCP\Util::needUpgrade()
999
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
1000
-			// For logged-in users: Load everything
1001
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1002
-				OC_App::loadApps();
1003
-			} else {
1004
-				// For guests: Load only filesystem and logging
1005
-				OC_App::loadApps(['filesystem', 'logging']);
1006
-
1007
-				// Don't try to login when a client is trying to get a OAuth token.
1008
-				// OAuth needs to support basic auth too, so the login is not valid
1009
-				// inside Nextcloud and the Login exception would ruin it.
1010
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1011
-					self::handleLogin($request);
1012
-				}
1013
-			}
1014
-		}
1015
-
1016
-		if (!self::$CLI) {
1017
-			try {
1018
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1019
-					OC_App::loadApps(['filesystem', 'logging']);
1020
-					OC_App::loadApps();
1021
-				}
1022
-				OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1023
-				return;
1024
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1025
-				//header('HTTP/1.0 404 Not Found');
1026
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1027
-				http_response_code(405);
1028
-				return;
1029
-			}
1030
-		}
1031
-
1032
-		// Handle WebDAV
1033
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1034
-			// not allowed any more to prevent people
1035
-			// mounting this root directly.
1036
-			// Users need to mount remote.php/webdav instead.
1037
-			http_response_code(405);
1038
-			return;
1039
-		}
1040
-
1041
-		// Someone is logged in
1042
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1043
-			OC_App::loadApps();
1044
-			OC_User::setupBackends();
1045
-			OC_Util::setupFS();
1046
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
1047
-		} else {
1048
-			// Not handled and not logged in
1049
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1050
-		}
1051
-	}
1052
-
1053
-	/**
1054
-	 * Check login: apache auth, auth token, basic auth
1055
-	 *
1056
-	 * @param OCP\IRequest $request
1057
-	 * @return boolean
1058
-	 */
1059
-	public static function handleLogin(OCP\IRequest $request) {
1060
-		$userSession = self::$server->getUserSession();
1061
-		if (OC_User::handleApacheAuth()) {
1062
-			return true;
1063
-		}
1064
-		if ($userSession->tryTokenLogin($request)) {
1065
-			return true;
1066
-		}
1067
-		if (isset($_COOKIE['nc_username'])
1068
-			&& isset($_COOKIE['nc_token'])
1069
-			&& isset($_COOKIE['nc_session_id'])
1070
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1071
-			return true;
1072
-		}
1073
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1074
-			return true;
1075
-		}
1076
-		return false;
1077
-	}
1078
-
1079
-	protected static function handleAuthHeaders() {
1080
-		//copy http auth headers for apache+php-fcgid work around
1081
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1082
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1083
-		}
1084
-
1085
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1086
-		$vars = [
1087
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1088
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1089
-		];
1090
-		foreach ($vars as $var) {
1091
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1092
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1093
-				if (count($credentials) === 2) {
1094
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1095
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1096
-					break;
1097
-				}
1098
-			}
1099
-		}
1100
-	}
82
+    /**
83
+     * Associative array for autoloading. classname => filename
84
+     */
85
+    public static $CLASSPATH = [];
86
+    /**
87
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
88
+     */
89
+    public static $SERVERROOT = '';
90
+    /**
91
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
92
+     */
93
+    private static $SUBURI = '';
94
+    /**
95
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
96
+     */
97
+    public static $WEBROOT = '';
98
+    /**
99
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
100
+     * web path in 'url'
101
+     */
102
+    public static $APPSROOTS = [];
103
+
104
+    /**
105
+     * @var string
106
+     */
107
+    public static $configDir;
108
+
109
+    /**
110
+     * requested app
111
+     */
112
+    public static $REQUESTEDAPP = '';
113
+
114
+    /**
115
+     * check if Nextcloud runs in cli mode
116
+     */
117
+    public static $CLI = false;
118
+
119
+    /**
120
+     * @var \OC\Autoloader $loader
121
+     */
122
+    public static $loader = null;
123
+
124
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
125
+    public static $composerAutoloader = null;
126
+
127
+    /**
128
+     * @var \OC\Server
129
+     */
130
+    public static $server = null;
131
+
132
+    /**
133
+     * @var \OC\Config
134
+     */
135
+    private static $config = null;
136
+
137
+    /**
138
+     * @throws \RuntimeException when the 3rdparty directory is missing or
139
+     * the app path list is empty or contains an invalid path
140
+     */
141
+    public static function initPaths() {
142
+        if (defined('PHPUNIT_CONFIG_DIR')) {
143
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
144
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
145
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
146
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
147
+            self::$configDir = rtrim($dir, '/') . '/';
148
+        } else {
149
+            self::$configDir = OC::$SERVERROOT . '/config/';
150
+        }
151
+        self::$config = new \OC\Config(self::$configDir);
152
+
153
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
154
+        /**
155
+         * FIXME: The following lines are required because we can't yet instantiate
156
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
157
+         */
158
+        $params = [
159
+            'server' => [
160
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
161
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
162
+            ],
163
+        ];
164
+        $fakeRequest = new \OC\AppFramework\Http\Request(
165
+            $params,
166
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
167
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
168
+        );
169
+        $scriptName = $fakeRequest->getScriptName();
170
+        if (substr($scriptName, -1) == '/') {
171
+            $scriptName .= 'index.php';
172
+            //make sure suburi follows the same rules as scriptName
173
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
174
+                if (substr(OC::$SUBURI, -1) != '/') {
175
+                    OC::$SUBURI = OC::$SUBURI . '/';
176
+                }
177
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
178
+            }
179
+        }
180
+
181
+
182
+        if (OC::$CLI) {
183
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
184
+        } else {
185
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
186
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
187
+
188
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
189
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
190
+                }
191
+            } else {
192
+                // The scriptName is not ending with OC::$SUBURI
193
+                // This most likely means that we are calling from CLI.
194
+                // However some cron jobs still need to generate
195
+                // a web URL, so we use overwritewebroot as a fallback.
196
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
197
+            }
198
+
199
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
200
+            // slash which is required by URL generation.
201
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
202
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
203
+                header('Location: '.\OC::$WEBROOT.'/');
204
+                exit();
205
+            }
206
+        }
207
+
208
+        // search the apps folder
209
+        $config_paths = self::$config->getValue('apps_paths', []);
210
+        if (!empty($config_paths)) {
211
+            foreach ($config_paths as $paths) {
212
+                if (isset($paths['url']) && isset($paths['path'])) {
213
+                    $paths['url'] = rtrim($paths['url'], '/');
214
+                    $paths['path'] = rtrim($paths['path'], '/');
215
+                    OC::$APPSROOTS[] = $paths;
216
+                }
217
+            }
218
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
219
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
220
+        }
221
+
222
+        if (empty(OC::$APPSROOTS)) {
223
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
+                . '. You can also configure the location in the config.php file.');
225
+        }
226
+        $paths = [];
227
+        foreach (OC::$APPSROOTS as $path) {
228
+            $paths[] = $path['path'];
229
+            if (!is_dir($path['path'])) {
230
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
232
+            }
233
+        }
234
+
235
+        // set the right include path
236
+        set_include_path(
237
+            implode(PATH_SEPARATOR, $paths)
238
+        );
239
+    }
240
+
241
+    public static function checkConfig() {
242
+        $l = \OC::$server->getL10N('lib');
243
+
244
+        // Create config if it does not already exist
245
+        $configFilePath = self::$configDir .'/config.php';
246
+        if (!file_exists($configFilePath)) {
247
+            @touch($configFilePath);
248
+        }
249
+
250
+        // Check if config is writable
251
+        $configFileWritable = is_writable($configFilePath);
252
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
253
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
254
+            $urlGenerator = \OC::$server->getURLGenerator();
255
+
256
+            if (self::$CLI) {
257
+                echo $l->t('Cannot write into "config" directory!')."\n";
258
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
259
+                echo "\n";
260
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
261
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
262
+                exit;
263
+            } else {
264
+                OC_Template::printErrorPage(
265
+                    $l->t('Cannot write into "config" directory!'),
266
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
267
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
268
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
269
+                    503
270
+                );
271
+            }
272
+        }
273
+    }
274
+
275
+    public static function checkInstalled(\OC\SystemConfig $systemConfig) {
276
+        if (defined('OC_CONSOLE')) {
277
+            return;
278
+        }
279
+        // Redirect to installer if not installed
280
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
+            if (OC::$CLI) {
282
+                throw new Exception('Not installed');
283
+            } else {
284
+                $url = OC::$WEBROOT . '/index.php';
285
+                header('Location: ' . $url);
286
+            }
287
+            exit();
288
+        }
289
+    }
290
+
291
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
292
+        // Allow ajax update script to execute without being stopped
293
+        if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
+            // send http status 503
295
+            http_response_code(503);
296
+            header('Retry-After: 120');
297
+
298
+            // render error page
299
+            $template = new OC_Template('', 'update.user', 'guest');
300
+            OC_Util::addScript('maintenance');
301
+            OC_Util::addStyle('core', 'guest');
302
+            $template->printPage();
303
+            die();
304
+        }
305
+    }
306
+
307
+    /**
308
+     * Prints the upgrade page
309
+     *
310
+     * @param \OC\SystemConfig $systemConfig
311
+     */
312
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
+        $tooBig = false;
315
+        if (!$disableWebUpdater) {
316
+            $apps = \OC::$server->getAppManager();
317
+            if ($apps->isInstalled('user_ldap')) {
318
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
+
320
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
321
+                    ->from('ldap_user_mapping')
322
+                    ->execute();
323
+                $row = $result->fetch();
324
+                $result->closeCursor();
325
+
326
+                $tooBig = ($row['user_count'] > 50);
327
+            }
328
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
329
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
+
331
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
332
+                    ->from('user_saml_users')
333
+                    ->execute();
334
+                $row = $result->fetch();
335
+                $result->closeCursor();
336
+
337
+                $tooBig = ($row['user_count'] > 50);
338
+            }
339
+            if (!$tooBig) {
340
+                // count users
341
+                $stats = \OC::$server->getUserManager()->countUsers();
342
+                $totalUsers = array_sum($stats);
343
+                $tooBig = ($totalUsers > 50);
344
+            }
345
+        }
346
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
+
349
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
+            // send http status 503
351
+            http_response_code(503);
352
+            header('Retry-After: 120');
353
+
354
+            // render error page
355
+            $template = new OC_Template('', 'update.use-cli', 'guest');
356
+            $template->assign('productName', 'nextcloud'); // for now
357
+            $template->assign('version', OC_Util::getVersionString());
358
+            $template->assign('tooBig', $tooBig);
359
+
360
+            $template->printPage();
361
+            die();
362
+        }
363
+
364
+        // check whether this is a core update or apps update
365
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
366
+        $currentVersion = implode('.', \OCP\Util::getVersion());
367
+
368
+        // if not a core upgrade, then it's apps upgrade
369
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
+
371
+        $oldTheme = $systemConfig->getValue('theme');
372
+        $systemConfig->setValue('theme', '');
373
+        \OCP\Util::addScript('core', 'common');
374
+        \OCP\Util::addScript('core', 'main');
375
+        \OCP\Util::addTranslations('core');
376
+        \OCP\Util::addScript('core', 'update');
377
+
378
+        /** @var \OC\App\AppManager $appManager */
379
+        $appManager = \OC::$server->getAppManager();
380
+
381
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
382
+        $tmpl->assign('version', OC_Util::getVersionString());
383
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
384
+
385
+        // get third party apps
386
+        $ocVersion = \OCP\Util::getVersion();
387
+        $ocVersion = implode('.', $ocVersion);
388
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
389
+        $incompatibleShippedApps = [];
390
+        foreach ($incompatibleApps as $appInfo) {
391
+            if ($appManager->isShipped($appInfo['id'])) {
392
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
393
+            }
394
+        }
395
+
396
+        if (!empty($incompatibleShippedApps)) {
397
+            $l = \OC::$server->getL10N('core');
398
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
399
+            throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
400
+        }
401
+
402
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
403
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
404
+        try {
405
+            $defaults = new \OC_Defaults();
406
+            $tmpl->assign('productName', $defaults->getName());
407
+        } catch (Throwable $error) {
408
+            $tmpl->assign('productName', 'Nextcloud');
409
+        }
410
+        $tmpl->assign('oldTheme', $oldTheme);
411
+        $tmpl->printPage();
412
+    }
413
+
414
+    public static function initSession() {
415
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
416
+            ini_set('session.cookie_secure', 'true');
417
+        }
418
+
419
+        // prevents javascript from accessing php session cookies
420
+        ini_set('session.cookie_httponly', 'true');
421
+
422
+        // set the cookie path to the Nextcloud directory
423
+        $cookie_path = OC::$WEBROOT ? : '/';
424
+        ini_set('session.cookie_path', $cookie_path);
425
+
426
+        // Let the session name be changed in the initSession Hook
427
+        $sessionName = OC_Util::getInstanceId();
428
+
429
+        try {
430
+            // set the session name to the instance id - which is unique
431
+            $session = new \OC\Session\Internal($sessionName);
432
+
433
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
434
+            $session = $cryptoWrapper->wrapSession($session);
435
+            self::$server->setSession($session);
436
+
437
+            // if session can't be started break with http 500 error
438
+        } catch (Exception $e) {
439
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
440
+            //show the user a detailed error page
441
+            OC_Template::printExceptionErrorPage($e, 500);
442
+            die();
443
+        }
444
+
445
+        $sessionLifeTime = self::getSessionLifeTime();
446
+
447
+        // session timeout
448
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
449
+            if (isset($_COOKIE[session_name()])) {
450
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
451
+            }
452
+            \OC::$server->getUserSession()->logout();
453
+        }
454
+
455
+        $session->set('LAST_ACTIVITY', time());
456
+    }
457
+
458
+    /**
459
+     * @return string
460
+     */
461
+    private static function getSessionLifeTime() {
462
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
463
+    }
464
+
465
+    /**
466
+     * Try to set some values to the required Nextcloud default
467
+     */
468
+    public static function setRequiredIniValues() {
469
+        @ini_set('default_charset', 'UTF-8');
470
+        @ini_set('gd.jpeg_ignore_warning', '1');
471
+    }
472
+
473
+    /**
474
+     * Send the same site cookies
475
+     */
476
+    private static function sendSameSiteCookies() {
477
+        $cookieParams = session_get_cookie_params();
478
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
479
+        $policies = [
480
+            'lax',
481
+            'strict',
482
+        ];
483
+
484
+        // Append __Host to the cookie if it meets the requirements
485
+        $cookiePrefix = '';
486
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
487
+            $cookiePrefix = '__Host-';
488
+        }
489
+
490
+        foreach ($policies as $policy) {
491
+            header(
492
+                sprintf(
493
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
494
+                    $cookiePrefix,
495
+                    $policy,
496
+                    $cookieParams['path'],
497
+                    $policy
498
+                ),
499
+                false
500
+            );
501
+        }
502
+    }
503
+
504
+    /**
505
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
506
+     * be set in every request if cookies are sent to add a second level of
507
+     * defense against CSRF.
508
+     *
509
+     * If the cookie is not sent this will set the cookie and reload the page.
510
+     * We use an additional cookie since we want to protect logout CSRF and
511
+     * also we can't directly interfere with PHP's session mechanism.
512
+     */
513
+    private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
514
+        $request = \OC::$server->getRequest();
515
+
516
+        // Some user agents are notorious and don't really properly follow HTTP
517
+        // specifications. For those, have an automated opt-out. Since the protection
518
+        // for remote.php is applied in base.php as starting point we need to opt out
519
+        // here.
520
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
521
+
522
+        // Fallback, if csrf.optout is unset
523
+        if (!is_array($incompatibleUserAgents)) {
524
+            $incompatibleUserAgents = [
525
+                // OS X Finder
526
+                '/^WebDAVFS/',
527
+                // Windows webdav drive
528
+                '/^Microsoft-WebDAV-MiniRedir/',
529
+            ];
530
+        }
531
+
532
+        if ($request->isUserAgent($incompatibleUserAgents)) {
533
+            return;
534
+        }
535
+
536
+        if (count($_COOKIE) > 0) {
537
+            $requestUri = $request->getScriptName();
538
+            $processingScript = explode('/', $requestUri);
539
+            $processingScript = $processingScript[count($processingScript) - 1];
540
+
541
+            // index.php routes are handled in the middleware
542
+            if ($processingScript === 'index.php') {
543
+                return;
544
+            }
545
+
546
+            // All other endpoints require the lax and the strict cookie
547
+            if (!$request->passesStrictCookieCheck()) {
548
+                self::sendSameSiteCookies();
549
+                // Debug mode gets access to the resources without strict cookie
550
+                // due to the fact that the SabreDAV browser also lives there.
551
+                if (!$config->getSystemValue('debug', false)) {
552
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
553
+                    exit();
554
+                }
555
+            }
556
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
557
+            self::sendSameSiteCookies();
558
+        }
559
+    }
560
+
561
+    public static function init() {
562
+        // calculate the root directories
563
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
564
+
565
+        // register autoloader
566
+        $loaderStart = microtime(true);
567
+        require_once __DIR__ . '/autoloader.php';
568
+        self::$loader = new \OC\Autoloader([
569
+            OC::$SERVERROOT . '/lib/private/legacy',
570
+        ]);
571
+        if (defined('PHPUNIT_RUN')) {
572
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
573
+        }
574
+        spl_autoload_register([self::$loader, 'load']);
575
+        $loaderEnd = microtime(true);
576
+
577
+        self::$CLI = (php_sapi_name() == 'cli');
578
+
579
+        // Add default composer PSR-4 autoloader
580
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
581
+
582
+        try {
583
+            self::initPaths();
584
+            // setup 3rdparty autoloader
585
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
586
+            if (!file_exists($vendorAutoLoad)) {
587
+                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".');
588
+            }
589
+            require_once $vendorAutoLoad;
590
+        } catch (\RuntimeException $e) {
591
+            if (!self::$CLI) {
592
+                http_response_code(503);
593
+            }
594
+            // we can't use the template error page here, because this needs the
595
+            // DI container which isn't available yet
596
+            print($e->getMessage());
597
+            exit();
598
+        }
599
+
600
+        // setup the basic server
601
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
+        self::$server->boot();
603
+
604
+        $eventLogger = \OC::$server->getEventLogger();
605
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
606
+        $eventLogger->start('request', 'Full request after autoloading');
607
+        register_shutdown_function(function () use ($eventLogger) {
608
+            $eventLogger->end('request');
609
+        });
610
+        $eventLogger->start('boot', 'Initialize');
611
+
612
+        // Override php.ini and log everything if we're troubleshooting
613
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
614
+            error_reporting(E_ALL);
615
+        }
616
+
617
+        // Don't display errors and log them
618
+        @ini_set('display_errors', '0');
619
+        @ini_set('log_errors', '1');
620
+
621
+        if (!date_default_timezone_set('UTC')) {
622
+            throw new \RuntimeException('Could not set timezone to UTC');
623
+        }
624
+
625
+        //try to configure php to enable big file uploads.
626
+        //this doesn´t work always depending on the web server and php configuration.
627
+        //Let´s try to overwrite some defaults anyway
628
+
629
+        //try to set the maximum execution time to 60min
630
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
631
+            @set_time_limit(3600);
632
+        }
633
+        @ini_set('max_execution_time', '3600');
634
+        @ini_set('max_input_time', '3600');
635
+
636
+        self::setRequiredIniValues();
637
+        self::handleAuthHeaders();
638
+        $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
639
+        self::registerAutoloaderCache($systemConfig);
640
+
641
+        // initialize intl fallback if necessary
642
+        OC_Util::isSetLocaleWorking();
643
+
644
+        $config = \OC::$server->get(\OCP\IConfig::class);
645
+        if (!defined('PHPUNIT_RUN')) {
646
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
647
+            $debug = $config->getSystemValue('debug', false);
648
+            OC\Log\ErrorHandler::register($debug);
649
+        }
650
+
651
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
652
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
653
+        $bootstrapCoordinator->runInitialRegistration();
654
+
655
+        $eventLogger->start('init_session', 'Initialize session');
656
+        OC_App::loadApps(['session']);
657
+        if (!self::$CLI) {
658
+            self::initSession();
659
+        }
660
+        $eventLogger->end('init_session');
661
+        self::checkConfig();
662
+        self::checkInstalled($systemConfig);
663
+
664
+        OC_Response::addSecurityHeaders();
665
+
666
+        self::performSameSiteCookieProtection($config);
667
+
668
+        if (!defined('OC_CONSOLE')) {
669
+            $errors = OC_Util::checkServer($systemConfig);
670
+            if (count($errors) > 0) {
671
+                if (!self::$CLI) {
672
+                    http_response_code(503);
673
+                    OC_Util::addStyle('guest');
674
+                    try {
675
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
676
+                        exit;
677
+                    } catch (\Exception $e) {
678
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
679
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
680
+                    }
681
+                }
682
+
683
+                // Convert l10n string into regular string for usage in database
684
+                $staticErrors = [];
685
+                foreach ($errors as $error) {
686
+                    echo $error['error'] . "\n";
687
+                    echo $error['hint'] . "\n\n";
688
+                    $staticErrors[] = [
689
+                        'error' => (string)$error['error'],
690
+                        'hint' => (string)$error['hint'],
691
+                    ];
692
+                }
693
+
694
+                try {
695
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
696
+                } catch (\Exception $e) {
697
+                    echo('Writing to database failed');
698
+                }
699
+                exit(1);
700
+            } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
701
+                $config->deleteAppValue('core', 'cronErrors');
702
+            }
703
+        }
704
+        //try to set the session lifetime
705
+        $sessionLifeTime = self::getSessionLifeTime();
706
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
707
+
708
+        // User and Groups
709
+        if (!$systemConfig->getValue("installed", false)) {
710
+            self::$server->getSession()->set('user_id', '');
711
+        }
712
+
713
+        OC_User::useBackend(new \OC\User\Database());
714
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
715
+
716
+        // Subscribe to the hook
717
+        \OCP\Util::connectHook(
718
+            '\OCA\Files_Sharing\API\Server2Server',
719
+            'preLoginNameUsedAsUserName',
720
+            '\OC\User\Database',
721
+            'preLoginNameUsedAsUserName'
722
+        );
723
+
724
+        //setup extra user backends
725
+        if (!\OCP\Util::needUpgrade()) {
726
+            OC_User::setupBackends();
727
+        } else {
728
+            // Run upgrades in incognito mode
729
+            OC_User::setIncognitoMode(true);
730
+        }
731
+
732
+        self::registerCleanupHooks($systemConfig);
733
+        self::registerFilesystemHooks();
734
+        self::registerShareHooks($systemConfig);
735
+        self::registerEncryptionWrapperAndHooks();
736
+        self::registerAccountHooks();
737
+        self::registerResourceCollectionHooks();
738
+        self::registerAppRestrictionsHooks();
739
+
740
+        // Make sure that the application class is not loaded before the database is setup
741
+        if ($systemConfig->getValue("installed", false)) {
742
+            OC_App::loadApp('settings');
743
+            /* Build core application to make sure that listeners are registered */
744
+            self::$server->get(\OC\Core\Application::class);
745
+        }
746
+
747
+        //make sure temporary files are cleaned up
748
+        $tmpManager = \OC::$server->getTempManager();
749
+        register_shutdown_function([$tmpManager, 'clean']);
750
+        $lockProvider = \OC::$server->getLockingProvider();
751
+        register_shutdown_function([$lockProvider, 'releaseAll']);
752
+
753
+        // Check whether the sample configuration has been copied
754
+        if ($systemConfig->getValue('copied_sample_config', false)) {
755
+            $l = \OC::$server->getL10N('lib');
756
+            OC_Template::printErrorPage(
757
+                $l->t('Sample configuration detected'),
758
+                $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'),
759
+                503
760
+            );
761
+            return;
762
+        }
763
+
764
+        $request = \OC::$server->getRequest();
765
+        $host = $request->getInsecureServerHost();
766
+        /**
767
+         * if the host passed in headers isn't trusted
768
+         * FIXME: Should not be in here at all :see_no_evil:
769
+         */
770
+        if (!OC::$CLI
771
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
772
+            && $config->getSystemValue('installed', false)
773
+        ) {
774
+            // Allow access to CSS resources
775
+            $isScssRequest = false;
776
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
777
+                $isScssRequest = true;
778
+            }
779
+
780
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
781
+                http_response_code(400);
782
+                header('Content-Type: application/json');
783
+                echo '{"error": "Trusted domain error.", "code": 15}';
784
+                exit();
785
+            }
786
+
787
+            if (!$isScssRequest) {
788
+                http_response_code(400);
789
+
790
+                \OC::$server->getLogger()->warning(
791
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
792
+                    [
793
+                        'app' => 'core',
794
+                        'remoteAddress' => $request->getRemoteAddress(),
795
+                        'host' => $host,
796
+                    ]
797
+                );
798
+
799
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
800
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
801
+                $tmpl->printPage();
802
+
803
+                exit();
804
+            }
805
+        }
806
+        $eventLogger->end('boot');
807
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
808
+    }
809
+
810
+    /**
811
+     * register hooks for the cleanup of cache and bruteforce protection
812
+     */
813
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
814
+        //don't try to do this before we are properly setup
815
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
816
+
817
+            // NOTE: This will be replaced to use OCP
818
+            $userSession = self::$server->getUserSession();
819
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
820
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
821
+                    // reset brute force delay for this IP address and username
822
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
823
+                    $request = \OC::$server->getRequest();
824
+                    $throttler = \OC::$server->getBruteForceThrottler();
825
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
826
+                }
827
+
828
+                try {
829
+                    $cache = new \OC\Cache\File();
830
+                    $cache->gc();
831
+                } catch (\OC\ServerNotAvailableException $e) {
832
+                    // not a GC exception, pass it on
833
+                    throw $e;
834
+                } catch (\OC\ForbiddenException $e) {
835
+                    // filesystem blocked for this request, ignore
836
+                } catch (\Exception $e) {
837
+                    // a GC exception should not prevent users from using OC,
838
+                    // so log the exception
839
+                    \OC::$server->getLogger()->logException($e, [
840
+                        'message' => 'Exception when running cache gc.',
841
+                        'level' => ILogger::WARN,
842
+                        'app' => 'core',
843
+                    ]);
844
+                }
845
+            });
846
+        }
847
+    }
848
+
849
+    private static function registerEncryptionWrapperAndHooks() {
850
+        $manager = self::$server->getEncryptionManager();
851
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
852
+
853
+        $enabled = $manager->isEnabled();
854
+        if ($enabled) {
855
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
856
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
857
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
858
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
859
+        }
860
+    }
861
+
862
+    private static function registerAccountHooks() {
863
+        /** @var IEventDispatcher $dispatcher */
864
+        $dispatcher = \OC::$server->get(IEventDispatcher::class);
865
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
866
+    }
867
+
868
+    private static function registerAppRestrictionsHooks() {
869
+        /** @var \OC\Group\Manager $groupManager */
870
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
871
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
872
+            $appManager = self::$server->getAppManager();
873
+            $apps = $appManager->getEnabledAppsForGroup($group);
874
+            foreach ($apps as $appId) {
875
+                $restrictions = $appManager->getAppRestriction($appId);
876
+                if (empty($restrictions)) {
877
+                    continue;
878
+                }
879
+                $key = array_search($group->getGID(), $restrictions);
880
+                unset($restrictions[$key]);
881
+                $restrictions = array_values($restrictions);
882
+                if (empty($restrictions)) {
883
+                    $appManager->disableApp($appId);
884
+                } else {
885
+                    $appManager->enableAppForGroups($appId, $restrictions);
886
+                }
887
+            }
888
+        });
889
+    }
890
+
891
+    private static function registerResourceCollectionHooks() {
892
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
893
+    }
894
+
895
+    /**
896
+     * register hooks for the filesystem
897
+     */
898
+    public static function registerFilesystemHooks() {
899
+        // Check for blacklisted files
900
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
901
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
902
+    }
903
+
904
+    /**
905
+     * register hooks for sharing
906
+     */
907
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
908
+        if ($systemConfig->getValue('installed')) {
909
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
910
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
911
+
912
+            /** @var IEventDispatcher $dispatcher */
913
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
914
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
915
+        }
916
+    }
917
+
918
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
919
+        // The class loader takes an optional low-latency cache, which MUST be
920
+        // namespaced. The instanceid is used for namespacing, but might be
921
+        // unavailable at this point. Furthermore, it might not be possible to
922
+        // generate an instanceid via \OC_Util::getInstanceId() because the
923
+        // config file may not be writable. As such, we only register a class
924
+        // loader cache if instanceid is available without trying to create one.
925
+        $instanceId = $systemConfig->getValue('instanceid', null);
926
+        if ($instanceId) {
927
+            try {
928
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
929
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
930
+            } catch (\Exception $ex) {
931
+            }
932
+        }
933
+    }
934
+
935
+    /**
936
+     * Handle the request
937
+     */
938
+    public static function handleRequest() {
939
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
940
+        $systemConfig = \OC::$server->getSystemConfig();
941
+
942
+        // Check if Nextcloud is installed or in maintenance (update) mode
943
+        if (!$systemConfig->getValue('installed', false)) {
944
+            \OC::$server->getSession()->clear();
945
+            $setupHelper = new OC\Setup(
946
+                $systemConfig,
947
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
948
+                \OC::$server->getL10N('lib'),
949
+                \OC::$server->query(\OCP\Defaults::class),
950
+                \OC::$server->get(\Psr\Log\LoggerInterface::class),
951
+                \OC::$server->getSecureRandom(),
952
+                \OC::$server->query(\OC\Installer::class)
953
+            );
954
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
955
+            $controller->run($_POST);
956
+            exit();
957
+        }
958
+
959
+        $request = \OC::$server->getRequest();
960
+        $requestPath = $request->getRawPathInfo();
961
+        if ($requestPath === '/heartbeat') {
962
+            return;
963
+        }
964
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
965
+            self::checkMaintenanceMode($systemConfig);
966
+
967
+            if (\OCP\Util::needUpgrade()) {
968
+                if (function_exists('opcache_reset')) {
969
+                    opcache_reset();
970
+                }
971
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
972
+                    self::printUpgradePage($systemConfig);
973
+                    exit();
974
+                }
975
+            }
976
+        }
977
+
978
+        // emergency app disabling
979
+        if ($requestPath === '/disableapp'
980
+            && $request->getMethod() === 'POST'
981
+            && ((array)$request->getParam('appid')) !== ''
982
+        ) {
983
+            \OC_JSON::callCheck();
984
+            \OC_JSON::checkAdminUser();
985
+            $appIds = (array)$request->getParam('appid');
986
+            foreach ($appIds as $appId) {
987
+                $appId = \OC_App::cleanAppId($appId);
988
+                \OC::$server->getAppManager()->disableApp($appId);
989
+            }
990
+            \OC_JSON::success();
991
+            exit();
992
+        }
993
+
994
+        // Always load authentication apps
995
+        OC_App::loadApps(['authentication']);
996
+
997
+        // Load minimum set of apps
998
+        if (!\OCP\Util::needUpgrade()
999
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
1000
+            // For logged-in users: Load everything
1001
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1002
+                OC_App::loadApps();
1003
+            } else {
1004
+                // For guests: Load only filesystem and logging
1005
+                OC_App::loadApps(['filesystem', 'logging']);
1006
+
1007
+                // Don't try to login when a client is trying to get a OAuth token.
1008
+                // OAuth needs to support basic auth too, so the login is not valid
1009
+                // inside Nextcloud and the Login exception would ruin it.
1010
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1011
+                    self::handleLogin($request);
1012
+                }
1013
+            }
1014
+        }
1015
+
1016
+        if (!self::$CLI) {
1017
+            try {
1018
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1019
+                    OC_App::loadApps(['filesystem', 'logging']);
1020
+                    OC_App::loadApps();
1021
+                }
1022
+                OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1023
+                return;
1024
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1025
+                //header('HTTP/1.0 404 Not Found');
1026
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1027
+                http_response_code(405);
1028
+                return;
1029
+            }
1030
+        }
1031
+
1032
+        // Handle WebDAV
1033
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1034
+            // not allowed any more to prevent people
1035
+            // mounting this root directly.
1036
+            // Users need to mount remote.php/webdav instead.
1037
+            http_response_code(405);
1038
+            return;
1039
+        }
1040
+
1041
+        // Someone is logged in
1042
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1043
+            OC_App::loadApps();
1044
+            OC_User::setupBackends();
1045
+            OC_Util::setupFS();
1046
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
1047
+        } else {
1048
+            // Not handled and not logged in
1049
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1050
+        }
1051
+    }
1052
+
1053
+    /**
1054
+     * Check login: apache auth, auth token, basic auth
1055
+     *
1056
+     * @param OCP\IRequest $request
1057
+     * @return boolean
1058
+     */
1059
+    public static function handleLogin(OCP\IRequest $request) {
1060
+        $userSession = self::$server->getUserSession();
1061
+        if (OC_User::handleApacheAuth()) {
1062
+            return true;
1063
+        }
1064
+        if ($userSession->tryTokenLogin($request)) {
1065
+            return true;
1066
+        }
1067
+        if (isset($_COOKIE['nc_username'])
1068
+            && isset($_COOKIE['nc_token'])
1069
+            && isset($_COOKIE['nc_session_id'])
1070
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1071
+            return true;
1072
+        }
1073
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1074
+            return true;
1075
+        }
1076
+        return false;
1077
+    }
1078
+
1079
+    protected static function handleAuthHeaders() {
1080
+        //copy http auth headers for apache+php-fcgid work around
1081
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1082
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1083
+        }
1084
+
1085
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1086
+        $vars = [
1087
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1088
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1089
+        ];
1090
+        foreach ($vars as $var) {
1091
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1092
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1093
+                if (count($credentials) === 2) {
1094
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1095
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1096
+                    break;
1097
+                }
1098
+            }
1099
+        }
1100
+    }
1101 1101
 }
1102 1102
 
1103 1103
 OC::init();
Please login to merge, or discard this patch.