Passed
Push — master ( 95ad9a...5c0637 )
by Joas
12:15 queued 11s
created
lib/private/Http/Client/Client.php 2 patches
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -45,361 +45,361 @@
 block discarded – undo
45 45
  * @package OC\Http
46 46
  */
47 47
 class Client implements IClient {
48
-	/** @var GuzzleClient */
49
-	private $client;
50
-	/** @var IConfig */
51
-	private $config;
52
-	/** @var ILogger */
53
-	private $logger;
54
-	/** @var ICertificateManager */
55
-	private $certificateManager;
56
-
57
-	public function __construct(
58
-		IConfig $config,
59
-		ILogger $logger,
60
-		ICertificateManager $certificateManager,
61
-		GuzzleClient $client
62
-	) {
63
-		$this->config = $config;
64
-		$this->logger = $logger;
65
-		$this->client = $client;
66
-		$this->certificateManager = $certificateManager;
67
-	}
68
-
69
-	private function buildRequestOptions(array $options): array {
70
-		$proxy = $this->getProxyUri();
71
-
72
-		$defaults = [
73
-			RequestOptions::VERIFY => $this->getCertBundle(),
74
-			RequestOptions::TIMEOUT => 30,
75
-		];
76
-
77
-		// Only add RequestOptions::PROXY if Nextcloud is explicitly
78
-		// configured to use a proxy. This is needed in order not to override
79
-		// Guzzle default values.
80
-		if ($proxy !== null) {
81
-			$defaults[RequestOptions::PROXY] = $proxy;
82
-		}
83
-
84
-		$options = array_merge($defaults, $options);
85
-
86
-		if (!isset($options[RequestOptions::HEADERS]['User-Agent'])) {
87
-			$options[RequestOptions::HEADERS]['User-Agent'] = 'Nextcloud Server Crawler';
88
-		}
89
-
90
-		return $options;
91
-	}
92
-
93
-	private function getCertBundle(): string {
94
-		if ($this->certificateManager->listCertificates() !== []) {
95
-			return $this->certificateManager->getAbsoluteBundlePath();
96
-		}
97
-
98
-		// If the instance is not yet setup we need to use the static path as
99
-		// $this->certificateManager->getAbsoluteBundlePath() tries to instantiiate
100
-		// a view
101
-		if ($this->config->getSystemValue('installed', false)) {
102
-			return $this->certificateManager->getAbsoluteBundlePath(null);
103
-		}
104
-
105
-		return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
106
-	}
107
-
108
-	/**
109
-	 * Returns a null or an associative array specifiying the proxy URI for
110
-	 * 'http' and 'https' schemes, in addition to a 'no' key value pair
111
-	 * providing a list of host names that should not be proxied to.
112
-	 *
113
-	 * @return array|null
114
-	 *
115
-	 * The return array looks like:
116
-	 * [
117
-	 *   'http' => 'username:[email protected]',
118
-	 *   'https' => 'username:[email protected]',
119
-	 *   'no' => ['foo.com', 'bar.com']
120
-	 * ]
121
-	 *
122
-	 */
123
-	private function getProxyUri(): ?array {
124
-		$proxyHost = $this->config->getSystemValue('proxy', '');
125
-
126
-		if ($proxyHost === '' || $proxyHost === null) {
127
-			return null;
128
-		}
129
-
130
-		$proxyUserPwd = $this->config->getSystemValue('proxyuserpwd', '');
131
-		if ($proxyUserPwd !== '' && $proxyUserPwd !== null) {
132
-			$proxyHost = $proxyUserPwd . '@' . $proxyHost;
133
-		}
134
-
135
-		$proxy = [
136
-			'http' => $proxyHost,
137
-			'https' => $proxyHost,
138
-		];
139
-
140
-		$proxyExclude = $this->config->getSystemValue('proxyexclude', []);
141
-		if ($proxyExclude !== [] && $proxyExclude !== null) {
142
-			$proxy['no'] = $proxyExclude;
143
-		}
144
-
145
-		return $proxy;
146
-	}
147
-
148
-	protected function preventLocalAddress(string $uri, array $options): void {
149
-		if (($options['nextcloud']['allow_local_address'] ?? false) ||
150
-			$this->config->getSystemValueBool('allow_local_remote_servers', false)) {
151
-			return;
152
-		}
153
-
154
-		$host = parse_url($uri, PHP_URL_HOST);
155
-		if ($host === false) {
156
-			$this->logger->warning("Could not detect any host in $uri");
157
-			throw new LocalServerException('Could not detect any host');
158
-		}
159
-
160
-		$host = strtolower($host);
161
-		// remove brackets from IPv6 addresses
162
-		if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
163
-			$host = substr($host, 1, -1);
164
-		}
165
-
166
-		// Disallow localhost and local network
167
-		if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
168
-			$this->logger->warning("Host $host was not connected to because it violates local access rules");
169
-			throw new LocalServerException('Host violates local access rules');
170
-		}
171
-
172
-		// Disallow hostname only
173
-		if (substr_count($host, '.') === 0) {
174
-			$this->logger->warning("Host $host was not connected to because it violates local access rules");
175
-			throw new LocalServerException('Host violates local access rules');
176
-		}
177
-
178
-		if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
179
-			$this->logger->warning("Host $host was not connected to because it violates local access rules");
180
-			throw new LocalServerException('Host violates local access rules');
181
-		}
182
-
183
-		// Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
184
-		if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
185
-			$delimiter = strrpos($host, ':'); // Get last colon
186
-			$ipv4Address = substr($host, $delimiter + 1);
187
-
188
-			if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
189
-				$this->logger->warning("Host $host was not connected to because it violates local access rules");
190
-				throw new LocalServerException('Host violates local access rules');
191
-			}
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * Sends a GET request
197
-	 *
198
-	 * @param string $uri
199
-	 * @param array $options Array such as
200
-	 *              'query' => [
201
-	 *                  'field' => 'abc',
202
-	 *                  'other_field' => '123',
203
-	 *                  'file_name' => fopen('/path/to/file', 'r'),
204
-	 *              ],
205
-	 *              'headers' => [
206
-	 *                  'foo' => 'bar',
207
-	 *              ],
208
-	 *              'cookies' => ['
209
-	 *                  'foo' => 'bar',
210
-	 *              ],
211
-	 *              'allow_redirects' => [
212
-	 *                   'max'       => 10,  // allow at most 10 redirects.
213
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
214
-	 *                   'referer'   => true,     // add a Referer header
215
-	 *                   'protocols' => ['https'] // only allow https URLs
216
-	 *              ],
217
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
218
-	 *              'verify' => true, // bool or string to CA file
219
-	 *              'debug' => true,
220
-	 *              'timeout' => 5,
221
-	 * @return IResponse
222
-	 * @throws \Exception If the request could not get completed
223
-	 */
224
-	public function get(string $uri, array $options = []): IResponse {
225
-		$this->preventLocalAddress($uri, $options);
226
-		$response = $this->client->request('get', $uri, $this->buildRequestOptions($options));
227
-		$isStream = isset($options['stream']) && $options['stream'];
228
-		return new Response($response, $isStream);
229
-	}
230
-
231
-	/**
232
-	 * Sends a HEAD request
233
-	 *
234
-	 * @param string $uri
235
-	 * @param array $options Array such as
236
-	 *              'headers' => [
237
-	 *                  'foo' => 'bar',
238
-	 *              ],
239
-	 *              'cookies' => ['
240
-	 *                  'foo' => 'bar',
241
-	 *              ],
242
-	 *              'allow_redirects' => [
243
-	 *                   'max'       => 10,  // allow at most 10 redirects.
244
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
245
-	 *                   'referer'   => true,     // add a Referer header
246
-	 *                   'protocols' => ['https'] // only allow https URLs
247
-	 *              ],
248
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
249
-	 *              'verify' => true, // bool or string to CA file
250
-	 *              'debug' => true,
251
-	 *              'timeout' => 5,
252
-	 * @return IResponse
253
-	 * @throws \Exception If the request could not get completed
254
-	 */
255
-	public function head(string $uri, array $options = []): IResponse {
256
-		$this->preventLocalAddress($uri, $options);
257
-		$response = $this->client->request('head', $uri, $this->buildRequestOptions($options));
258
-		return new Response($response);
259
-	}
260
-
261
-	/**
262
-	 * Sends a POST request
263
-	 *
264
-	 * @param string $uri
265
-	 * @param array $options Array such as
266
-	 *              'body' => [
267
-	 *                  'field' => 'abc',
268
-	 *                  'other_field' => '123',
269
-	 *                  'file_name' => fopen('/path/to/file', 'r'),
270
-	 *              ],
271
-	 *              'headers' => [
272
-	 *                  'foo' => 'bar',
273
-	 *              ],
274
-	 *              'cookies' => ['
275
-	 *                  'foo' => 'bar',
276
-	 *              ],
277
-	 *              'allow_redirects' => [
278
-	 *                   'max'       => 10,  // allow at most 10 redirects.
279
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
280
-	 *                   'referer'   => true,     // add a Referer header
281
-	 *                   'protocols' => ['https'] // only allow https URLs
282
-	 *              ],
283
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
284
-	 *              'verify' => true, // bool or string to CA file
285
-	 *              'debug' => true,
286
-	 *              'timeout' => 5,
287
-	 * @return IResponse
288
-	 * @throws \Exception If the request could not get completed
289
-	 */
290
-	public function post(string $uri, array $options = []): IResponse {
291
-		$this->preventLocalAddress($uri, $options);
292
-
293
-		if (isset($options['body']) && is_array($options['body'])) {
294
-			$options['form_params'] = $options['body'];
295
-			unset($options['body']);
296
-		}
297
-		$response = $this->client->request('post', $uri, $this->buildRequestOptions($options));
298
-		return new Response($response);
299
-	}
300
-
301
-	/**
302
-	 * Sends a PUT request
303
-	 *
304
-	 * @param string $uri
305
-	 * @param array $options Array such as
306
-	 *              'body' => [
307
-	 *                  'field' => 'abc',
308
-	 *                  'other_field' => '123',
309
-	 *                  'file_name' => fopen('/path/to/file', 'r'),
310
-	 *              ],
311
-	 *              'headers' => [
312
-	 *                  'foo' => 'bar',
313
-	 *              ],
314
-	 *              'cookies' => ['
315
-	 *                  'foo' => 'bar',
316
-	 *              ],
317
-	 *              'allow_redirects' => [
318
-	 *                   'max'       => 10,  // allow at most 10 redirects.
319
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
320
-	 *                   'referer'   => true,     // add a Referer header
321
-	 *                   'protocols' => ['https'] // only allow https URLs
322
-	 *              ],
323
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
324
-	 *              'verify' => true, // bool or string to CA file
325
-	 *              'debug' => true,
326
-	 *              'timeout' => 5,
327
-	 * @return IResponse
328
-	 * @throws \Exception If the request could not get completed
329
-	 */
330
-	public function put(string $uri, array $options = []): IResponse {
331
-		$this->preventLocalAddress($uri, $options);
332
-		$response = $this->client->request('put', $uri, $this->buildRequestOptions($options));
333
-		return new Response($response);
334
-	}
335
-
336
-	/**
337
-	 * Sends a DELETE request
338
-	 *
339
-	 * @param string $uri
340
-	 * @param array $options Array such as
341
-	 *              'body' => [
342
-	 *                  'field' => 'abc',
343
-	 *                  'other_field' => '123',
344
-	 *                  'file_name' => fopen('/path/to/file', 'r'),
345
-	 *              ],
346
-	 *              'headers' => [
347
-	 *                  'foo' => 'bar',
348
-	 *              ],
349
-	 *              'cookies' => ['
350
-	 *                  'foo' => 'bar',
351
-	 *              ],
352
-	 *              'allow_redirects' => [
353
-	 *                   'max'       => 10,  // allow at most 10 redirects.
354
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
355
-	 *                   'referer'   => true,     // add a Referer header
356
-	 *                   'protocols' => ['https'] // only allow https URLs
357
-	 *              ],
358
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
359
-	 *              'verify' => true, // bool or string to CA file
360
-	 *              'debug' => true,
361
-	 *              'timeout' => 5,
362
-	 * @return IResponse
363
-	 * @throws \Exception If the request could not get completed
364
-	 */
365
-	public function delete(string $uri, array $options = []): IResponse {
366
-		$this->preventLocalAddress($uri, $options);
367
-		$response = $this->client->request('delete', $uri, $this->buildRequestOptions($options));
368
-		return new Response($response);
369
-	}
370
-
371
-	/**
372
-	 * Sends a options request
373
-	 *
374
-	 * @param string $uri
375
-	 * @param array $options Array such as
376
-	 *              'body' => [
377
-	 *                  'field' => 'abc',
378
-	 *                  'other_field' => '123',
379
-	 *                  'file_name' => fopen('/path/to/file', 'r'),
380
-	 *              ],
381
-	 *              'headers' => [
382
-	 *                  'foo' => 'bar',
383
-	 *              ],
384
-	 *              'cookies' => ['
385
-	 *                  'foo' => 'bar',
386
-	 *              ],
387
-	 *              'allow_redirects' => [
388
-	 *                   'max'       => 10,  // allow at most 10 redirects.
389
-	 *                   'strict'    => true,     // use "strict" RFC compliant redirects.
390
-	 *                   'referer'   => true,     // add a Referer header
391
-	 *                   'protocols' => ['https'] // only allow https URLs
392
-	 *              ],
393
-	 *              'save_to' => '/path/to/file', // save to a file or a stream
394
-	 *              'verify' => true, // bool or string to CA file
395
-	 *              'debug' => true,
396
-	 *              'timeout' => 5,
397
-	 * @return IResponse
398
-	 * @throws \Exception If the request could not get completed
399
-	 */
400
-	public function options(string $uri, array $options = []): IResponse {
401
-		$this->preventLocalAddress($uri, $options);
402
-		$response = $this->client->request('options', $uri, $this->buildRequestOptions($options));
403
-		return new Response($response);
404
-	}
48
+    /** @var GuzzleClient */
49
+    private $client;
50
+    /** @var IConfig */
51
+    private $config;
52
+    /** @var ILogger */
53
+    private $logger;
54
+    /** @var ICertificateManager */
55
+    private $certificateManager;
56
+
57
+    public function __construct(
58
+        IConfig $config,
59
+        ILogger $logger,
60
+        ICertificateManager $certificateManager,
61
+        GuzzleClient $client
62
+    ) {
63
+        $this->config = $config;
64
+        $this->logger = $logger;
65
+        $this->client = $client;
66
+        $this->certificateManager = $certificateManager;
67
+    }
68
+
69
+    private function buildRequestOptions(array $options): array {
70
+        $proxy = $this->getProxyUri();
71
+
72
+        $defaults = [
73
+            RequestOptions::VERIFY => $this->getCertBundle(),
74
+            RequestOptions::TIMEOUT => 30,
75
+        ];
76
+
77
+        // Only add RequestOptions::PROXY if Nextcloud is explicitly
78
+        // configured to use a proxy. This is needed in order not to override
79
+        // Guzzle default values.
80
+        if ($proxy !== null) {
81
+            $defaults[RequestOptions::PROXY] = $proxy;
82
+        }
83
+
84
+        $options = array_merge($defaults, $options);
85
+
86
+        if (!isset($options[RequestOptions::HEADERS]['User-Agent'])) {
87
+            $options[RequestOptions::HEADERS]['User-Agent'] = 'Nextcloud Server Crawler';
88
+        }
89
+
90
+        return $options;
91
+    }
92
+
93
+    private function getCertBundle(): string {
94
+        if ($this->certificateManager->listCertificates() !== []) {
95
+            return $this->certificateManager->getAbsoluteBundlePath();
96
+        }
97
+
98
+        // If the instance is not yet setup we need to use the static path as
99
+        // $this->certificateManager->getAbsoluteBundlePath() tries to instantiiate
100
+        // a view
101
+        if ($this->config->getSystemValue('installed', false)) {
102
+            return $this->certificateManager->getAbsoluteBundlePath(null);
103
+        }
104
+
105
+        return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
106
+    }
107
+
108
+    /**
109
+     * Returns a null or an associative array specifiying the proxy URI for
110
+     * 'http' and 'https' schemes, in addition to a 'no' key value pair
111
+     * providing a list of host names that should not be proxied to.
112
+     *
113
+     * @return array|null
114
+     *
115
+     * The return array looks like:
116
+     * [
117
+     *   'http' => 'username:[email protected]',
118
+     *   'https' => 'username:[email protected]',
119
+     *   'no' => ['foo.com', 'bar.com']
120
+     * ]
121
+     *
122
+     */
123
+    private function getProxyUri(): ?array {
124
+        $proxyHost = $this->config->getSystemValue('proxy', '');
125
+
126
+        if ($proxyHost === '' || $proxyHost === null) {
127
+            return null;
128
+        }
129
+
130
+        $proxyUserPwd = $this->config->getSystemValue('proxyuserpwd', '');
131
+        if ($proxyUserPwd !== '' && $proxyUserPwd !== null) {
132
+            $proxyHost = $proxyUserPwd . '@' . $proxyHost;
133
+        }
134
+
135
+        $proxy = [
136
+            'http' => $proxyHost,
137
+            'https' => $proxyHost,
138
+        ];
139
+
140
+        $proxyExclude = $this->config->getSystemValue('proxyexclude', []);
141
+        if ($proxyExclude !== [] && $proxyExclude !== null) {
142
+            $proxy['no'] = $proxyExclude;
143
+        }
144
+
145
+        return $proxy;
146
+    }
147
+
148
+    protected function preventLocalAddress(string $uri, array $options): void {
149
+        if (($options['nextcloud']['allow_local_address'] ?? false) ||
150
+            $this->config->getSystemValueBool('allow_local_remote_servers', false)) {
151
+            return;
152
+        }
153
+
154
+        $host = parse_url($uri, PHP_URL_HOST);
155
+        if ($host === false) {
156
+            $this->logger->warning("Could not detect any host in $uri");
157
+            throw new LocalServerException('Could not detect any host');
158
+        }
159
+
160
+        $host = strtolower($host);
161
+        // remove brackets from IPv6 addresses
162
+        if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
163
+            $host = substr($host, 1, -1);
164
+        }
165
+
166
+        // Disallow localhost and local network
167
+        if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
168
+            $this->logger->warning("Host $host was not connected to because it violates local access rules");
169
+            throw new LocalServerException('Host violates local access rules');
170
+        }
171
+
172
+        // Disallow hostname only
173
+        if (substr_count($host, '.') === 0) {
174
+            $this->logger->warning("Host $host was not connected to because it violates local access rules");
175
+            throw new LocalServerException('Host violates local access rules');
176
+        }
177
+
178
+        if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
179
+            $this->logger->warning("Host $host was not connected to because it violates local access rules");
180
+            throw new LocalServerException('Host violates local access rules');
181
+        }
182
+
183
+        // Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
184
+        if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
185
+            $delimiter = strrpos($host, ':'); // Get last colon
186
+            $ipv4Address = substr($host, $delimiter + 1);
187
+
188
+            if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
189
+                $this->logger->warning("Host $host was not connected to because it violates local access rules");
190
+                throw new LocalServerException('Host violates local access rules');
191
+            }
192
+        }
193
+    }
194
+
195
+    /**
196
+     * Sends a GET request
197
+     *
198
+     * @param string $uri
199
+     * @param array $options Array such as
200
+     *              'query' => [
201
+     *                  'field' => 'abc',
202
+     *                  'other_field' => '123',
203
+     *                  'file_name' => fopen('/path/to/file', 'r'),
204
+     *              ],
205
+     *              'headers' => [
206
+     *                  'foo' => 'bar',
207
+     *              ],
208
+     *              'cookies' => ['
209
+     *                  'foo' => 'bar',
210
+     *              ],
211
+     *              'allow_redirects' => [
212
+     *                   'max'       => 10,  // allow at most 10 redirects.
213
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
214
+     *                   'referer'   => true,     // add a Referer header
215
+     *                   'protocols' => ['https'] // only allow https URLs
216
+     *              ],
217
+     *              'save_to' => '/path/to/file', // save to a file or a stream
218
+     *              'verify' => true, // bool or string to CA file
219
+     *              'debug' => true,
220
+     *              'timeout' => 5,
221
+     * @return IResponse
222
+     * @throws \Exception If the request could not get completed
223
+     */
224
+    public function get(string $uri, array $options = []): IResponse {
225
+        $this->preventLocalAddress($uri, $options);
226
+        $response = $this->client->request('get', $uri, $this->buildRequestOptions($options));
227
+        $isStream = isset($options['stream']) && $options['stream'];
228
+        return new Response($response, $isStream);
229
+    }
230
+
231
+    /**
232
+     * Sends a HEAD request
233
+     *
234
+     * @param string $uri
235
+     * @param array $options Array such as
236
+     *              'headers' => [
237
+     *                  'foo' => 'bar',
238
+     *              ],
239
+     *              'cookies' => ['
240
+     *                  'foo' => 'bar',
241
+     *              ],
242
+     *              'allow_redirects' => [
243
+     *                   'max'       => 10,  // allow at most 10 redirects.
244
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
245
+     *                   'referer'   => true,     // add a Referer header
246
+     *                   'protocols' => ['https'] // only allow https URLs
247
+     *              ],
248
+     *              'save_to' => '/path/to/file', // save to a file or a stream
249
+     *              'verify' => true, // bool or string to CA file
250
+     *              'debug' => true,
251
+     *              'timeout' => 5,
252
+     * @return IResponse
253
+     * @throws \Exception If the request could not get completed
254
+     */
255
+    public function head(string $uri, array $options = []): IResponse {
256
+        $this->preventLocalAddress($uri, $options);
257
+        $response = $this->client->request('head', $uri, $this->buildRequestOptions($options));
258
+        return new Response($response);
259
+    }
260
+
261
+    /**
262
+     * Sends a POST request
263
+     *
264
+     * @param string $uri
265
+     * @param array $options Array such as
266
+     *              'body' => [
267
+     *                  'field' => 'abc',
268
+     *                  'other_field' => '123',
269
+     *                  'file_name' => fopen('/path/to/file', 'r'),
270
+     *              ],
271
+     *              'headers' => [
272
+     *                  'foo' => 'bar',
273
+     *              ],
274
+     *              'cookies' => ['
275
+     *                  'foo' => 'bar',
276
+     *              ],
277
+     *              'allow_redirects' => [
278
+     *                   'max'       => 10,  // allow at most 10 redirects.
279
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
280
+     *                   'referer'   => true,     // add a Referer header
281
+     *                   'protocols' => ['https'] // only allow https URLs
282
+     *              ],
283
+     *              'save_to' => '/path/to/file', // save to a file or a stream
284
+     *              'verify' => true, // bool or string to CA file
285
+     *              'debug' => true,
286
+     *              'timeout' => 5,
287
+     * @return IResponse
288
+     * @throws \Exception If the request could not get completed
289
+     */
290
+    public function post(string $uri, array $options = []): IResponse {
291
+        $this->preventLocalAddress($uri, $options);
292
+
293
+        if (isset($options['body']) && is_array($options['body'])) {
294
+            $options['form_params'] = $options['body'];
295
+            unset($options['body']);
296
+        }
297
+        $response = $this->client->request('post', $uri, $this->buildRequestOptions($options));
298
+        return new Response($response);
299
+    }
300
+
301
+    /**
302
+     * Sends a PUT request
303
+     *
304
+     * @param string $uri
305
+     * @param array $options Array such as
306
+     *              'body' => [
307
+     *                  'field' => 'abc',
308
+     *                  'other_field' => '123',
309
+     *                  'file_name' => fopen('/path/to/file', 'r'),
310
+     *              ],
311
+     *              'headers' => [
312
+     *                  'foo' => 'bar',
313
+     *              ],
314
+     *              'cookies' => ['
315
+     *                  'foo' => 'bar',
316
+     *              ],
317
+     *              'allow_redirects' => [
318
+     *                   'max'       => 10,  // allow at most 10 redirects.
319
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
320
+     *                   'referer'   => true,     // add a Referer header
321
+     *                   'protocols' => ['https'] // only allow https URLs
322
+     *              ],
323
+     *              'save_to' => '/path/to/file', // save to a file or a stream
324
+     *              'verify' => true, // bool or string to CA file
325
+     *              'debug' => true,
326
+     *              'timeout' => 5,
327
+     * @return IResponse
328
+     * @throws \Exception If the request could not get completed
329
+     */
330
+    public function put(string $uri, array $options = []): IResponse {
331
+        $this->preventLocalAddress($uri, $options);
332
+        $response = $this->client->request('put', $uri, $this->buildRequestOptions($options));
333
+        return new Response($response);
334
+    }
335
+
336
+    /**
337
+     * Sends a DELETE request
338
+     *
339
+     * @param string $uri
340
+     * @param array $options Array such as
341
+     *              'body' => [
342
+     *                  'field' => 'abc',
343
+     *                  'other_field' => '123',
344
+     *                  'file_name' => fopen('/path/to/file', 'r'),
345
+     *              ],
346
+     *              'headers' => [
347
+     *                  'foo' => 'bar',
348
+     *              ],
349
+     *              'cookies' => ['
350
+     *                  'foo' => 'bar',
351
+     *              ],
352
+     *              'allow_redirects' => [
353
+     *                   'max'       => 10,  // allow at most 10 redirects.
354
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
355
+     *                   'referer'   => true,     // add a Referer header
356
+     *                   'protocols' => ['https'] // only allow https URLs
357
+     *              ],
358
+     *              'save_to' => '/path/to/file', // save to a file or a stream
359
+     *              'verify' => true, // bool or string to CA file
360
+     *              'debug' => true,
361
+     *              'timeout' => 5,
362
+     * @return IResponse
363
+     * @throws \Exception If the request could not get completed
364
+     */
365
+    public function delete(string $uri, array $options = []): IResponse {
366
+        $this->preventLocalAddress($uri, $options);
367
+        $response = $this->client->request('delete', $uri, $this->buildRequestOptions($options));
368
+        return new Response($response);
369
+    }
370
+
371
+    /**
372
+     * Sends a options request
373
+     *
374
+     * @param string $uri
375
+     * @param array $options Array such as
376
+     *              'body' => [
377
+     *                  'field' => 'abc',
378
+     *                  'other_field' => '123',
379
+     *                  'file_name' => fopen('/path/to/file', 'r'),
380
+     *              ],
381
+     *              'headers' => [
382
+     *                  'foo' => 'bar',
383
+     *              ],
384
+     *              'cookies' => ['
385
+     *                  'foo' => 'bar',
386
+     *              ],
387
+     *              'allow_redirects' => [
388
+     *                   'max'       => 10,  // allow at most 10 redirects.
389
+     *                   'strict'    => true,     // use "strict" RFC compliant redirects.
390
+     *                   'referer'   => true,     // add a Referer header
391
+     *                   'protocols' => ['https'] // only allow https URLs
392
+     *              ],
393
+     *              'save_to' => '/path/to/file', // save to a file or a stream
394
+     *              'verify' => true, // bool or string to CA file
395
+     *              'debug' => true,
396
+     *              'timeout' => 5,
397
+     * @return IResponse
398
+     * @throws \Exception If the request could not get completed
399
+     */
400
+    public function options(string $uri, array $options = []): IResponse {
401
+        $this->preventLocalAddress($uri, $options);
402
+        $response = $this->client->request('options', $uri, $this->buildRequestOptions($options));
403
+        return new Response($response);
404
+    }
405 405
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 			return $this->certificateManager->getAbsoluteBundlePath(null);
103 103
 		}
104 104
 
105
-		return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
105
+		return \OC::$SERVERROOT.'/resources/config/ca-bundle.crt';
106 106
 	}
107 107
 
108 108
 	/**
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 
130 130
 		$proxyUserPwd = $this->config->getSystemValue('proxyuserpwd', '');
131 131
 		if ($proxyUserPwd !== '' && $proxyUserPwd !== null) {
132
-			$proxyHost = $proxyUserPwd . '@' . $proxyHost;
132
+			$proxyHost = $proxyUserPwd.'@'.$proxyHost;
133 133
 		}
134 134
 
135 135
 		$proxy = [
@@ -175,13 +175,13 @@  discard block
 block discarded – undo
175 175
 			throw new LocalServerException('Host violates local access rules');
176 176
 		}
177 177
 
178
-		if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
178
+		if ((bool) filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
179 179
 			$this->logger->warning("Host $host was not connected to because it violates local access rules");
180 180
 			throw new LocalServerException('Host violates local access rules');
181 181
 		}
182 182
 
183 183
 		// Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
184
-		if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
184
+		if ((bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
185 185
 			$delimiter = strrpos($host, ':'); // Get last colon
186 186
 			$ipv4Address = substr($host, $delimiter + 1);
187 187
 
Please login to merge, or discard this patch.
lib/private/Http/Client/ClientService.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -40,25 +40,25 @@
 block discarded – undo
40 40
  * @package OC\Http
41 41
  */
42 42
 class ClientService implements IClientService {
43
-	/** @var IConfig */
44
-	private $config;
45
-	/** @var ILogger */
46
-	private $logger;
47
-	/** @var ICertificateManager */
48
-	private $certificateManager;
43
+    /** @var IConfig */
44
+    private $config;
45
+    /** @var ILogger */
46
+    private $logger;
47
+    /** @var ICertificateManager */
48
+    private $certificateManager;
49 49
 
50
-	public function __construct(IConfig $config,
51
-								ILogger $logger,
52
-								ICertificateManager $certificateManager) {
53
-		$this->config = $config;
54
-		$this->logger = $logger;
55
-		$this->certificateManager = $certificateManager;
56
-	}
50
+    public function __construct(IConfig $config,
51
+                                ILogger $logger,
52
+                                ICertificateManager $certificateManager) {
53
+        $this->config = $config;
54
+        $this->logger = $logger;
55
+        $this->certificateManager = $certificateManager;
56
+    }
57 57
 
58
-	/**
59
-	 * @return Client
60
-	 */
61
-	public function newClient(): IClient {
62
-		return new Client($this->config, $this->logger, $this->certificateManager, new GuzzleClient());
63
-	}
58
+    /**
59
+     * @return Client
60
+     */
61
+    public function newClient(): IClient {
62
+        return new Client($this->config, $this->logger, $this->certificateManager, new GuzzleClient());
63
+    }
64 64
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +2001 added lines, -2001 removed lines patch added patch discarded remove patch
@@ -242,2010 +242,2010 @@
 block discarded – undo
242 242
  * TODO: hookup all manager classes
243 243
  */
244 244
 class Server extends ServerContainer implements IServerContainer {
245
-	/** @var string */
246
-	private $webRoot;
247
-
248
-	/**
249
-	 * @param string $webRoot
250
-	 * @param \OC\Config $config
251
-	 */
252
-	public function __construct($webRoot, \OC\Config $config) {
253
-		parent::__construct();
254
-		$this->webRoot = $webRoot;
255
-
256
-		// To find out if we are running from CLI or not
257
-		$this->registerParameter('isCLI', \OC::$CLI);
258
-
259
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
260
-			return $c;
261
-		});
262
-
263
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
264
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
265
-
266
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
267
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
268
-
269
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
270
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
271
-
272
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
273
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
274
-
275
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
276
-
277
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
278
-
279
-
280
-		$this->registerService(IPreview::class, function (Server $c) {
281
-			return new PreviewManager(
282
-				$c->getConfig(),
283
-				$c->getRootFolder(),
284
-				$c->getAppDataDir('preview'),
285
-				$c->getEventDispatcher(),
286
-				$c->getGeneratorHelper(),
287
-				$c->getSession()->get('user_id')
288
-			);
289
-		});
290
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
291
-
292
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
293
-			return new \OC\Preview\Watcher(
294
-				$c->getAppDataDir('preview')
295
-			);
296
-		});
297
-
298
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
299
-			$view = new View();
300
-			$util = new Encryption\Util(
301
-				$view,
302
-				$c->getUserManager(),
303
-				$c->getGroupManager(),
304
-				$c->getConfig()
305
-			);
306
-			return new Encryption\Manager(
307
-				$c->getConfig(),
308
-				$c->getLogger(),
309
-				$c->getL10N('core'),
310
-				new View(),
311
-				$util,
312
-				new ArrayCache()
313
-			);
314
-		});
315
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
316
-
317
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
318
-			$util = new Encryption\Util(
319
-				new View(),
320
-				$c->getUserManager(),
321
-				$c->getGroupManager(),
322
-				$c->getConfig()
323
-			);
324
-			return new Encryption\File(
325
-				$util,
326
-				$c->getRootFolder(),
327
-				$c->getShareManager()
328
-			);
329
-		});
330
-
331
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
332
-			$view = new View();
333
-			$util = new Encryption\Util(
334
-				$view,
335
-				$c->getUserManager(),
336
-				$c->getGroupManager(),
337
-				$c->getConfig()
338
-			);
339
-
340
-			return new Encryption\Keys\Storage($view, $util);
341
-		});
342
-		$this->registerService('TagMapper', function (Server $c) {
343
-			return new TagMapper($c->getDatabaseConnection());
344
-		});
345
-
346
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
347
-			$tagMapper = $c->query('TagMapper');
348
-			return new TagManager($tagMapper, $c->getUserSession());
349
-		});
350
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
351
-
352
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
353
-			$config = $c->getConfig();
354
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
355
-			return new $factoryClass($this);
356
-		});
357
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
358
-			return $c->query('SystemTagManagerFactory')->getManager();
359
-		});
360
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
361
-
362
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
363
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
364
-		});
365
-		$this->registerService('RootFolder', function (Server $c) {
366
-			$manager = \OC\Files\Filesystem::getMountManager(null);
367
-			$view = new View();
368
-			$root = new Root(
369
-				$manager,
370
-				$view,
371
-				null,
372
-				$c->getUserMountCache(),
373
-				$this->getLogger(),
374
-				$this->getUserManager()
375
-			);
376
-			$connector = new HookConnector($root, $view, $c->getEventDispatcher());
377
-			$connector->viewToNode();
378
-
379
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
380
-			$previewConnector->connectWatcher();
381
-
382
-			return $root;
383
-		});
384
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
385
-
386
-		$this->registerService(IRootFolder::class, function (Server $c) {
387
-			return new LazyRoot(function () use ($c) {
388
-				return $c->query('RootFolder');
389
-			});
390
-		});
391
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
392
-
393
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
394
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
395
-
396
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
397
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
398
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
399
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
400
-
401
-				/** @var IEventDispatcher $dispatcher */
402
-				$dispatcher = $this->query(IEventDispatcher::class);
403
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
404
-			});
405
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
406
-				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
407
-
408
-				/** @var IEventDispatcher $dispatcher */
409
-				$dispatcher = $this->query(IEventDispatcher::class);
410
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
411
-			});
412
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
413
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
414
-
415
-				/** @var IEventDispatcher $dispatcher */
416
-				$dispatcher = $this->query(IEventDispatcher::class);
417
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
418
-			});
419
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
420
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
421
-
422
-				/** @var IEventDispatcher $dispatcher */
423
-				$dispatcher = $this->query(IEventDispatcher::class);
424
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
425
-			});
426
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
427
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
428
-
429
-				/** @var IEventDispatcher $dispatcher */
430
-				$dispatcher = $this->query(IEventDispatcher::class);
431
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
432
-			});
433
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
434
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
435
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
436
-				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
437
-
438
-				/** @var IEventDispatcher $dispatcher */
439
-				$dispatcher = $this->query(IEventDispatcher::class);
440
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
441
-			});
442
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
443
-				/** @var IEventDispatcher $dispatcher */
444
-				$dispatcher = $this->query(IEventDispatcher::class);
445
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
446
-			});
447
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
448
-				/** @var IEventDispatcher $dispatcher */
449
-				$dispatcher = $this->query(IEventDispatcher::class);
450
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
451
-			});
452
-			return $groupManager;
453
-		});
454
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
455
-
456
-		$this->registerService(Store::class, function (Server $c) {
457
-			$session = $c->getSession();
458
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
459
-				$tokenProvider = $c->query(IProvider::class);
460
-			} else {
461
-				$tokenProvider = null;
462
-			}
463
-			$logger = $c->getLogger();
464
-			return new Store($session, $logger, $tokenProvider);
465
-		});
466
-		$this->registerAlias(IStore::class, Store::class);
467
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
468
-			$dbConnection = $c->getDatabaseConnection();
469
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
470
-		});
471
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
472
-
473
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
474
-			$manager = $c->getUserManager();
475
-			$session = new \OC\Session\Memory('');
476
-			$timeFactory = new TimeFactory();
477
-			// Token providers might require a working database. This code
478
-			// might however be called when ownCloud is not yet setup.
479
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
480
-				$defaultTokenProvider = $c->query(IProvider::class);
481
-			} else {
482
-				$defaultTokenProvider = null;
483
-			}
484
-
485
-			$legacyDispatcher = $c->getEventDispatcher();
486
-
487
-			$userSession = new \OC\User\Session(
488
-				$manager,
489
-				$session,
490
-				$timeFactory,
491
-				$defaultTokenProvider,
492
-				$c->getConfig(),
493
-				$c->getSecureRandom(),
494
-				$c->getLockdownManager(),
495
-				$c->getLogger(),
496
-				$c->query(IEventDispatcher::class)
497
-			);
498
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
499
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
500
-
501
-				/** @var IEventDispatcher $dispatcher */
502
-				$dispatcher = $this->query(IEventDispatcher::class);
503
-				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
504
-			});
505
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
506
-				/** @var $user \OC\User\User */
507
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
508
-
509
-				/** @var IEventDispatcher $dispatcher */
510
-				$dispatcher = $this->query(IEventDispatcher::class);
511
-				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
512
-			});
513
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
514
-				/** @var $user \OC\User\User */
515
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
516
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
517
-
518
-				/** @var IEventDispatcher $dispatcher */
519
-				$dispatcher = $this->query(IEventDispatcher::class);
520
-				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
521
-			});
522
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
523
-				/** @var $user \OC\User\User */
524
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
525
-
526
-				/** @var IEventDispatcher $dispatcher */
527
-				$dispatcher = $this->query(IEventDispatcher::class);
528
-				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
529
-			});
530
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
531
-				/** @var $user \OC\User\User */
532
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
533
-
534
-				/** @var IEventDispatcher $dispatcher */
535
-				$dispatcher = $this->query(IEventDispatcher::class);
536
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
537
-			});
538
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
539
-				/** @var $user \OC\User\User */
540
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
541
-
542
-				/** @var IEventDispatcher $dispatcher */
543
-				$dispatcher = $this->query(IEventDispatcher::class);
544
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
545
-			});
546
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
547
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
548
-
549
-				/** @var IEventDispatcher $dispatcher */
550
-				$dispatcher = $this->query(IEventDispatcher::class);
551
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
552
-			});
553
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
554
-				/** @var $user \OC\User\User */
555
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
556
-
557
-				/** @var IEventDispatcher $dispatcher */
558
-				$dispatcher = $this->query(IEventDispatcher::class);
559
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
560
-			});
561
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
562
-				/** @var IEventDispatcher $dispatcher */
563
-				$dispatcher = $this->query(IEventDispatcher::class);
564
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
565
-			});
566
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
567
-				/** @var $user \OC\User\User */
568
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
569
-
570
-				/** @var IEventDispatcher $dispatcher */
571
-				$dispatcher = $this->query(IEventDispatcher::class);
572
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
573
-			});
574
-			$userSession->listen('\OC\User', 'logout', function ($user) {
575
-				\OC_Hook::emit('OC_User', 'logout', []);
576
-
577
-				/** @var IEventDispatcher $dispatcher */
578
-				$dispatcher = $this->query(IEventDispatcher::class);
579
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
580
-			});
581
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
582
-				/** @var IEventDispatcher $dispatcher */
583
-				$dispatcher = $this->query(IEventDispatcher::class);
584
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
585
-			});
586
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
587
-				/** @var $user \OC\User\User */
588
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
589
-
590
-				/** @var IEventDispatcher $dispatcher */
591
-				$dispatcher = $this->query(IEventDispatcher::class);
592
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
593
-			});
594
-			return $userSession;
595
-		});
596
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
597
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
598
-
599
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
600
-
601
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
602
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
603
-
604
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
605
-			return new \OC\AllConfig(
606
-				$c->getSystemConfig()
607
-			);
608
-		});
609
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
610
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
611
-
612
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
613
-			return new \OC\SystemConfig($config);
614
-		});
615
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
616
-
617
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
618
-			return new \OC\AppConfig($c->getDatabaseConnection());
619
-		});
620
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
621
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
622
-
623
-		$this->registerService(IFactory::class, function (Server $c) {
624
-			return new \OC\L10N\Factory(
625
-				$c->getConfig(),
626
-				$c->getRequest(),
627
-				$c->getUserSession(),
628
-				\OC::$SERVERROOT
629
-			);
630
-		});
631
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
632
-
633
-		$this->registerService(IURLGenerator::class, function (Server $c) {
634
-			$config = $c->getConfig();
635
-			$cacheFactory = $c->getMemCacheFactory();
636
-			$request = $c->getRequest();
637
-			return new \OC\URLGenerator(
638
-				$config,
639
-				$cacheFactory,
640
-				$request
641
-			);
642
-		});
643
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
644
-
645
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
646
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
647
-
648
-		$this->registerService(ICache::class, function ($c) {
649
-			return new Cache\File();
650
-		});
651
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
652
-
653
-		$this->registerService(Factory::class, function (Server $c) {
654
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
655
-				ArrayCache::class,
656
-				ArrayCache::class,
657
-				ArrayCache::class
658
-			);
659
-			$config = $c->getConfig();
660
-
661
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
662
-				$v = \OC_App::getAppVersions();
663
-				$v['core'] = implode(',', \OC_Util::getVersion());
664
-				$version = implode(',', $v);
665
-				$instanceId = \OC_Util::getInstanceId();
666
-				$path = \OC::$SERVERROOT;
667
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
668
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
669
-					$config->getSystemValue('memcache.local', null),
670
-					$config->getSystemValue('memcache.distributed', null),
671
-					$config->getSystemValue('memcache.locking', null)
672
-				);
673
-			}
674
-			return $arrayCacheFactory;
675
-		});
676
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
677
-		$this->registerAlias(ICacheFactory::class, Factory::class);
678
-
679
-		$this->registerService('RedisFactory', function (Server $c) {
680
-			$systemConfig = $c->getSystemConfig();
681
-			return new RedisFactory($systemConfig);
682
-		});
683
-
684
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
685
-			return new \OC\Activity\Manager(
686
-				$c->getRequest(),
687
-				$c->getUserSession(),
688
-				$c->getConfig(),
689
-				$c->query(IValidator::class)
690
-			);
691
-		});
692
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
693
-
694
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
695
-			return new \OC\Activity\EventMerger(
696
-				$c->getL10N('lib')
697
-			);
698
-		});
699
-		$this->registerAlias(IValidator::class, Validator::class);
700
-
701
-		$this->registerService(AvatarManager::class, function (Server $c) {
702
-			return new AvatarManager(
703
-				$c->query(\OC\User\Manager::class),
704
-				$c->getAppDataDir('avatar'),
705
-				$c->getL10N('lib'),
706
-				$c->getLogger(),
707
-				$c->getConfig()
708
-			);
709
-		});
710
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
711
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
712
-
713
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
714
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
715
-
716
-		$this->registerService(\OC\Log::class, function (Server $c) {
717
-			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
718
-			$factory = new LogFactory($c, $this->getSystemConfig());
719
-			$logger = $factory->get($logType);
720
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
721
-
722
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
723
-		});
724
-		$this->registerAlias(ILogger::class, \OC\Log::class);
725
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
726
-		// PSR-3 logger
727
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
728
-
729
-		$this->registerService(ILogFactory::class, function (Server $c) {
730
-			return new LogFactory($c, $this->getSystemConfig());
731
-		});
732
-
733
-		$this->registerService(IJobList::class, function (Server $c) {
734
-			$config = $c->getConfig();
735
-			return new \OC\BackgroundJob\JobList(
736
-				$c->getDatabaseConnection(),
737
-				$config,
738
-				new TimeFactory()
739
-			);
740
-		});
741
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
742
-
743
-		$this->registerService(IRouter::class, function (Server $c) {
744
-			$cacheFactory = $c->getMemCacheFactory();
745
-			$logger = $c->getLogger();
746
-			if ($cacheFactory->isLocalCacheAvailable()) {
747
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
748
-			} else {
749
-				$router = new \OC\Route\Router($logger);
750
-			}
751
-			return $router;
752
-		});
753
-		$this->registerDeprecatedAlias('Router', IRouter::class);
754
-
755
-		$this->registerService(ISearch::class, function ($c) {
756
-			return new Search();
757
-		});
758
-		$this->registerDeprecatedAlias('Search', ISearch::class);
759
-
760
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
761
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
762
-				$this->getMemCacheFactory(),
763
-				new \OC\AppFramework\Utility\TimeFactory()
764
-			);
765
-		});
766
-
767
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
768
-			return new SecureRandom();
769
-		});
770
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
771
-
772
-		$this->registerService(ICrypto::class, function (Server $c) {
773
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
774
-		});
775
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
776
-
777
-		$this->registerService(IHasher::class, function (Server $c) {
778
-			return new Hasher($c->getConfig());
779
-		});
780
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
781
-
782
-		$this->registerService(ICredentialsManager::class, function (Server $c) {
783
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
784
-		});
785
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
786
-
787
-		$this->registerService(IDBConnection::class, function (Server $c) {
788
-			$systemConfig = $c->getSystemConfig();
789
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
790
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
791
-			if (!$factory->isValidType($type)) {
792
-				throw new \OC\DatabaseException('Invalid database type');
793
-			}
794
-			$connectionParams = $factory->createConnectionParams();
795
-			$connection = $factory->getConnection($type, $connectionParams);
796
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
797
-			return $connection;
798
-		});
799
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
800
-
801
-
802
-		$this->registerService(IClientService::class, function (Server $c) {
803
-			$user = \OC_User::getUser();
804
-			$uid = $user ? $user : null;
805
-			return new ClientService(
806
-				$c->getConfig(),
807
-				$c->getLogger(),
808
-				new \OC\Security\CertificateManager(
809
-					$uid,
810
-					new View(),
811
-					$c->getConfig(),
812
-					$c->getLogger(),
813
-					$c->getSecureRandom()
814
-				)
815
-			);
816
-		});
817
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
818
-		$this->registerService(IEventLogger::class, function (Server $c) {
819
-			$eventLogger = new EventLogger();
820
-			if ($c->getSystemConfig()->getValue('debug', false)) {
821
-				// In debug mode, module is being activated by default
822
-				$eventLogger->activate();
823
-			}
824
-			return $eventLogger;
825
-		});
826
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
827
-
828
-		$this->registerService(IQueryLogger::class, function (Server $c) {
829
-			$queryLogger = new QueryLogger();
830
-			if ($c->getSystemConfig()->getValue('debug', false)) {
831
-				// In debug mode, module is being activated by default
832
-				$queryLogger->activate();
833
-			}
834
-			return $queryLogger;
835
-		});
836
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
837
-
838
-		$this->registerService(TempManager::class, function (Server $c) {
839
-			return new TempManager(
840
-				$c->getLogger(),
841
-				$c->getConfig()
842
-			);
843
-		});
844
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
845
-		$this->registerAlias(ITempManager::class, TempManager::class);
846
-
847
-		$this->registerService(AppManager::class, function (Server $c) {
848
-			return new \OC\App\AppManager(
849
-				$c->getUserSession(),
850
-				$c->getConfig(),
851
-				$c->query(\OC\AppConfig::class),
852
-				$c->getGroupManager(),
853
-				$c->getMemCacheFactory(),
854
-				$c->getEventDispatcher(),
855
-				$c->getLogger()
856
-			);
857
-		});
858
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
859
-		$this->registerAlias(IAppManager::class, AppManager::class);
860
-
861
-		$this->registerService(IDateTimeZone::class, function (Server $c) {
862
-			return new DateTimeZone(
863
-				$c->getConfig(),
864
-				$c->getSession()
865
-			);
866
-		});
867
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
868
-
869
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
870
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
871
-
872
-			return new DateTimeFormatter(
873
-				$c->getDateTimeZone()->getTimeZone(),
874
-				$c->getL10N('lib', $language)
875
-			);
876
-		});
877
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
878
-
879
-		$this->registerService(IUserMountCache::class, function (Server $c) {
880
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
881
-			$listener = new UserMountCacheListener($mountCache);
882
-			$listener->listen($c->getUserManager());
883
-			return $mountCache;
884
-		});
885
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
886
-
887
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
888
-			$loader = \OC\Files\Filesystem::getLoader();
889
-			$mountCache = $c->query(IUserMountCache::class);
890
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
891
-
892
-			// builtin providers
893
-
894
-			$config = $c->getConfig();
895
-			$manager->registerProvider(new CacheMountProvider($config));
896
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
897
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
898
-
899
-			return $manager;
900
-		});
901
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
902
-
903
-		$this->registerService('IniWrapper', function ($c) {
904
-			return new IniGetWrapper();
905
-		});
906
-		$this->registerService('AsyncCommandBus', function (Server $c) {
907
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
908
-			if ($busClass) {
909
-				list($app, $class) = explode('::', $busClass, 2);
910
-				if ($c->getAppManager()->isInstalled($app)) {
911
-					\OC_App::loadApp($app);
912
-					return $c->query($class);
913
-				} else {
914
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
915
-				}
916
-			} else {
917
-				$jobList = $c->getJobList();
918
-				return new CronBus($jobList);
919
-			}
920
-		});
921
-		$this->registerService('TrustedDomainHelper', function ($c) {
922
-			return new TrustedDomainHelper($this->getConfig());
923
-		});
924
-		$this->registerService(Throttler::class, function (Server $c) {
925
-			return new Throttler(
926
-				$c->getDatabaseConnection(),
927
-				new TimeFactory(),
928
-				$c->getLogger(),
929
-				$c->getConfig()
930
-			);
931
-		});
932
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
933
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
934
-			// IConfig and IAppManager requires a working database. This code
935
-			// might however be called when ownCloud is not yet setup.
936
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
937
-				$config = $c->getConfig();
938
-				$appManager = $c->getAppManager();
939
-			} else {
940
-				$config = null;
941
-				$appManager = null;
942
-			}
943
-
944
-			return new Checker(
945
-				new EnvironmentHelper(),
946
-				new FileAccessHelper(),
947
-				new AppLocator(),
948
-				$config,
949
-				$c->getMemCacheFactory(),
950
-				$appManager,
951
-				$c->getTempManager(),
952
-				$c->getMimeTypeDetector()
953
-			);
954
-		});
955
-		$this->registerService(\OCP\IRequest::class, function ($c) {
956
-			if (isset($this['urlParams'])) {
957
-				$urlParams = $this['urlParams'];
958
-			} else {
959
-				$urlParams = [];
960
-			}
961
-
962
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
963
-				&& in_array('fakeinput', stream_get_wrappers())
964
-			) {
965
-				$stream = 'fakeinput://data';
966
-			} else {
967
-				$stream = 'php://input';
968
-			}
969
-
970
-			return new Request(
971
-				[
972
-					'get' => $_GET,
973
-					'post' => $_POST,
974
-					'files' => $_FILES,
975
-					'server' => $_SERVER,
976
-					'env' => $_ENV,
977
-					'cookies' => $_COOKIE,
978
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
979
-						? $_SERVER['REQUEST_METHOD']
980
-						: '',
981
-					'urlParams' => $urlParams,
982
-				],
983
-				$this->getSecureRandom(),
984
-				$this->getConfig(),
985
-				$this->getCsrfTokenManager(),
986
-				$stream
987
-			);
988
-		});
989
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
990
-
991
-		$this->registerService(IMailer::class, function (Server $c) {
992
-			return new Mailer(
993
-				$c->getConfig(),
994
-				$c->getLogger(),
995
-				$c->query(Defaults::class),
996
-				$c->getURLGenerator(),
997
-				$c->getL10N('lib'),
998
-				$c->query(IEventDispatcher::class)
999
-			);
1000
-		});
1001
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1002
-
1003
-		$this->registerService('LDAPProvider', function (Server $c) {
1004
-			$config = $c->getConfig();
1005
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1006
-			if (is_null($factoryClass)) {
1007
-				throw new \Exception('ldapProviderFactory not set');
1008
-			}
1009
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1010
-			$factory = new $factoryClass($this);
1011
-			return $factory->getLDAPProvider();
1012
-		});
1013
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1014
-			$ini = $c->getIniWrapper();
1015
-			$config = $c->getConfig();
1016
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1017
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1018
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1019
-				$memcacheFactory = $c->getMemCacheFactory();
1020
-				$memcache = $memcacheFactory->createLocking('lock');
1021
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1022
-					return new MemcacheLockingProvider($memcache, $ttl);
1023
-				}
1024
-				return new DBLockingProvider(
1025
-					$c->getDatabaseConnection(),
1026
-					$c->getLogger(),
1027
-					new TimeFactory(),
1028
-					$ttl,
1029
-					!\OC::$CLI
1030
-				);
1031
-			}
1032
-			return new NoopLockingProvider();
1033
-		});
1034
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1035
-
1036
-		$this->registerService(IMountManager::class, function () {
1037
-			return new \OC\Files\Mount\Manager();
1038
-		});
1039
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1040
-
1041
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1042
-			return new \OC\Files\Type\Detection(
1043
-				$c->getURLGenerator(),
1044
-				$c->getLogger(),
1045
-				\OC::$configDir,
1046
-				\OC::$SERVERROOT . '/resources/config/'
1047
-			);
1048
-		});
1049
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1050
-
1051
-		$this->registerService(IMimeTypeLoader::class, function (Server $c) {
1052
-			return new \OC\Files\Type\Loader(
1053
-				$c->getDatabaseConnection()
1054
-			);
1055
-		});
1056
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1057
-		$this->registerService(BundleFetcher::class, function () {
1058
-			return new BundleFetcher($this->getL10N('lib'));
1059
-		});
1060
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1061
-			return new Manager(
1062
-				$c->query(IValidator::class),
1063
-				$c->getLogger()
1064
-			);
1065
-		});
1066
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1067
-
1068
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1069
-			$manager = new CapabilitiesManager($c->getLogger());
1070
-			$manager->registerCapability(function () use ($c) {
1071
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
1072
-			});
1073
-			$manager->registerCapability(function () use ($c) {
1074
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1075
-			});
1076
-			return $manager;
1077
-		});
1078
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1079
-
1080
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1081
-			$config = $c->getConfig();
1082
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1083
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1084
-			$factory = new $factoryClass($this);
1085
-			$manager = $factory->getManager();
1086
-
1087
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1088
-				$manager = $c->getUserManager();
1089
-				$user = $manager->get($id);
1090
-				if (is_null($user)) {
1091
-					$l = $c->getL10N('core');
1092
-					$displayName = $l->t('Unknown user');
1093
-				} else {
1094
-					$displayName = $user->getDisplayName();
1095
-				}
1096
-				return $displayName;
1097
-			});
1098
-
1099
-			return $manager;
1100
-		});
1101
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1102
-
1103
-		$this->registerService('ThemingDefaults', function (Server $c) {
1104
-			/*
245
+    /** @var string */
246
+    private $webRoot;
247
+
248
+    /**
249
+     * @param string $webRoot
250
+     * @param \OC\Config $config
251
+     */
252
+    public function __construct($webRoot, \OC\Config $config) {
253
+        parent::__construct();
254
+        $this->webRoot = $webRoot;
255
+
256
+        // To find out if we are running from CLI or not
257
+        $this->registerParameter('isCLI', \OC::$CLI);
258
+
259
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
260
+            return $c;
261
+        });
262
+
263
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
264
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
265
+
266
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
267
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
268
+
269
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
270
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
271
+
272
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
273
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
274
+
275
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
276
+
277
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
278
+
279
+
280
+        $this->registerService(IPreview::class, function (Server $c) {
281
+            return new PreviewManager(
282
+                $c->getConfig(),
283
+                $c->getRootFolder(),
284
+                $c->getAppDataDir('preview'),
285
+                $c->getEventDispatcher(),
286
+                $c->getGeneratorHelper(),
287
+                $c->getSession()->get('user_id')
288
+            );
289
+        });
290
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
291
+
292
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
293
+            return new \OC\Preview\Watcher(
294
+                $c->getAppDataDir('preview')
295
+            );
296
+        });
297
+
298
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
299
+            $view = new View();
300
+            $util = new Encryption\Util(
301
+                $view,
302
+                $c->getUserManager(),
303
+                $c->getGroupManager(),
304
+                $c->getConfig()
305
+            );
306
+            return new Encryption\Manager(
307
+                $c->getConfig(),
308
+                $c->getLogger(),
309
+                $c->getL10N('core'),
310
+                new View(),
311
+                $util,
312
+                new ArrayCache()
313
+            );
314
+        });
315
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
316
+
317
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
318
+            $util = new Encryption\Util(
319
+                new View(),
320
+                $c->getUserManager(),
321
+                $c->getGroupManager(),
322
+                $c->getConfig()
323
+            );
324
+            return new Encryption\File(
325
+                $util,
326
+                $c->getRootFolder(),
327
+                $c->getShareManager()
328
+            );
329
+        });
330
+
331
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
332
+            $view = new View();
333
+            $util = new Encryption\Util(
334
+                $view,
335
+                $c->getUserManager(),
336
+                $c->getGroupManager(),
337
+                $c->getConfig()
338
+            );
339
+
340
+            return new Encryption\Keys\Storage($view, $util);
341
+        });
342
+        $this->registerService('TagMapper', function (Server $c) {
343
+            return new TagMapper($c->getDatabaseConnection());
344
+        });
345
+
346
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
347
+            $tagMapper = $c->query('TagMapper');
348
+            return new TagManager($tagMapper, $c->getUserSession());
349
+        });
350
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
351
+
352
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
353
+            $config = $c->getConfig();
354
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
355
+            return new $factoryClass($this);
356
+        });
357
+        $this->registerService(ISystemTagManager::class, function (Server $c) {
358
+            return $c->query('SystemTagManagerFactory')->getManager();
359
+        });
360
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
361
+
362
+        $this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
363
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
364
+        });
365
+        $this->registerService('RootFolder', function (Server $c) {
366
+            $manager = \OC\Files\Filesystem::getMountManager(null);
367
+            $view = new View();
368
+            $root = new Root(
369
+                $manager,
370
+                $view,
371
+                null,
372
+                $c->getUserMountCache(),
373
+                $this->getLogger(),
374
+                $this->getUserManager()
375
+            );
376
+            $connector = new HookConnector($root, $view, $c->getEventDispatcher());
377
+            $connector->viewToNode();
378
+
379
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
380
+            $previewConnector->connectWatcher();
381
+
382
+            return $root;
383
+        });
384
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
385
+
386
+        $this->registerService(IRootFolder::class, function (Server $c) {
387
+            return new LazyRoot(function () use ($c) {
388
+                return $c->query('RootFolder');
389
+            });
390
+        });
391
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
392
+
393
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
394
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
395
+
396
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
397
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
398
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
399
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
400
+
401
+                /** @var IEventDispatcher $dispatcher */
402
+                $dispatcher = $this->query(IEventDispatcher::class);
403
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
404
+            });
405
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
406
+                \OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
407
+
408
+                /** @var IEventDispatcher $dispatcher */
409
+                $dispatcher = $this->query(IEventDispatcher::class);
410
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
411
+            });
412
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
413
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
414
+
415
+                /** @var IEventDispatcher $dispatcher */
416
+                $dispatcher = $this->query(IEventDispatcher::class);
417
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
418
+            });
419
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
420
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
421
+
422
+                /** @var IEventDispatcher $dispatcher */
423
+                $dispatcher = $this->query(IEventDispatcher::class);
424
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
425
+            });
426
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
427
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
428
+
429
+                /** @var IEventDispatcher $dispatcher */
430
+                $dispatcher = $this->query(IEventDispatcher::class);
431
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
432
+            });
433
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
434
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
435
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
436
+                \OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
437
+
438
+                /** @var IEventDispatcher $dispatcher */
439
+                $dispatcher = $this->query(IEventDispatcher::class);
440
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
441
+            });
442
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
443
+                /** @var IEventDispatcher $dispatcher */
444
+                $dispatcher = $this->query(IEventDispatcher::class);
445
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
446
+            });
447
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
448
+                /** @var IEventDispatcher $dispatcher */
449
+                $dispatcher = $this->query(IEventDispatcher::class);
450
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
451
+            });
452
+            return $groupManager;
453
+        });
454
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
455
+
456
+        $this->registerService(Store::class, function (Server $c) {
457
+            $session = $c->getSession();
458
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
459
+                $tokenProvider = $c->query(IProvider::class);
460
+            } else {
461
+                $tokenProvider = null;
462
+            }
463
+            $logger = $c->getLogger();
464
+            return new Store($session, $logger, $tokenProvider);
465
+        });
466
+        $this->registerAlias(IStore::class, Store::class);
467
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
468
+            $dbConnection = $c->getDatabaseConnection();
469
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
470
+        });
471
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
472
+
473
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
474
+            $manager = $c->getUserManager();
475
+            $session = new \OC\Session\Memory('');
476
+            $timeFactory = new TimeFactory();
477
+            // Token providers might require a working database. This code
478
+            // might however be called when ownCloud is not yet setup.
479
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
480
+                $defaultTokenProvider = $c->query(IProvider::class);
481
+            } else {
482
+                $defaultTokenProvider = null;
483
+            }
484
+
485
+            $legacyDispatcher = $c->getEventDispatcher();
486
+
487
+            $userSession = new \OC\User\Session(
488
+                $manager,
489
+                $session,
490
+                $timeFactory,
491
+                $defaultTokenProvider,
492
+                $c->getConfig(),
493
+                $c->getSecureRandom(),
494
+                $c->getLockdownManager(),
495
+                $c->getLogger(),
496
+                $c->query(IEventDispatcher::class)
497
+            );
498
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
499
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
500
+
501
+                /** @var IEventDispatcher $dispatcher */
502
+                $dispatcher = $this->query(IEventDispatcher::class);
503
+                $dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
504
+            });
505
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
506
+                /** @var $user \OC\User\User */
507
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
508
+
509
+                /** @var IEventDispatcher $dispatcher */
510
+                $dispatcher = $this->query(IEventDispatcher::class);
511
+                $dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
512
+            });
513
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
514
+                /** @var $user \OC\User\User */
515
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
516
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
517
+
518
+                /** @var IEventDispatcher $dispatcher */
519
+                $dispatcher = $this->query(IEventDispatcher::class);
520
+                $dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
521
+            });
522
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
523
+                /** @var $user \OC\User\User */
524
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
525
+
526
+                /** @var IEventDispatcher $dispatcher */
527
+                $dispatcher = $this->query(IEventDispatcher::class);
528
+                $dispatcher->dispatchTyped(new UserDeletedEvent($user));
529
+            });
530
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
531
+                /** @var $user \OC\User\User */
532
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
533
+
534
+                /** @var IEventDispatcher $dispatcher */
535
+                $dispatcher = $this->query(IEventDispatcher::class);
536
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
537
+            });
538
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
539
+                /** @var $user \OC\User\User */
540
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
541
+
542
+                /** @var IEventDispatcher $dispatcher */
543
+                $dispatcher = $this->query(IEventDispatcher::class);
544
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
545
+            });
546
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
547
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
548
+
549
+                /** @var IEventDispatcher $dispatcher */
550
+                $dispatcher = $this->query(IEventDispatcher::class);
551
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
552
+            });
553
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
554
+                /** @var $user \OC\User\User */
555
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
556
+
557
+                /** @var IEventDispatcher $dispatcher */
558
+                $dispatcher = $this->query(IEventDispatcher::class);
559
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
560
+            });
561
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
562
+                /** @var IEventDispatcher $dispatcher */
563
+                $dispatcher = $this->query(IEventDispatcher::class);
564
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
565
+            });
566
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
567
+                /** @var $user \OC\User\User */
568
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
569
+
570
+                /** @var IEventDispatcher $dispatcher */
571
+                $dispatcher = $this->query(IEventDispatcher::class);
572
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
573
+            });
574
+            $userSession->listen('\OC\User', 'logout', function ($user) {
575
+                \OC_Hook::emit('OC_User', 'logout', []);
576
+
577
+                /** @var IEventDispatcher $dispatcher */
578
+                $dispatcher = $this->query(IEventDispatcher::class);
579
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
580
+            });
581
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
582
+                /** @var IEventDispatcher $dispatcher */
583
+                $dispatcher = $this->query(IEventDispatcher::class);
584
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
585
+            });
586
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
587
+                /** @var $user \OC\User\User */
588
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
589
+
590
+                /** @var IEventDispatcher $dispatcher */
591
+                $dispatcher = $this->query(IEventDispatcher::class);
592
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
593
+            });
594
+            return $userSession;
595
+        });
596
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
597
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
598
+
599
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
600
+
601
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
602
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
603
+
604
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
605
+            return new \OC\AllConfig(
606
+                $c->getSystemConfig()
607
+            );
608
+        });
609
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
610
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
611
+
612
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
613
+            return new \OC\SystemConfig($config);
614
+        });
615
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
616
+
617
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
618
+            return new \OC\AppConfig($c->getDatabaseConnection());
619
+        });
620
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
621
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
622
+
623
+        $this->registerService(IFactory::class, function (Server $c) {
624
+            return new \OC\L10N\Factory(
625
+                $c->getConfig(),
626
+                $c->getRequest(),
627
+                $c->getUserSession(),
628
+                \OC::$SERVERROOT
629
+            );
630
+        });
631
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
632
+
633
+        $this->registerService(IURLGenerator::class, function (Server $c) {
634
+            $config = $c->getConfig();
635
+            $cacheFactory = $c->getMemCacheFactory();
636
+            $request = $c->getRequest();
637
+            return new \OC\URLGenerator(
638
+                $config,
639
+                $cacheFactory,
640
+                $request
641
+            );
642
+        });
643
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
644
+
645
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
646
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
647
+
648
+        $this->registerService(ICache::class, function ($c) {
649
+            return new Cache\File();
650
+        });
651
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
652
+
653
+        $this->registerService(Factory::class, function (Server $c) {
654
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
655
+                ArrayCache::class,
656
+                ArrayCache::class,
657
+                ArrayCache::class
658
+            );
659
+            $config = $c->getConfig();
660
+
661
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
662
+                $v = \OC_App::getAppVersions();
663
+                $v['core'] = implode(',', \OC_Util::getVersion());
664
+                $version = implode(',', $v);
665
+                $instanceId = \OC_Util::getInstanceId();
666
+                $path = \OC::$SERVERROOT;
667
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
668
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
669
+                    $config->getSystemValue('memcache.local', null),
670
+                    $config->getSystemValue('memcache.distributed', null),
671
+                    $config->getSystemValue('memcache.locking', null)
672
+                );
673
+            }
674
+            return $arrayCacheFactory;
675
+        });
676
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
677
+        $this->registerAlias(ICacheFactory::class, Factory::class);
678
+
679
+        $this->registerService('RedisFactory', function (Server $c) {
680
+            $systemConfig = $c->getSystemConfig();
681
+            return new RedisFactory($systemConfig);
682
+        });
683
+
684
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
685
+            return new \OC\Activity\Manager(
686
+                $c->getRequest(),
687
+                $c->getUserSession(),
688
+                $c->getConfig(),
689
+                $c->query(IValidator::class)
690
+            );
691
+        });
692
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
693
+
694
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
695
+            return new \OC\Activity\EventMerger(
696
+                $c->getL10N('lib')
697
+            );
698
+        });
699
+        $this->registerAlias(IValidator::class, Validator::class);
700
+
701
+        $this->registerService(AvatarManager::class, function (Server $c) {
702
+            return new AvatarManager(
703
+                $c->query(\OC\User\Manager::class),
704
+                $c->getAppDataDir('avatar'),
705
+                $c->getL10N('lib'),
706
+                $c->getLogger(),
707
+                $c->getConfig()
708
+            );
709
+        });
710
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
711
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
712
+
713
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
714
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
715
+
716
+        $this->registerService(\OC\Log::class, function (Server $c) {
717
+            $logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
718
+            $factory = new LogFactory($c, $this->getSystemConfig());
719
+            $logger = $factory->get($logType);
720
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
721
+
722
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
723
+        });
724
+        $this->registerAlias(ILogger::class, \OC\Log::class);
725
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
726
+        // PSR-3 logger
727
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
728
+
729
+        $this->registerService(ILogFactory::class, function (Server $c) {
730
+            return new LogFactory($c, $this->getSystemConfig());
731
+        });
732
+
733
+        $this->registerService(IJobList::class, function (Server $c) {
734
+            $config = $c->getConfig();
735
+            return new \OC\BackgroundJob\JobList(
736
+                $c->getDatabaseConnection(),
737
+                $config,
738
+                new TimeFactory()
739
+            );
740
+        });
741
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
742
+
743
+        $this->registerService(IRouter::class, function (Server $c) {
744
+            $cacheFactory = $c->getMemCacheFactory();
745
+            $logger = $c->getLogger();
746
+            if ($cacheFactory->isLocalCacheAvailable()) {
747
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
748
+            } else {
749
+                $router = new \OC\Route\Router($logger);
750
+            }
751
+            return $router;
752
+        });
753
+        $this->registerDeprecatedAlias('Router', IRouter::class);
754
+
755
+        $this->registerService(ISearch::class, function ($c) {
756
+            return new Search();
757
+        });
758
+        $this->registerDeprecatedAlias('Search', ISearch::class);
759
+
760
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
761
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
762
+                $this->getMemCacheFactory(),
763
+                new \OC\AppFramework\Utility\TimeFactory()
764
+            );
765
+        });
766
+
767
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
768
+            return new SecureRandom();
769
+        });
770
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
771
+
772
+        $this->registerService(ICrypto::class, function (Server $c) {
773
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
774
+        });
775
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
776
+
777
+        $this->registerService(IHasher::class, function (Server $c) {
778
+            return new Hasher($c->getConfig());
779
+        });
780
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
781
+
782
+        $this->registerService(ICredentialsManager::class, function (Server $c) {
783
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
784
+        });
785
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
786
+
787
+        $this->registerService(IDBConnection::class, function (Server $c) {
788
+            $systemConfig = $c->getSystemConfig();
789
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
790
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
791
+            if (!$factory->isValidType($type)) {
792
+                throw new \OC\DatabaseException('Invalid database type');
793
+            }
794
+            $connectionParams = $factory->createConnectionParams();
795
+            $connection = $factory->getConnection($type, $connectionParams);
796
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
797
+            return $connection;
798
+        });
799
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
800
+
801
+
802
+        $this->registerService(IClientService::class, function (Server $c) {
803
+            $user = \OC_User::getUser();
804
+            $uid = $user ? $user : null;
805
+            return new ClientService(
806
+                $c->getConfig(),
807
+                $c->getLogger(),
808
+                new \OC\Security\CertificateManager(
809
+                    $uid,
810
+                    new View(),
811
+                    $c->getConfig(),
812
+                    $c->getLogger(),
813
+                    $c->getSecureRandom()
814
+                )
815
+            );
816
+        });
817
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
818
+        $this->registerService(IEventLogger::class, function (Server $c) {
819
+            $eventLogger = new EventLogger();
820
+            if ($c->getSystemConfig()->getValue('debug', false)) {
821
+                // In debug mode, module is being activated by default
822
+                $eventLogger->activate();
823
+            }
824
+            return $eventLogger;
825
+        });
826
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
827
+
828
+        $this->registerService(IQueryLogger::class, function (Server $c) {
829
+            $queryLogger = new QueryLogger();
830
+            if ($c->getSystemConfig()->getValue('debug', false)) {
831
+                // In debug mode, module is being activated by default
832
+                $queryLogger->activate();
833
+            }
834
+            return $queryLogger;
835
+        });
836
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
837
+
838
+        $this->registerService(TempManager::class, function (Server $c) {
839
+            return new TempManager(
840
+                $c->getLogger(),
841
+                $c->getConfig()
842
+            );
843
+        });
844
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
845
+        $this->registerAlias(ITempManager::class, TempManager::class);
846
+
847
+        $this->registerService(AppManager::class, function (Server $c) {
848
+            return new \OC\App\AppManager(
849
+                $c->getUserSession(),
850
+                $c->getConfig(),
851
+                $c->query(\OC\AppConfig::class),
852
+                $c->getGroupManager(),
853
+                $c->getMemCacheFactory(),
854
+                $c->getEventDispatcher(),
855
+                $c->getLogger()
856
+            );
857
+        });
858
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
859
+        $this->registerAlias(IAppManager::class, AppManager::class);
860
+
861
+        $this->registerService(IDateTimeZone::class, function (Server $c) {
862
+            return new DateTimeZone(
863
+                $c->getConfig(),
864
+                $c->getSession()
865
+            );
866
+        });
867
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
868
+
869
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
870
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
871
+
872
+            return new DateTimeFormatter(
873
+                $c->getDateTimeZone()->getTimeZone(),
874
+                $c->getL10N('lib', $language)
875
+            );
876
+        });
877
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
878
+
879
+        $this->registerService(IUserMountCache::class, function (Server $c) {
880
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
881
+            $listener = new UserMountCacheListener($mountCache);
882
+            $listener->listen($c->getUserManager());
883
+            return $mountCache;
884
+        });
885
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
886
+
887
+        $this->registerService(IMountProviderCollection::class, function (Server $c) {
888
+            $loader = \OC\Files\Filesystem::getLoader();
889
+            $mountCache = $c->query(IUserMountCache::class);
890
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
891
+
892
+            // builtin providers
893
+
894
+            $config = $c->getConfig();
895
+            $manager->registerProvider(new CacheMountProvider($config));
896
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
897
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
898
+
899
+            return $manager;
900
+        });
901
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
902
+
903
+        $this->registerService('IniWrapper', function ($c) {
904
+            return new IniGetWrapper();
905
+        });
906
+        $this->registerService('AsyncCommandBus', function (Server $c) {
907
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
908
+            if ($busClass) {
909
+                list($app, $class) = explode('::', $busClass, 2);
910
+                if ($c->getAppManager()->isInstalled($app)) {
911
+                    \OC_App::loadApp($app);
912
+                    return $c->query($class);
913
+                } else {
914
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
915
+                }
916
+            } else {
917
+                $jobList = $c->getJobList();
918
+                return new CronBus($jobList);
919
+            }
920
+        });
921
+        $this->registerService('TrustedDomainHelper', function ($c) {
922
+            return new TrustedDomainHelper($this->getConfig());
923
+        });
924
+        $this->registerService(Throttler::class, function (Server $c) {
925
+            return new Throttler(
926
+                $c->getDatabaseConnection(),
927
+                new TimeFactory(),
928
+                $c->getLogger(),
929
+                $c->getConfig()
930
+            );
931
+        });
932
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
933
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
934
+            // IConfig and IAppManager requires a working database. This code
935
+            // might however be called when ownCloud is not yet setup.
936
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
937
+                $config = $c->getConfig();
938
+                $appManager = $c->getAppManager();
939
+            } else {
940
+                $config = null;
941
+                $appManager = null;
942
+            }
943
+
944
+            return new Checker(
945
+                new EnvironmentHelper(),
946
+                new FileAccessHelper(),
947
+                new AppLocator(),
948
+                $config,
949
+                $c->getMemCacheFactory(),
950
+                $appManager,
951
+                $c->getTempManager(),
952
+                $c->getMimeTypeDetector()
953
+            );
954
+        });
955
+        $this->registerService(\OCP\IRequest::class, function ($c) {
956
+            if (isset($this['urlParams'])) {
957
+                $urlParams = $this['urlParams'];
958
+            } else {
959
+                $urlParams = [];
960
+            }
961
+
962
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
963
+                && in_array('fakeinput', stream_get_wrappers())
964
+            ) {
965
+                $stream = 'fakeinput://data';
966
+            } else {
967
+                $stream = 'php://input';
968
+            }
969
+
970
+            return new Request(
971
+                [
972
+                    'get' => $_GET,
973
+                    'post' => $_POST,
974
+                    'files' => $_FILES,
975
+                    'server' => $_SERVER,
976
+                    'env' => $_ENV,
977
+                    'cookies' => $_COOKIE,
978
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
979
+                        ? $_SERVER['REQUEST_METHOD']
980
+                        : '',
981
+                    'urlParams' => $urlParams,
982
+                ],
983
+                $this->getSecureRandom(),
984
+                $this->getConfig(),
985
+                $this->getCsrfTokenManager(),
986
+                $stream
987
+            );
988
+        });
989
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
990
+
991
+        $this->registerService(IMailer::class, function (Server $c) {
992
+            return new Mailer(
993
+                $c->getConfig(),
994
+                $c->getLogger(),
995
+                $c->query(Defaults::class),
996
+                $c->getURLGenerator(),
997
+                $c->getL10N('lib'),
998
+                $c->query(IEventDispatcher::class)
999
+            );
1000
+        });
1001
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1002
+
1003
+        $this->registerService('LDAPProvider', function (Server $c) {
1004
+            $config = $c->getConfig();
1005
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1006
+            if (is_null($factoryClass)) {
1007
+                throw new \Exception('ldapProviderFactory not set');
1008
+            }
1009
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1010
+            $factory = new $factoryClass($this);
1011
+            return $factory->getLDAPProvider();
1012
+        });
1013
+        $this->registerService(ILockingProvider::class, function (Server $c) {
1014
+            $ini = $c->getIniWrapper();
1015
+            $config = $c->getConfig();
1016
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1017
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1018
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1019
+                $memcacheFactory = $c->getMemCacheFactory();
1020
+                $memcache = $memcacheFactory->createLocking('lock');
1021
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1022
+                    return new MemcacheLockingProvider($memcache, $ttl);
1023
+                }
1024
+                return new DBLockingProvider(
1025
+                    $c->getDatabaseConnection(),
1026
+                    $c->getLogger(),
1027
+                    new TimeFactory(),
1028
+                    $ttl,
1029
+                    !\OC::$CLI
1030
+                );
1031
+            }
1032
+            return new NoopLockingProvider();
1033
+        });
1034
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1035
+
1036
+        $this->registerService(IMountManager::class, function () {
1037
+            return new \OC\Files\Mount\Manager();
1038
+        });
1039
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1040
+
1041
+        $this->registerService(IMimeTypeDetector::class, function (Server $c) {
1042
+            return new \OC\Files\Type\Detection(
1043
+                $c->getURLGenerator(),
1044
+                $c->getLogger(),
1045
+                \OC::$configDir,
1046
+                \OC::$SERVERROOT . '/resources/config/'
1047
+            );
1048
+        });
1049
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1050
+
1051
+        $this->registerService(IMimeTypeLoader::class, function (Server $c) {
1052
+            return new \OC\Files\Type\Loader(
1053
+                $c->getDatabaseConnection()
1054
+            );
1055
+        });
1056
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1057
+        $this->registerService(BundleFetcher::class, function () {
1058
+            return new BundleFetcher($this->getL10N('lib'));
1059
+        });
1060
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1061
+            return new Manager(
1062
+                $c->query(IValidator::class),
1063
+                $c->getLogger()
1064
+            );
1065
+        });
1066
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1067
+
1068
+        $this->registerService(CapabilitiesManager::class, function (Server $c) {
1069
+            $manager = new CapabilitiesManager($c->getLogger());
1070
+            $manager->registerCapability(function () use ($c) {
1071
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
1072
+            });
1073
+            $manager->registerCapability(function () use ($c) {
1074
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1075
+            });
1076
+            return $manager;
1077
+        });
1078
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1079
+
1080
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1081
+            $config = $c->getConfig();
1082
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1083
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1084
+            $factory = new $factoryClass($this);
1085
+            $manager = $factory->getManager();
1086
+
1087
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1088
+                $manager = $c->getUserManager();
1089
+                $user = $manager->get($id);
1090
+                if (is_null($user)) {
1091
+                    $l = $c->getL10N('core');
1092
+                    $displayName = $l->t('Unknown user');
1093
+                } else {
1094
+                    $displayName = $user->getDisplayName();
1095
+                }
1096
+                return $displayName;
1097
+            });
1098
+
1099
+            return $manager;
1100
+        });
1101
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1102
+
1103
+        $this->registerService('ThemingDefaults', function (Server $c) {
1104
+            /*
1105 1105
 			 * Dark magic for autoloader.
1106 1106
 			 * If we do a class_exists it will try to load the class which will
1107 1107
 			 * make composer cache the result. Resulting in errors when enabling
1108 1108
 			 * the theming app.
1109 1109
 			 */
1110
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1111
-			if (isset($prefixes['OCA\\Theming\\'])) {
1112
-				$classExists = true;
1113
-			} else {
1114
-				$classExists = false;
1115
-			}
1116
-
1117
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1118
-				return new ThemingDefaults(
1119
-					$c->getConfig(),
1120
-					$c->getL10N('theming'),
1121
-					$c->getURLGenerator(),
1122
-					$c->getMemCacheFactory(),
1123
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1124
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1125
-					$c->getAppManager(),
1126
-					$c->getNavigationManager()
1127
-				);
1128
-			}
1129
-			return new \OC_Defaults();
1130
-		});
1131
-		$this->registerService(SCSSCacher::class, function (Server $c) {
1132
-			return new SCSSCacher(
1133
-				$c->getLogger(),
1134
-				$c->query(\OC\Files\AppData\Factory::class),
1135
-				$c->getURLGenerator(),
1136
-				$c->getConfig(),
1137
-				$c->getThemingDefaults(),
1138
-				\OC::$SERVERROOT,
1139
-				$this->getMemCacheFactory(),
1140
-				$c->query(IconsCacher::class),
1141
-				new TimeFactory()
1142
-			);
1143
-		});
1144
-		$this->registerService(JSCombiner::class, function (Server $c) {
1145
-			return new JSCombiner(
1146
-				$c->getAppDataDir('js'),
1147
-				$c->getURLGenerator(),
1148
-				$this->getMemCacheFactory(),
1149
-				$c->getSystemConfig(),
1150
-				$c->getLogger()
1151
-			);
1152
-		});
1153
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1154
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1155
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1156
-
1157
-		$this->registerService('CryptoWrapper', function (Server $c) {
1158
-			// FIXME: Instantiiated here due to cyclic dependency
1159
-			$request = new Request(
1160
-				[
1161
-					'get' => $_GET,
1162
-					'post' => $_POST,
1163
-					'files' => $_FILES,
1164
-					'server' => $_SERVER,
1165
-					'env' => $_ENV,
1166
-					'cookies' => $_COOKIE,
1167
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1168
-						? $_SERVER['REQUEST_METHOD']
1169
-						: null,
1170
-				],
1171
-				$c->getSecureRandom(),
1172
-				$c->getConfig()
1173
-			);
1174
-
1175
-			return new CryptoWrapper(
1176
-				$c->getConfig(),
1177
-				$c->getCrypto(),
1178
-				$c->getSecureRandom(),
1179
-				$request
1180
-			);
1181
-		});
1182
-		$this->registerService(CsrfTokenManager::class, function (Server $c) {
1183
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1184
-
1185
-			return new CsrfTokenManager(
1186
-				$tokenGenerator,
1187
-				$c->query(SessionStorage::class)
1188
-			);
1189
-		});
1190
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1191
-		$this->registerService(SessionStorage::class, function (Server $c) {
1192
-			return new SessionStorage($c->getSession());
1193
-		});
1194
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1195
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1196
-
1197
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1198
-			return new ContentSecurityPolicyNonceManager(
1199
-				$c->getCsrfTokenManager(),
1200
-				$c->getRequest()
1201
-			);
1202
-		});
1203
-
1204
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1205
-			$config = $c->getConfig();
1206
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1207
-			/** @var \OCP\Share\IProviderFactory $factory */
1208
-			$factory = new $factoryClass($this);
1209
-
1210
-			$manager = new \OC\Share20\Manager(
1211
-				$c->getLogger(),
1212
-				$c->getConfig(),
1213
-				$c->getSecureRandom(),
1214
-				$c->getHasher(),
1215
-				$c->getMountManager(),
1216
-				$c->getGroupManager(),
1217
-				$c->getL10N('lib'),
1218
-				$c->getL10NFactory(),
1219
-				$factory,
1220
-				$c->getUserManager(),
1221
-				$c->getLazyRootFolder(),
1222
-				$c->getEventDispatcher(),
1223
-				$c->getMailer(),
1224
-				$c->getURLGenerator(),
1225
-				$c->getThemingDefaults(),
1226
-				$c->query(IEventDispatcher::class)
1227
-			);
1228
-
1229
-			return $manager;
1230
-		});
1231
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1232
-
1233
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1234
-			$instance = new Collaboration\Collaborators\Search($c);
1235
-
1236
-			// register default plugins
1237
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1238
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1239
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1240
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1241
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1242
-
1243
-			return $instance;
1244
-		});
1245
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1246
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1247
-
1248
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1249
-
1250
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1251
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1252
-
1253
-		$this->registerService('SettingsManager', function (Server $c) {
1254
-			$manager = new \OC\Settings\Manager(
1255
-				$c->getLogger(),
1256
-				$c->getL10NFactory(),
1257
-				$c->getURLGenerator(),
1258
-				$c
1259
-			);
1260
-			return $manager;
1261
-		});
1262
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1263
-			return new \OC\Files\AppData\Factory(
1264
-				$c->getRootFolder(),
1265
-				$c->getSystemConfig()
1266
-			);
1267
-		});
1268
-
1269
-		$this->registerService('LockdownManager', function (Server $c) {
1270
-			return new LockdownManager(function () use ($c) {
1271
-				return $c->getSession();
1272
-			});
1273
-		});
1274
-
1275
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1276
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1277
-		});
1278
-
1279
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1280
-			return new CloudIdManager();
1281
-		});
1282
-
1283
-		$this->registerService(IConfig::class, function (Server $c) {
1284
-			return new GlobalScale\Config($c->getConfig());
1285
-		});
1286
-
1287
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1288
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1289
-		});
1290
-
1291
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1292
-			return new CloudFederationFactory();
1293
-		});
1294
-
1295
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1296
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1297
-
1298
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1299
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1300
-
1301
-		$this->registerService(Defaults::class, function (Server $c) {
1302
-			return new Defaults(
1303
-				$c->getThemingDefaults()
1304
-			);
1305
-		});
1306
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1307
-
1308
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1309
-			return $c->query(\OCP\IUserSession::class)->getSession();
1310
-		});
1311
-
1312
-		$this->registerService(IShareHelper::class, function (Server $c) {
1313
-			return new ShareHelper(
1314
-				$c->query(\OCP\Share\IManager::class)
1315
-			);
1316
-		});
1317
-
1318
-		$this->registerService(Installer::class, function (Server $c) {
1319
-			return new Installer(
1320
-				$c->getAppFetcher(),
1321
-				$c->getHTTPClientService(),
1322
-				$c->getTempManager(),
1323
-				$c->getLogger(),
1324
-				$c->getConfig(),
1325
-				\OC::$CLI
1326
-			);
1327
-		});
1328
-
1329
-		$this->registerService(IApiFactory::class, function (Server $c) {
1330
-			return new ApiFactory($c->getHTTPClientService());
1331
-		});
1332
-
1333
-		$this->registerService(IInstanceFactory::class, function (Server $c) {
1334
-			$memcacheFactory = $c->getMemCacheFactory();
1335
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1336
-		});
1337
-
1338
-		$this->registerService(IContactsStore::class, function (Server $c) {
1339
-			return new ContactsStore(
1340
-				$c->getContactsManager(),
1341
-				$c->getConfig(),
1342
-				$c->getUserManager(),
1343
-				$c->getGroupManager()
1344
-			);
1345
-		});
1346
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1347
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1348
-
1349
-		$this->registerService(IStorageFactory::class, function () {
1350
-			return new StorageFactory();
1351
-		});
1352
-
1353
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1354
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1355
-
1356
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1357
-
1358
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1359
-
1360
-		$this->connectDispatcher();
1361
-	}
1362
-
1363
-	/**
1364
-	 * @return \OCP\Calendar\IManager
1365
-	 */
1366
-	public function getCalendarManager() {
1367
-		return $this->query(\OC\Calendar\Manager::class);
1368
-	}
1369
-
1370
-	/**
1371
-	 * @return \OCP\Calendar\Resource\IManager
1372
-	 */
1373
-	public function getCalendarResourceBackendManager() {
1374
-		return $this->query(\OC\Calendar\Resource\Manager::class);
1375
-	}
1376
-
1377
-	/**
1378
-	 * @return \OCP\Calendar\Room\IManager
1379
-	 */
1380
-	public function getCalendarRoomBackendManager() {
1381
-		return $this->query(\OC\Calendar\Room\Manager::class);
1382
-	}
1383
-
1384
-	private function connectDispatcher() {
1385
-		$dispatcher = $this->getEventDispatcher();
1386
-
1387
-		// Delete avatar on user deletion
1388
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1389
-			$logger = $this->getLogger();
1390
-			$manager = $this->getAvatarManager();
1391
-			/** @var IUser $user */
1392
-			$user = $e->getSubject();
1393
-
1394
-			try {
1395
-				$avatar = $manager->getAvatar($user->getUID());
1396
-				$avatar->remove();
1397
-			} catch (NotFoundException $e) {
1398
-				// no avatar to remove
1399
-			} catch (\Exception $e) {
1400
-				// Ignore exceptions
1401
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1402
-			}
1403
-		});
1404
-
1405
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1406
-			$manager = $this->getAvatarManager();
1407
-			/** @var IUser $user */
1408
-			$user = $e->getSubject();
1409
-			$feature = $e->getArgument('feature');
1410
-			$oldValue = $e->getArgument('oldValue');
1411
-			$value = $e->getArgument('value');
1412
-
1413
-			// We only change the avatar on display name changes
1414
-			if ($feature !== 'displayName') {
1415
-				return;
1416
-			}
1417
-
1418
-			try {
1419
-				$avatar = $manager->getAvatar($user->getUID());
1420
-				$avatar->userChanged($feature, $oldValue, $value);
1421
-			} catch (NotFoundException $e) {
1422
-				// no avatar to remove
1423
-			}
1424
-		});
1425
-
1426
-		/** @var IEventDispatcher $eventDispatched */
1427
-		$eventDispatched = $this->query(IEventDispatcher::class);
1428
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1429
-	}
1430
-
1431
-	/**
1432
-	 * @return \OCP\Contacts\IManager
1433
-	 */
1434
-	public function getContactsManager() {
1435
-		return $this->query(\OCP\Contacts\IManager::class);
1436
-	}
1437
-
1438
-	/**
1439
-	 * @return \OC\Encryption\Manager
1440
-	 */
1441
-	public function getEncryptionManager() {
1442
-		return $this->query(\OCP\Encryption\IManager::class);
1443
-	}
1444
-
1445
-	/**
1446
-	 * @return \OC\Encryption\File
1447
-	 */
1448
-	public function getEncryptionFilesHelper() {
1449
-		return $this->query('EncryptionFileHelper');
1450
-	}
1451
-
1452
-	/**
1453
-	 * @return \OCP\Encryption\Keys\IStorage
1454
-	 */
1455
-	public function getEncryptionKeyStorage() {
1456
-		return $this->query('EncryptionKeyStorage');
1457
-	}
1458
-
1459
-	/**
1460
-	 * The current request object holding all information about the request
1461
-	 * currently being processed is returned from this method.
1462
-	 * In case the current execution was not initiated by a web request null is returned
1463
-	 *
1464
-	 * @return \OCP\IRequest
1465
-	 */
1466
-	public function getRequest() {
1467
-		return $this->query(IRequest::class);
1468
-	}
1469
-
1470
-	/**
1471
-	 * Returns the preview manager which can create preview images for a given file
1472
-	 *
1473
-	 * @return IPreview
1474
-	 */
1475
-	public function getPreviewManager() {
1476
-		return $this->query(IPreview::class);
1477
-	}
1478
-
1479
-	/**
1480
-	 * Returns the tag manager which can get and set tags for different object types
1481
-	 *
1482
-	 * @see \OCP\ITagManager::load()
1483
-	 * @return ITagManager
1484
-	 */
1485
-	public function getTagManager() {
1486
-		return $this->query(ITagManager::class);
1487
-	}
1488
-
1489
-	/**
1490
-	 * Returns the system-tag manager
1491
-	 *
1492
-	 * @return ISystemTagManager
1493
-	 *
1494
-	 * @since 9.0.0
1495
-	 */
1496
-	public function getSystemTagManager() {
1497
-		return $this->query(ISystemTagManager::class);
1498
-	}
1499
-
1500
-	/**
1501
-	 * Returns the system-tag object mapper
1502
-	 *
1503
-	 * @return ISystemTagObjectMapper
1504
-	 *
1505
-	 * @since 9.0.0
1506
-	 */
1507
-	public function getSystemTagObjectMapper() {
1508
-		return $this->query(ISystemTagObjectMapper::class);
1509
-	}
1510
-
1511
-	/**
1512
-	 * Returns the avatar manager, used for avatar functionality
1513
-	 *
1514
-	 * @return IAvatarManager
1515
-	 */
1516
-	public function getAvatarManager() {
1517
-		return $this->query(IAvatarManager::class);
1518
-	}
1519
-
1520
-	/**
1521
-	 * Returns the root folder of ownCloud's data directory
1522
-	 *
1523
-	 * @return IRootFolder
1524
-	 */
1525
-	public function getRootFolder() {
1526
-		return $this->query(IRootFolder::class);
1527
-	}
1528
-
1529
-	/**
1530
-	 * Returns the root folder of ownCloud's data directory
1531
-	 * This is the lazy variant so this gets only initialized once it
1532
-	 * is actually used.
1533
-	 *
1534
-	 * @return IRootFolder
1535
-	 */
1536
-	public function getLazyRootFolder() {
1537
-		return $this->query(IRootFolder::class);
1538
-	}
1539
-
1540
-	/**
1541
-	 * Returns a view to ownCloud's files folder
1542
-	 *
1543
-	 * @param string $userId user ID
1544
-	 * @return \OCP\Files\Folder|null
1545
-	 */
1546
-	public function getUserFolder($userId = null) {
1547
-		if ($userId === null) {
1548
-			$user = $this->getUserSession()->getUser();
1549
-			if (!$user) {
1550
-				return null;
1551
-			}
1552
-			$userId = $user->getUID();
1553
-		}
1554
-		$root = $this->getRootFolder();
1555
-		return $root->getUserFolder($userId);
1556
-	}
1557
-
1558
-	/**
1559
-	 * Returns an app-specific view in ownClouds data directory
1560
-	 *
1561
-	 * @return \OCP\Files\Folder
1562
-	 * @deprecated since 9.2.0 use IAppData
1563
-	 */
1564
-	public function getAppFolder() {
1565
-		$dir = '/' . \OC_App::getCurrentApp();
1566
-		$root = $this->getRootFolder();
1567
-		if (!$root->nodeExists($dir)) {
1568
-			$folder = $root->newFolder($dir);
1569
-		} else {
1570
-			$folder = $root->get($dir);
1571
-		}
1572
-		return $folder;
1573
-	}
1574
-
1575
-	/**
1576
-	 * @return \OC\User\Manager
1577
-	 */
1578
-	public function getUserManager() {
1579
-		return $this->query(IUserManager::class);
1580
-	}
1581
-
1582
-	/**
1583
-	 * @return \OC\Group\Manager
1584
-	 */
1585
-	public function getGroupManager() {
1586
-		return $this->query(IGroupManager::class);
1587
-	}
1588
-
1589
-	/**
1590
-	 * @return \OC\User\Session
1591
-	 */
1592
-	public function getUserSession() {
1593
-		return $this->query(IUserSession::class);
1594
-	}
1595
-
1596
-	/**
1597
-	 * @return \OCP\ISession
1598
-	 */
1599
-	public function getSession() {
1600
-		return $this->getUserSession()->getSession();
1601
-	}
1602
-
1603
-	/**
1604
-	 * @param \OCP\ISession $session
1605
-	 */
1606
-	public function setSession(\OCP\ISession $session) {
1607
-		$this->query(SessionStorage::class)->setSession($session);
1608
-		$this->getUserSession()->setSession($session);
1609
-		$this->query(Store::class)->setSession($session);
1610
-	}
1611
-
1612
-	/**
1613
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1614
-	 */
1615
-	public function getTwoFactorAuthManager() {
1616
-		return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1617
-	}
1618
-
1619
-	/**
1620
-	 * @return \OC\NavigationManager
1621
-	 */
1622
-	public function getNavigationManager() {
1623
-		return $this->query(INavigationManager::class);
1624
-	}
1625
-
1626
-	/**
1627
-	 * @return \OCP\IConfig
1628
-	 */
1629
-	public function getConfig() {
1630
-		return $this->query(AllConfig::class);
1631
-	}
1632
-
1633
-	/**
1634
-	 * @return \OC\SystemConfig
1635
-	 */
1636
-	public function getSystemConfig() {
1637
-		return $this->query(SystemConfig::class);
1638
-	}
1639
-
1640
-	/**
1641
-	 * Returns the app config manager
1642
-	 *
1643
-	 * @return IAppConfig
1644
-	 */
1645
-	public function getAppConfig() {
1646
-		return $this->query(IAppConfig::class);
1647
-	}
1648
-
1649
-	/**
1650
-	 * @return IFactory
1651
-	 */
1652
-	public function getL10NFactory() {
1653
-		return $this->query(IFactory::class);
1654
-	}
1655
-
1656
-	/**
1657
-	 * get an L10N instance
1658
-	 *
1659
-	 * @param string $app appid
1660
-	 * @param string $lang
1661
-	 * @return IL10N
1662
-	 */
1663
-	public function getL10N($app, $lang = null) {
1664
-		return $this->getL10NFactory()->get($app, $lang);
1665
-	}
1666
-
1667
-	/**
1668
-	 * @return IURLGenerator
1669
-	 */
1670
-	public function getURLGenerator() {
1671
-		return $this->query(IURLGenerator::class);
1672
-	}
1673
-
1674
-	/**
1675
-	 * @return AppFetcher
1676
-	 */
1677
-	public function getAppFetcher() {
1678
-		return $this->query(AppFetcher::class);
1679
-	}
1680
-
1681
-	/**
1682
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1683
-	 * getMemCacheFactory() instead.
1684
-	 *
1685
-	 * @return ICache
1686
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1687
-	 */
1688
-	public function getCache() {
1689
-		return $this->query(ICache::class);
1690
-	}
1691
-
1692
-	/**
1693
-	 * Returns an \OCP\CacheFactory instance
1694
-	 *
1695
-	 * @return \OCP\ICacheFactory
1696
-	 */
1697
-	public function getMemCacheFactory() {
1698
-		return $this->query(Factory::class);
1699
-	}
1700
-
1701
-	/**
1702
-	 * Returns an \OC\RedisFactory instance
1703
-	 *
1704
-	 * @return \OC\RedisFactory
1705
-	 */
1706
-	public function getGetRedisFactory() {
1707
-		return $this->query('RedisFactory');
1708
-	}
1709
-
1710
-
1711
-	/**
1712
-	 * Returns the current session
1713
-	 *
1714
-	 * @return \OCP\IDBConnection
1715
-	 */
1716
-	public function getDatabaseConnection() {
1717
-		return $this->query(IDBConnection::class);
1718
-	}
1719
-
1720
-	/**
1721
-	 * Returns the activity manager
1722
-	 *
1723
-	 * @return \OCP\Activity\IManager
1724
-	 */
1725
-	public function getActivityManager() {
1726
-		return $this->query(\OCP\Activity\IManager::class);
1727
-	}
1728
-
1729
-	/**
1730
-	 * Returns an job list for controlling background jobs
1731
-	 *
1732
-	 * @return IJobList
1733
-	 */
1734
-	public function getJobList() {
1735
-		return $this->query(IJobList::class);
1736
-	}
1737
-
1738
-	/**
1739
-	 * Returns a logger instance
1740
-	 *
1741
-	 * @return ILogger
1742
-	 */
1743
-	public function getLogger() {
1744
-		return $this->query(ILogger::class);
1745
-	}
1746
-
1747
-	/**
1748
-	 * @return ILogFactory
1749
-	 * @throws \OCP\AppFramework\QueryException
1750
-	 */
1751
-	public function getLogFactory() {
1752
-		return $this->query(ILogFactory::class);
1753
-	}
1754
-
1755
-	/**
1756
-	 * Returns a router for generating and matching urls
1757
-	 *
1758
-	 * @return IRouter
1759
-	 */
1760
-	public function getRouter() {
1761
-		return $this->query(IRouter::class);
1762
-	}
1763
-
1764
-	/**
1765
-	 * Returns a search instance
1766
-	 *
1767
-	 * @return ISearch
1768
-	 */
1769
-	public function getSearch() {
1770
-		return $this->query(ISearch::class);
1771
-	}
1772
-
1773
-	/**
1774
-	 * Returns a SecureRandom instance
1775
-	 *
1776
-	 * @return \OCP\Security\ISecureRandom
1777
-	 */
1778
-	public function getSecureRandom() {
1779
-		return $this->query(ISecureRandom::class);
1780
-	}
1781
-
1782
-	/**
1783
-	 * Returns a Crypto instance
1784
-	 *
1785
-	 * @return ICrypto
1786
-	 */
1787
-	public function getCrypto() {
1788
-		return $this->query(ICrypto::class);
1789
-	}
1790
-
1791
-	/**
1792
-	 * Returns a Hasher instance
1793
-	 *
1794
-	 * @return IHasher
1795
-	 */
1796
-	public function getHasher() {
1797
-		return $this->query(IHasher::class);
1798
-	}
1799
-
1800
-	/**
1801
-	 * Returns a CredentialsManager instance
1802
-	 *
1803
-	 * @return ICredentialsManager
1804
-	 */
1805
-	public function getCredentialsManager() {
1806
-		return $this->query(ICredentialsManager::class);
1807
-	}
1808
-
1809
-	/**
1810
-	 * Get the certificate manager for the user
1811
-	 *
1812
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1813
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1814
-	 */
1815
-	public function getCertificateManager($userId = '') {
1816
-		if ($userId === '') {
1817
-			$userSession = $this->getUserSession();
1818
-			$user = $userSession->getUser();
1819
-			if (is_null($user)) {
1820
-				return null;
1821
-			}
1822
-			$userId = $user->getUID();
1823
-		}
1824
-		return new CertificateManager(
1825
-			$userId,
1826
-			new View(),
1827
-			$this->getConfig(),
1828
-			$this->getLogger(),
1829
-			$this->getSecureRandom()
1830
-		);
1831
-	}
1832
-
1833
-	/**
1834
-	 * Returns an instance of the HTTP client service
1835
-	 *
1836
-	 * @return IClientService
1837
-	 */
1838
-	public function getHTTPClientService() {
1839
-		return $this->query(IClientService::class);
1840
-	}
1841
-
1842
-	/**
1843
-	 * Create a new event source
1844
-	 *
1845
-	 * @return \OCP\IEventSource
1846
-	 */
1847
-	public function createEventSource() {
1848
-		return new \OC_EventSource();
1849
-	}
1850
-
1851
-	/**
1852
-	 * Get the active event logger
1853
-	 *
1854
-	 * The returned logger only logs data when debug mode is enabled
1855
-	 *
1856
-	 * @return IEventLogger
1857
-	 */
1858
-	public function getEventLogger() {
1859
-		return $this->query(IEventLogger::class);
1860
-	}
1861
-
1862
-	/**
1863
-	 * Get the active query logger
1864
-	 *
1865
-	 * The returned logger only logs data when debug mode is enabled
1866
-	 *
1867
-	 * @return IQueryLogger
1868
-	 */
1869
-	public function getQueryLogger() {
1870
-		return $this->query(IQueryLogger::class);
1871
-	}
1872
-
1873
-	/**
1874
-	 * Get the manager for temporary files and folders
1875
-	 *
1876
-	 * @return \OCP\ITempManager
1877
-	 */
1878
-	public function getTempManager() {
1879
-		return $this->query(ITempManager::class);
1880
-	}
1881
-
1882
-	/**
1883
-	 * Get the app manager
1884
-	 *
1885
-	 * @return \OCP\App\IAppManager
1886
-	 */
1887
-	public function getAppManager() {
1888
-		return $this->query(IAppManager::class);
1889
-	}
1890
-
1891
-	/**
1892
-	 * Creates a new mailer
1893
-	 *
1894
-	 * @return IMailer
1895
-	 */
1896
-	public function getMailer() {
1897
-		return $this->query(IMailer::class);
1898
-	}
1899
-
1900
-	/**
1901
-	 * Get the webroot
1902
-	 *
1903
-	 * @return string
1904
-	 */
1905
-	public function getWebRoot() {
1906
-		return $this->webRoot;
1907
-	}
1908
-
1909
-	/**
1910
-	 * @return \OC\OCSClient
1911
-	 */
1912
-	public function getOcsClient() {
1913
-		return $this->query('OcsClient');
1914
-	}
1915
-
1916
-	/**
1917
-	 * @return IDateTimeZone
1918
-	 */
1919
-	public function getDateTimeZone() {
1920
-		return $this->query(IDateTimeZone::class);
1921
-	}
1922
-
1923
-	/**
1924
-	 * @return IDateTimeFormatter
1925
-	 */
1926
-	public function getDateTimeFormatter() {
1927
-		return $this->query(IDateTimeFormatter::class);
1928
-	}
1929
-
1930
-	/**
1931
-	 * @return IMountProviderCollection
1932
-	 */
1933
-	public function getMountProviderCollection() {
1934
-		return $this->query(IMountProviderCollection::class);
1935
-	}
1936
-
1937
-	/**
1938
-	 * Get the IniWrapper
1939
-	 *
1940
-	 * @return IniGetWrapper
1941
-	 */
1942
-	public function getIniWrapper() {
1943
-		return $this->query('IniWrapper');
1944
-	}
1945
-
1946
-	/**
1947
-	 * @return \OCP\Command\IBus
1948
-	 */
1949
-	public function getCommandBus() {
1950
-		return $this->query('AsyncCommandBus');
1951
-	}
1952
-
1953
-	/**
1954
-	 * Get the trusted domain helper
1955
-	 *
1956
-	 * @return TrustedDomainHelper
1957
-	 */
1958
-	public function getTrustedDomainHelper() {
1959
-		return $this->query('TrustedDomainHelper');
1960
-	}
1961
-
1962
-	/**
1963
-	 * Get the locking provider
1964
-	 *
1965
-	 * @return ILockingProvider
1966
-	 * @since 8.1.0
1967
-	 */
1968
-	public function getLockingProvider() {
1969
-		return $this->query(ILockingProvider::class);
1970
-	}
1971
-
1972
-	/**
1973
-	 * @return IMountManager
1974
-	 **/
1975
-	public function getMountManager() {
1976
-		return $this->query(IMountManager::class);
1977
-	}
1978
-
1979
-	/**
1980
-	 * @return IUserMountCache
1981
-	 */
1982
-	public function getUserMountCache() {
1983
-		return $this->query(IUserMountCache::class);
1984
-	}
1985
-
1986
-	/**
1987
-	 * Get the MimeTypeDetector
1988
-	 *
1989
-	 * @return IMimeTypeDetector
1990
-	 */
1991
-	public function getMimeTypeDetector() {
1992
-		return $this->query(IMimeTypeDetector::class);
1993
-	}
1994
-
1995
-	/**
1996
-	 * Get the MimeTypeLoader
1997
-	 *
1998
-	 * @return IMimeTypeLoader
1999
-	 */
2000
-	public function getMimeTypeLoader() {
2001
-		return $this->query(IMimeTypeLoader::class);
2002
-	}
2003
-
2004
-	/**
2005
-	 * Get the manager of all the capabilities
2006
-	 *
2007
-	 * @return CapabilitiesManager
2008
-	 */
2009
-	public function getCapabilitiesManager() {
2010
-		return $this->query(CapabilitiesManager::class);
2011
-	}
2012
-
2013
-	/**
2014
-	 * Get the EventDispatcher
2015
-	 *
2016
-	 * @return EventDispatcherInterface
2017
-	 * @since 8.2.0
2018
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2019
-	 */
2020
-	public function getEventDispatcher() {
2021
-		return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2022
-	}
2023
-
2024
-	/**
2025
-	 * Get the Notification Manager
2026
-	 *
2027
-	 * @return \OCP\Notification\IManager
2028
-	 * @since 8.2.0
2029
-	 */
2030
-	public function getNotificationManager() {
2031
-		return $this->query(\OCP\Notification\IManager::class);
2032
-	}
2033
-
2034
-	/**
2035
-	 * @return ICommentsManager
2036
-	 */
2037
-	public function getCommentsManager() {
2038
-		return $this->query(ICommentsManager::class);
2039
-	}
2040
-
2041
-	/**
2042
-	 * @return \OCA\Theming\ThemingDefaults
2043
-	 */
2044
-	public function getThemingDefaults() {
2045
-		return $this->query('ThemingDefaults');
2046
-	}
2047
-
2048
-	/**
2049
-	 * @return \OC\IntegrityCheck\Checker
2050
-	 */
2051
-	public function getIntegrityCodeChecker() {
2052
-		return $this->query('IntegrityCodeChecker');
2053
-	}
2054
-
2055
-	/**
2056
-	 * @return \OC\Session\CryptoWrapper
2057
-	 */
2058
-	public function getSessionCryptoWrapper() {
2059
-		return $this->query('CryptoWrapper');
2060
-	}
2061
-
2062
-	/**
2063
-	 * @return CsrfTokenManager
2064
-	 */
2065
-	public function getCsrfTokenManager() {
2066
-		return $this->query(CsrfTokenManager::class);
2067
-	}
2068
-
2069
-	/**
2070
-	 * @return Throttler
2071
-	 */
2072
-	public function getBruteForceThrottler() {
2073
-		return $this->query(Throttler::class);
2074
-	}
2075
-
2076
-	/**
2077
-	 * @return IContentSecurityPolicyManager
2078
-	 */
2079
-	public function getContentSecurityPolicyManager() {
2080
-		return $this->query(ContentSecurityPolicyManager::class);
2081
-	}
2082
-
2083
-	/**
2084
-	 * @return ContentSecurityPolicyNonceManager
2085
-	 */
2086
-	public function getContentSecurityPolicyNonceManager() {
2087
-		return $this->query('ContentSecurityPolicyNonceManager');
2088
-	}
2089
-
2090
-	/**
2091
-	 * Not a public API as of 8.2, wait for 9.0
2092
-	 *
2093
-	 * @return \OCA\Files_External\Service\BackendService
2094
-	 */
2095
-	public function getStoragesBackendService() {
2096
-		return $this->query(BackendService::class);
2097
-	}
2098
-
2099
-	/**
2100
-	 * Not a public API as of 8.2, wait for 9.0
2101
-	 *
2102
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2103
-	 */
2104
-	public function getGlobalStoragesService() {
2105
-		return $this->query(GlobalStoragesService::class);
2106
-	}
2107
-
2108
-	/**
2109
-	 * Not a public API as of 8.2, wait for 9.0
2110
-	 *
2111
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2112
-	 */
2113
-	public function getUserGlobalStoragesService() {
2114
-		return $this->query(UserGlobalStoragesService::class);
2115
-	}
2116
-
2117
-	/**
2118
-	 * Not a public API as of 8.2, wait for 9.0
2119
-	 *
2120
-	 * @return \OCA\Files_External\Service\UserStoragesService
2121
-	 */
2122
-	public function getUserStoragesService() {
2123
-		return $this->query(UserStoragesService::class);
2124
-	}
2125
-
2126
-	/**
2127
-	 * @return \OCP\Share\IManager
2128
-	 */
2129
-	public function getShareManager() {
2130
-		return $this->query(\OCP\Share\IManager::class);
2131
-	}
2132
-
2133
-	/**
2134
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2135
-	 */
2136
-	public function getCollaboratorSearch() {
2137
-		return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2138
-	}
2139
-
2140
-	/**
2141
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2142
-	 */
2143
-	public function getAutoCompleteManager() {
2144
-		return $this->query(IManager::class);
2145
-	}
2146
-
2147
-	/**
2148
-	 * Returns the LDAP Provider
2149
-	 *
2150
-	 * @return \OCP\LDAP\ILDAPProvider
2151
-	 */
2152
-	public function getLDAPProvider() {
2153
-		return $this->query('LDAPProvider');
2154
-	}
2155
-
2156
-	/**
2157
-	 * @return \OCP\Settings\IManager
2158
-	 */
2159
-	public function getSettingsManager() {
2160
-		return $this->query('SettingsManager');
2161
-	}
2162
-
2163
-	/**
2164
-	 * @return \OCP\Files\IAppData
2165
-	 */
2166
-	public function getAppDataDir($app) {
2167
-		/** @var \OC\Files\AppData\Factory $factory */
2168
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
2169
-		return $factory->get($app);
2170
-	}
2171
-
2172
-	/**
2173
-	 * @return \OCP\Lockdown\ILockdownManager
2174
-	 */
2175
-	public function getLockdownManager() {
2176
-		return $this->query('LockdownManager');
2177
-	}
2178
-
2179
-	/**
2180
-	 * @return \OCP\Federation\ICloudIdManager
2181
-	 */
2182
-	public function getCloudIdManager() {
2183
-		return $this->query(ICloudIdManager::class);
2184
-	}
2185
-
2186
-	/**
2187
-	 * @return \OCP\GlobalScale\IConfig
2188
-	 */
2189
-	public function getGlobalScaleConfig() {
2190
-		return $this->query(IConfig::class);
2191
-	}
2192
-
2193
-	/**
2194
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2195
-	 */
2196
-	public function getCloudFederationProviderManager() {
2197
-		return $this->query(ICloudFederationProviderManager::class);
2198
-	}
2199
-
2200
-	/**
2201
-	 * @return \OCP\Remote\Api\IApiFactory
2202
-	 */
2203
-	public function getRemoteApiFactory() {
2204
-		return $this->query(IApiFactory::class);
2205
-	}
2206
-
2207
-	/**
2208
-	 * @return \OCP\Federation\ICloudFederationFactory
2209
-	 */
2210
-	public function getCloudFederationFactory() {
2211
-		return $this->query(ICloudFederationFactory::class);
2212
-	}
2213
-
2214
-	/**
2215
-	 * @return \OCP\Remote\IInstanceFactory
2216
-	 */
2217
-	public function getRemoteInstanceFactory() {
2218
-		return $this->query(IInstanceFactory::class);
2219
-	}
2220
-
2221
-	/**
2222
-	 * @return IStorageFactory
2223
-	 */
2224
-	public function getStorageFactory() {
2225
-		return $this->query(IStorageFactory::class);
2226
-	}
2227
-
2228
-	/**
2229
-	 * Get the Preview GeneratorHelper
2230
-	 *
2231
-	 * @return GeneratorHelper
2232
-	 * @since 17.0.0
2233
-	 */
2234
-	public function getGeneratorHelper() {
2235
-		return $this->query(\OC\Preview\GeneratorHelper::class);
2236
-	}
2237
-
2238
-	private function registerDeprecatedAlias(string $alias, string $target) {
2239
-		$this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2240
-			try {
2241
-				/** @var ILogger $logger */
2242
-				$logger = $container->query(ILogger::class);
2243
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2244
-			} catch (QueryException $e) {
2245
-				// Could not get logger. Continue
2246
-			}
2247
-
2248
-			return $container->query($target);
2249
-		}, false);
2250
-	}
1110
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1111
+            if (isset($prefixes['OCA\\Theming\\'])) {
1112
+                $classExists = true;
1113
+            } else {
1114
+                $classExists = false;
1115
+            }
1116
+
1117
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1118
+                return new ThemingDefaults(
1119
+                    $c->getConfig(),
1120
+                    $c->getL10N('theming'),
1121
+                    $c->getURLGenerator(),
1122
+                    $c->getMemCacheFactory(),
1123
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1124
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1125
+                    $c->getAppManager(),
1126
+                    $c->getNavigationManager()
1127
+                );
1128
+            }
1129
+            return new \OC_Defaults();
1130
+        });
1131
+        $this->registerService(SCSSCacher::class, function (Server $c) {
1132
+            return new SCSSCacher(
1133
+                $c->getLogger(),
1134
+                $c->query(\OC\Files\AppData\Factory::class),
1135
+                $c->getURLGenerator(),
1136
+                $c->getConfig(),
1137
+                $c->getThemingDefaults(),
1138
+                \OC::$SERVERROOT,
1139
+                $this->getMemCacheFactory(),
1140
+                $c->query(IconsCacher::class),
1141
+                new TimeFactory()
1142
+            );
1143
+        });
1144
+        $this->registerService(JSCombiner::class, function (Server $c) {
1145
+            return new JSCombiner(
1146
+                $c->getAppDataDir('js'),
1147
+                $c->getURLGenerator(),
1148
+                $this->getMemCacheFactory(),
1149
+                $c->getSystemConfig(),
1150
+                $c->getLogger()
1151
+            );
1152
+        });
1153
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1154
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1155
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1156
+
1157
+        $this->registerService('CryptoWrapper', function (Server $c) {
1158
+            // FIXME: Instantiiated here due to cyclic dependency
1159
+            $request = new Request(
1160
+                [
1161
+                    'get' => $_GET,
1162
+                    'post' => $_POST,
1163
+                    'files' => $_FILES,
1164
+                    'server' => $_SERVER,
1165
+                    'env' => $_ENV,
1166
+                    'cookies' => $_COOKIE,
1167
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1168
+                        ? $_SERVER['REQUEST_METHOD']
1169
+                        : null,
1170
+                ],
1171
+                $c->getSecureRandom(),
1172
+                $c->getConfig()
1173
+            );
1174
+
1175
+            return new CryptoWrapper(
1176
+                $c->getConfig(),
1177
+                $c->getCrypto(),
1178
+                $c->getSecureRandom(),
1179
+                $request
1180
+            );
1181
+        });
1182
+        $this->registerService(CsrfTokenManager::class, function (Server $c) {
1183
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1184
+
1185
+            return new CsrfTokenManager(
1186
+                $tokenGenerator,
1187
+                $c->query(SessionStorage::class)
1188
+            );
1189
+        });
1190
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1191
+        $this->registerService(SessionStorage::class, function (Server $c) {
1192
+            return new SessionStorage($c->getSession());
1193
+        });
1194
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1195
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1196
+
1197
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1198
+            return new ContentSecurityPolicyNonceManager(
1199
+                $c->getCsrfTokenManager(),
1200
+                $c->getRequest()
1201
+            );
1202
+        });
1203
+
1204
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1205
+            $config = $c->getConfig();
1206
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1207
+            /** @var \OCP\Share\IProviderFactory $factory */
1208
+            $factory = new $factoryClass($this);
1209
+
1210
+            $manager = new \OC\Share20\Manager(
1211
+                $c->getLogger(),
1212
+                $c->getConfig(),
1213
+                $c->getSecureRandom(),
1214
+                $c->getHasher(),
1215
+                $c->getMountManager(),
1216
+                $c->getGroupManager(),
1217
+                $c->getL10N('lib'),
1218
+                $c->getL10NFactory(),
1219
+                $factory,
1220
+                $c->getUserManager(),
1221
+                $c->getLazyRootFolder(),
1222
+                $c->getEventDispatcher(),
1223
+                $c->getMailer(),
1224
+                $c->getURLGenerator(),
1225
+                $c->getThemingDefaults(),
1226
+                $c->query(IEventDispatcher::class)
1227
+            );
1228
+
1229
+            return $manager;
1230
+        });
1231
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1232
+
1233
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1234
+            $instance = new Collaboration\Collaborators\Search($c);
1235
+
1236
+            // register default plugins
1237
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1238
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1239
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1240
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1241
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1242
+
1243
+            return $instance;
1244
+        });
1245
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1246
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1247
+
1248
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1249
+
1250
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1251
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1252
+
1253
+        $this->registerService('SettingsManager', function (Server $c) {
1254
+            $manager = new \OC\Settings\Manager(
1255
+                $c->getLogger(),
1256
+                $c->getL10NFactory(),
1257
+                $c->getURLGenerator(),
1258
+                $c
1259
+            );
1260
+            return $manager;
1261
+        });
1262
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1263
+            return new \OC\Files\AppData\Factory(
1264
+                $c->getRootFolder(),
1265
+                $c->getSystemConfig()
1266
+            );
1267
+        });
1268
+
1269
+        $this->registerService('LockdownManager', function (Server $c) {
1270
+            return new LockdownManager(function () use ($c) {
1271
+                return $c->getSession();
1272
+            });
1273
+        });
1274
+
1275
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1276
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1277
+        });
1278
+
1279
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1280
+            return new CloudIdManager();
1281
+        });
1282
+
1283
+        $this->registerService(IConfig::class, function (Server $c) {
1284
+            return new GlobalScale\Config($c->getConfig());
1285
+        });
1286
+
1287
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1288
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1289
+        });
1290
+
1291
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1292
+            return new CloudFederationFactory();
1293
+        });
1294
+
1295
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1296
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1297
+
1298
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1299
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1300
+
1301
+        $this->registerService(Defaults::class, function (Server $c) {
1302
+            return new Defaults(
1303
+                $c->getThemingDefaults()
1304
+            );
1305
+        });
1306
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1307
+
1308
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1309
+            return $c->query(\OCP\IUserSession::class)->getSession();
1310
+        });
1311
+
1312
+        $this->registerService(IShareHelper::class, function (Server $c) {
1313
+            return new ShareHelper(
1314
+                $c->query(\OCP\Share\IManager::class)
1315
+            );
1316
+        });
1317
+
1318
+        $this->registerService(Installer::class, function (Server $c) {
1319
+            return new Installer(
1320
+                $c->getAppFetcher(),
1321
+                $c->getHTTPClientService(),
1322
+                $c->getTempManager(),
1323
+                $c->getLogger(),
1324
+                $c->getConfig(),
1325
+                \OC::$CLI
1326
+            );
1327
+        });
1328
+
1329
+        $this->registerService(IApiFactory::class, function (Server $c) {
1330
+            return new ApiFactory($c->getHTTPClientService());
1331
+        });
1332
+
1333
+        $this->registerService(IInstanceFactory::class, function (Server $c) {
1334
+            $memcacheFactory = $c->getMemCacheFactory();
1335
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1336
+        });
1337
+
1338
+        $this->registerService(IContactsStore::class, function (Server $c) {
1339
+            return new ContactsStore(
1340
+                $c->getContactsManager(),
1341
+                $c->getConfig(),
1342
+                $c->getUserManager(),
1343
+                $c->getGroupManager()
1344
+            );
1345
+        });
1346
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1347
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1348
+
1349
+        $this->registerService(IStorageFactory::class, function () {
1350
+            return new StorageFactory();
1351
+        });
1352
+
1353
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1354
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1355
+
1356
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1357
+
1358
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1359
+
1360
+        $this->connectDispatcher();
1361
+    }
1362
+
1363
+    /**
1364
+     * @return \OCP\Calendar\IManager
1365
+     */
1366
+    public function getCalendarManager() {
1367
+        return $this->query(\OC\Calendar\Manager::class);
1368
+    }
1369
+
1370
+    /**
1371
+     * @return \OCP\Calendar\Resource\IManager
1372
+     */
1373
+    public function getCalendarResourceBackendManager() {
1374
+        return $this->query(\OC\Calendar\Resource\Manager::class);
1375
+    }
1376
+
1377
+    /**
1378
+     * @return \OCP\Calendar\Room\IManager
1379
+     */
1380
+    public function getCalendarRoomBackendManager() {
1381
+        return $this->query(\OC\Calendar\Room\Manager::class);
1382
+    }
1383
+
1384
+    private function connectDispatcher() {
1385
+        $dispatcher = $this->getEventDispatcher();
1386
+
1387
+        // Delete avatar on user deletion
1388
+        $dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1389
+            $logger = $this->getLogger();
1390
+            $manager = $this->getAvatarManager();
1391
+            /** @var IUser $user */
1392
+            $user = $e->getSubject();
1393
+
1394
+            try {
1395
+                $avatar = $manager->getAvatar($user->getUID());
1396
+                $avatar->remove();
1397
+            } catch (NotFoundException $e) {
1398
+                // no avatar to remove
1399
+            } catch (\Exception $e) {
1400
+                // Ignore exceptions
1401
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1402
+            }
1403
+        });
1404
+
1405
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1406
+            $manager = $this->getAvatarManager();
1407
+            /** @var IUser $user */
1408
+            $user = $e->getSubject();
1409
+            $feature = $e->getArgument('feature');
1410
+            $oldValue = $e->getArgument('oldValue');
1411
+            $value = $e->getArgument('value');
1412
+
1413
+            // We only change the avatar on display name changes
1414
+            if ($feature !== 'displayName') {
1415
+                return;
1416
+            }
1417
+
1418
+            try {
1419
+                $avatar = $manager->getAvatar($user->getUID());
1420
+                $avatar->userChanged($feature, $oldValue, $value);
1421
+            } catch (NotFoundException $e) {
1422
+                // no avatar to remove
1423
+            }
1424
+        });
1425
+
1426
+        /** @var IEventDispatcher $eventDispatched */
1427
+        $eventDispatched = $this->query(IEventDispatcher::class);
1428
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1429
+    }
1430
+
1431
+    /**
1432
+     * @return \OCP\Contacts\IManager
1433
+     */
1434
+    public function getContactsManager() {
1435
+        return $this->query(\OCP\Contacts\IManager::class);
1436
+    }
1437
+
1438
+    /**
1439
+     * @return \OC\Encryption\Manager
1440
+     */
1441
+    public function getEncryptionManager() {
1442
+        return $this->query(\OCP\Encryption\IManager::class);
1443
+    }
1444
+
1445
+    /**
1446
+     * @return \OC\Encryption\File
1447
+     */
1448
+    public function getEncryptionFilesHelper() {
1449
+        return $this->query('EncryptionFileHelper');
1450
+    }
1451
+
1452
+    /**
1453
+     * @return \OCP\Encryption\Keys\IStorage
1454
+     */
1455
+    public function getEncryptionKeyStorage() {
1456
+        return $this->query('EncryptionKeyStorage');
1457
+    }
1458
+
1459
+    /**
1460
+     * The current request object holding all information about the request
1461
+     * currently being processed is returned from this method.
1462
+     * In case the current execution was not initiated by a web request null is returned
1463
+     *
1464
+     * @return \OCP\IRequest
1465
+     */
1466
+    public function getRequest() {
1467
+        return $this->query(IRequest::class);
1468
+    }
1469
+
1470
+    /**
1471
+     * Returns the preview manager which can create preview images for a given file
1472
+     *
1473
+     * @return IPreview
1474
+     */
1475
+    public function getPreviewManager() {
1476
+        return $this->query(IPreview::class);
1477
+    }
1478
+
1479
+    /**
1480
+     * Returns the tag manager which can get and set tags for different object types
1481
+     *
1482
+     * @see \OCP\ITagManager::load()
1483
+     * @return ITagManager
1484
+     */
1485
+    public function getTagManager() {
1486
+        return $this->query(ITagManager::class);
1487
+    }
1488
+
1489
+    /**
1490
+     * Returns the system-tag manager
1491
+     *
1492
+     * @return ISystemTagManager
1493
+     *
1494
+     * @since 9.0.0
1495
+     */
1496
+    public function getSystemTagManager() {
1497
+        return $this->query(ISystemTagManager::class);
1498
+    }
1499
+
1500
+    /**
1501
+     * Returns the system-tag object mapper
1502
+     *
1503
+     * @return ISystemTagObjectMapper
1504
+     *
1505
+     * @since 9.0.0
1506
+     */
1507
+    public function getSystemTagObjectMapper() {
1508
+        return $this->query(ISystemTagObjectMapper::class);
1509
+    }
1510
+
1511
+    /**
1512
+     * Returns the avatar manager, used for avatar functionality
1513
+     *
1514
+     * @return IAvatarManager
1515
+     */
1516
+    public function getAvatarManager() {
1517
+        return $this->query(IAvatarManager::class);
1518
+    }
1519
+
1520
+    /**
1521
+     * Returns the root folder of ownCloud's data directory
1522
+     *
1523
+     * @return IRootFolder
1524
+     */
1525
+    public function getRootFolder() {
1526
+        return $this->query(IRootFolder::class);
1527
+    }
1528
+
1529
+    /**
1530
+     * Returns the root folder of ownCloud's data directory
1531
+     * This is the lazy variant so this gets only initialized once it
1532
+     * is actually used.
1533
+     *
1534
+     * @return IRootFolder
1535
+     */
1536
+    public function getLazyRootFolder() {
1537
+        return $this->query(IRootFolder::class);
1538
+    }
1539
+
1540
+    /**
1541
+     * Returns a view to ownCloud's files folder
1542
+     *
1543
+     * @param string $userId user ID
1544
+     * @return \OCP\Files\Folder|null
1545
+     */
1546
+    public function getUserFolder($userId = null) {
1547
+        if ($userId === null) {
1548
+            $user = $this->getUserSession()->getUser();
1549
+            if (!$user) {
1550
+                return null;
1551
+            }
1552
+            $userId = $user->getUID();
1553
+        }
1554
+        $root = $this->getRootFolder();
1555
+        return $root->getUserFolder($userId);
1556
+    }
1557
+
1558
+    /**
1559
+     * Returns an app-specific view in ownClouds data directory
1560
+     *
1561
+     * @return \OCP\Files\Folder
1562
+     * @deprecated since 9.2.0 use IAppData
1563
+     */
1564
+    public function getAppFolder() {
1565
+        $dir = '/' . \OC_App::getCurrentApp();
1566
+        $root = $this->getRootFolder();
1567
+        if (!$root->nodeExists($dir)) {
1568
+            $folder = $root->newFolder($dir);
1569
+        } else {
1570
+            $folder = $root->get($dir);
1571
+        }
1572
+        return $folder;
1573
+    }
1574
+
1575
+    /**
1576
+     * @return \OC\User\Manager
1577
+     */
1578
+    public function getUserManager() {
1579
+        return $this->query(IUserManager::class);
1580
+    }
1581
+
1582
+    /**
1583
+     * @return \OC\Group\Manager
1584
+     */
1585
+    public function getGroupManager() {
1586
+        return $this->query(IGroupManager::class);
1587
+    }
1588
+
1589
+    /**
1590
+     * @return \OC\User\Session
1591
+     */
1592
+    public function getUserSession() {
1593
+        return $this->query(IUserSession::class);
1594
+    }
1595
+
1596
+    /**
1597
+     * @return \OCP\ISession
1598
+     */
1599
+    public function getSession() {
1600
+        return $this->getUserSession()->getSession();
1601
+    }
1602
+
1603
+    /**
1604
+     * @param \OCP\ISession $session
1605
+     */
1606
+    public function setSession(\OCP\ISession $session) {
1607
+        $this->query(SessionStorage::class)->setSession($session);
1608
+        $this->getUserSession()->setSession($session);
1609
+        $this->query(Store::class)->setSession($session);
1610
+    }
1611
+
1612
+    /**
1613
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1614
+     */
1615
+    public function getTwoFactorAuthManager() {
1616
+        return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1617
+    }
1618
+
1619
+    /**
1620
+     * @return \OC\NavigationManager
1621
+     */
1622
+    public function getNavigationManager() {
1623
+        return $this->query(INavigationManager::class);
1624
+    }
1625
+
1626
+    /**
1627
+     * @return \OCP\IConfig
1628
+     */
1629
+    public function getConfig() {
1630
+        return $this->query(AllConfig::class);
1631
+    }
1632
+
1633
+    /**
1634
+     * @return \OC\SystemConfig
1635
+     */
1636
+    public function getSystemConfig() {
1637
+        return $this->query(SystemConfig::class);
1638
+    }
1639
+
1640
+    /**
1641
+     * Returns the app config manager
1642
+     *
1643
+     * @return IAppConfig
1644
+     */
1645
+    public function getAppConfig() {
1646
+        return $this->query(IAppConfig::class);
1647
+    }
1648
+
1649
+    /**
1650
+     * @return IFactory
1651
+     */
1652
+    public function getL10NFactory() {
1653
+        return $this->query(IFactory::class);
1654
+    }
1655
+
1656
+    /**
1657
+     * get an L10N instance
1658
+     *
1659
+     * @param string $app appid
1660
+     * @param string $lang
1661
+     * @return IL10N
1662
+     */
1663
+    public function getL10N($app, $lang = null) {
1664
+        return $this->getL10NFactory()->get($app, $lang);
1665
+    }
1666
+
1667
+    /**
1668
+     * @return IURLGenerator
1669
+     */
1670
+    public function getURLGenerator() {
1671
+        return $this->query(IURLGenerator::class);
1672
+    }
1673
+
1674
+    /**
1675
+     * @return AppFetcher
1676
+     */
1677
+    public function getAppFetcher() {
1678
+        return $this->query(AppFetcher::class);
1679
+    }
1680
+
1681
+    /**
1682
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1683
+     * getMemCacheFactory() instead.
1684
+     *
1685
+     * @return ICache
1686
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1687
+     */
1688
+    public function getCache() {
1689
+        return $this->query(ICache::class);
1690
+    }
1691
+
1692
+    /**
1693
+     * Returns an \OCP\CacheFactory instance
1694
+     *
1695
+     * @return \OCP\ICacheFactory
1696
+     */
1697
+    public function getMemCacheFactory() {
1698
+        return $this->query(Factory::class);
1699
+    }
1700
+
1701
+    /**
1702
+     * Returns an \OC\RedisFactory instance
1703
+     *
1704
+     * @return \OC\RedisFactory
1705
+     */
1706
+    public function getGetRedisFactory() {
1707
+        return $this->query('RedisFactory');
1708
+    }
1709
+
1710
+
1711
+    /**
1712
+     * Returns the current session
1713
+     *
1714
+     * @return \OCP\IDBConnection
1715
+     */
1716
+    public function getDatabaseConnection() {
1717
+        return $this->query(IDBConnection::class);
1718
+    }
1719
+
1720
+    /**
1721
+     * Returns the activity manager
1722
+     *
1723
+     * @return \OCP\Activity\IManager
1724
+     */
1725
+    public function getActivityManager() {
1726
+        return $this->query(\OCP\Activity\IManager::class);
1727
+    }
1728
+
1729
+    /**
1730
+     * Returns an job list for controlling background jobs
1731
+     *
1732
+     * @return IJobList
1733
+     */
1734
+    public function getJobList() {
1735
+        return $this->query(IJobList::class);
1736
+    }
1737
+
1738
+    /**
1739
+     * Returns a logger instance
1740
+     *
1741
+     * @return ILogger
1742
+     */
1743
+    public function getLogger() {
1744
+        return $this->query(ILogger::class);
1745
+    }
1746
+
1747
+    /**
1748
+     * @return ILogFactory
1749
+     * @throws \OCP\AppFramework\QueryException
1750
+     */
1751
+    public function getLogFactory() {
1752
+        return $this->query(ILogFactory::class);
1753
+    }
1754
+
1755
+    /**
1756
+     * Returns a router for generating and matching urls
1757
+     *
1758
+     * @return IRouter
1759
+     */
1760
+    public function getRouter() {
1761
+        return $this->query(IRouter::class);
1762
+    }
1763
+
1764
+    /**
1765
+     * Returns a search instance
1766
+     *
1767
+     * @return ISearch
1768
+     */
1769
+    public function getSearch() {
1770
+        return $this->query(ISearch::class);
1771
+    }
1772
+
1773
+    /**
1774
+     * Returns a SecureRandom instance
1775
+     *
1776
+     * @return \OCP\Security\ISecureRandom
1777
+     */
1778
+    public function getSecureRandom() {
1779
+        return $this->query(ISecureRandom::class);
1780
+    }
1781
+
1782
+    /**
1783
+     * Returns a Crypto instance
1784
+     *
1785
+     * @return ICrypto
1786
+     */
1787
+    public function getCrypto() {
1788
+        return $this->query(ICrypto::class);
1789
+    }
1790
+
1791
+    /**
1792
+     * Returns a Hasher instance
1793
+     *
1794
+     * @return IHasher
1795
+     */
1796
+    public function getHasher() {
1797
+        return $this->query(IHasher::class);
1798
+    }
1799
+
1800
+    /**
1801
+     * Returns a CredentialsManager instance
1802
+     *
1803
+     * @return ICredentialsManager
1804
+     */
1805
+    public function getCredentialsManager() {
1806
+        return $this->query(ICredentialsManager::class);
1807
+    }
1808
+
1809
+    /**
1810
+     * Get the certificate manager for the user
1811
+     *
1812
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1813
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1814
+     */
1815
+    public function getCertificateManager($userId = '') {
1816
+        if ($userId === '') {
1817
+            $userSession = $this->getUserSession();
1818
+            $user = $userSession->getUser();
1819
+            if (is_null($user)) {
1820
+                return null;
1821
+            }
1822
+            $userId = $user->getUID();
1823
+        }
1824
+        return new CertificateManager(
1825
+            $userId,
1826
+            new View(),
1827
+            $this->getConfig(),
1828
+            $this->getLogger(),
1829
+            $this->getSecureRandom()
1830
+        );
1831
+    }
1832
+
1833
+    /**
1834
+     * Returns an instance of the HTTP client service
1835
+     *
1836
+     * @return IClientService
1837
+     */
1838
+    public function getHTTPClientService() {
1839
+        return $this->query(IClientService::class);
1840
+    }
1841
+
1842
+    /**
1843
+     * Create a new event source
1844
+     *
1845
+     * @return \OCP\IEventSource
1846
+     */
1847
+    public function createEventSource() {
1848
+        return new \OC_EventSource();
1849
+    }
1850
+
1851
+    /**
1852
+     * Get the active event logger
1853
+     *
1854
+     * The returned logger only logs data when debug mode is enabled
1855
+     *
1856
+     * @return IEventLogger
1857
+     */
1858
+    public function getEventLogger() {
1859
+        return $this->query(IEventLogger::class);
1860
+    }
1861
+
1862
+    /**
1863
+     * Get the active query logger
1864
+     *
1865
+     * The returned logger only logs data when debug mode is enabled
1866
+     *
1867
+     * @return IQueryLogger
1868
+     */
1869
+    public function getQueryLogger() {
1870
+        return $this->query(IQueryLogger::class);
1871
+    }
1872
+
1873
+    /**
1874
+     * Get the manager for temporary files and folders
1875
+     *
1876
+     * @return \OCP\ITempManager
1877
+     */
1878
+    public function getTempManager() {
1879
+        return $this->query(ITempManager::class);
1880
+    }
1881
+
1882
+    /**
1883
+     * Get the app manager
1884
+     *
1885
+     * @return \OCP\App\IAppManager
1886
+     */
1887
+    public function getAppManager() {
1888
+        return $this->query(IAppManager::class);
1889
+    }
1890
+
1891
+    /**
1892
+     * Creates a new mailer
1893
+     *
1894
+     * @return IMailer
1895
+     */
1896
+    public function getMailer() {
1897
+        return $this->query(IMailer::class);
1898
+    }
1899
+
1900
+    /**
1901
+     * Get the webroot
1902
+     *
1903
+     * @return string
1904
+     */
1905
+    public function getWebRoot() {
1906
+        return $this->webRoot;
1907
+    }
1908
+
1909
+    /**
1910
+     * @return \OC\OCSClient
1911
+     */
1912
+    public function getOcsClient() {
1913
+        return $this->query('OcsClient');
1914
+    }
1915
+
1916
+    /**
1917
+     * @return IDateTimeZone
1918
+     */
1919
+    public function getDateTimeZone() {
1920
+        return $this->query(IDateTimeZone::class);
1921
+    }
1922
+
1923
+    /**
1924
+     * @return IDateTimeFormatter
1925
+     */
1926
+    public function getDateTimeFormatter() {
1927
+        return $this->query(IDateTimeFormatter::class);
1928
+    }
1929
+
1930
+    /**
1931
+     * @return IMountProviderCollection
1932
+     */
1933
+    public function getMountProviderCollection() {
1934
+        return $this->query(IMountProviderCollection::class);
1935
+    }
1936
+
1937
+    /**
1938
+     * Get the IniWrapper
1939
+     *
1940
+     * @return IniGetWrapper
1941
+     */
1942
+    public function getIniWrapper() {
1943
+        return $this->query('IniWrapper');
1944
+    }
1945
+
1946
+    /**
1947
+     * @return \OCP\Command\IBus
1948
+     */
1949
+    public function getCommandBus() {
1950
+        return $this->query('AsyncCommandBus');
1951
+    }
1952
+
1953
+    /**
1954
+     * Get the trusted domain helper
1955
+     *
1956
+     * @return TrustedDomainHelper
1957
+     */
1958
+    public function getTrustedDomainHelper() {
1959
+        return $this->query('TrustedDomainHelper');
1960
+    }
1961
+
1962
+    /**
1963
+     * Get the locking provider
1964
+     *
1965
+     * @return ILockingProvider
1966
+     * @since 8.1.0
1967
+     */
1968
+    public function getLockingProvider() {
1969
+        return $this->query(ILockingProvider::class);
1970
+    }
1971
+
1972
+    /**
1973
+     * @return IMountManager
1974
+     **/
1975
+    public function getMountManager() {
1976
+        return $this->query(IMountManager::class);
1977
+    }
1978
+
1979
+    /**
1980
+     * @return IUserMountCache
1981
+     */
1982
+    public function getUserMountCache() {
1983
+        return $this->query(IUserMountCache::class);
1984
+    }
1985
+
1986
+    /**
1987
+     * Get the MimeTypeDetector
1988
+     *
1989
+     * @return IMimeTypeDetector
1990
+     */
1991
+    public function getMimeTypeDetector() {
1992
+        return $this->query(IMimeTypeDetector::class);
1993
+    }
1994
+
1995
+    /**
1996
+     * Get the MimeTypeLoader
1997
+     *
1998
+     * @return IMimeTypeLoader
1999
+     */
2000
+    public function getMimeTypeLoader() {
2001
+        return $this->query(IMimeTypeLoader::class);
2002
+    }
2003
+
2004
+    /**
2005
+     * Get the manager of all the capabilities
2006
+     *
2007
+     * @return CapabilitiesManager
2008
+     */
2009
+    public function getCapabilitiesManager() {
2010
+        return $this->query(CapabilitiesManager::class);
2011
+    }
2012
+
2013
+    /**
2014
+     * Get the EventDispatcher
2015
+     *
2016
+     * @return EventDispatcherInterface
2017
+     * @since 8.2.0
2018
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2019
+     */
2020
+    public function getEventDispatcher() {
2021
+        return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2022
+    }
2023
+
2024
+    /**
2025
+     * Get the Notification Manager
2026
+     *
2027
+     * @return \OCP\Notification\IManager
2028
+     * @since 8.2.0
2029
+     */
2030
+    public function getNotificationManager() {
2031
+        return $this->query(\OCP\Notification\IManager::class);
2032
+    }
2033
+
2034
+    /**
2035
+     * @return ICommentsManager
2036
+     */
2037
+    public function getCommentsManager() {
2038
+        return $this->query(ICommentsManager::class);
2039
+    }
2040
+
2041
+    /**
2042
+     * @return \OCA\Theming\ThemingDefaults
2043
+     */
2044
+    public function getThemingDefaults() {
2045
+        return $this->query('ThemingDefaults');
2046
+    }
2047
+
2048
+    /**
2049
+     * @return \OC\IntegrityCheck\Checker
2050
+     */
2051
+    public function getIntegrityCodeChecker() {
2052
+        return $this->query('IntegrityCodeChecker');
2053
+    }
2054
+
2055
+    /**
2056
+     * @return \OC\Session\CryptoWrapper
2057
+     */
2058
+    public function getSessionCryptoWrapper() {
2059
+        return $this->query('CryptoWrapper');
2060
+    }
2061
+
2062
+    /**
2063
+     * @return CsrfTokenManager
2064
+     */
2065
+    public function getCsrfTokenManager() {
2066
+        return $this->query(CsrfTokenManager::class);
2067
+    }
2068
+
2069
+    /**
2070
+     * @return Throttler
2071
+     */
2072
+    public function getBruteForceThrottler() {
2073
+        return $this->query(Throttler::class);
2074
+    }
2075
+
2076
+    /**
2077
+     * @return IContentSecurityPolicyManager
2078
+     */
2079
+    public function getContentSecurityPolicyManager() {
2080
+        return $this->query(ContentSecurityPolicyManager::class);
2081
+    }
2082
+
2083
+    /**
2084
+     * @return ContentSecurityPolicyNonceManager
2085
+     */
2086
+    public function getContentSecurityPolicyNonceManager() {
2087
+        return $this->query('ContentSecurityPolicyNonceManager');
2088
+    }
2089
+
2090
+    /**
2091
+     * Not a public API as of 8.2, wait for 9.0
2092
+     *
2093
+     * @return \OCA\Files_External\Service\BackendService
2094
+     */
2095
+    public function getStoragesBackendService() {
2096
+        return $this->query(BackendService::class);
2097
+    }
2098
+
2099
+    /**
2100
+     * Not a public API as of 8.2, wait for 9.0
2101
+     *
2102
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2103
+     */
2104
+    public function getGlobalStoragesService() {
2105
+        return $this->query(GlobalStoragesService::class);
2106
+    }
2107
+
2108
+    /**
2109
+     * Not a public API as of 8.2, wait for 9.0
2110
+     *
2111
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2112
+     */
2113
+    public function getUserGlobalStoragesService() {
2114
+        return $this->query(UserGlobalStoragesService::class);
2115
+    }
2116
+
2117
+    /**
2118
+     * Not a public API as of 8.2, wait for 9.0
2119
+     *
2120
+     * @return \OCA\Files_External\Service\UserStoragesService
2121
+     */
2122
+    public function getUserStoragesService() {
2123
+        return $this->query(UserStoragesService::class);
2124
+    }
2125
+
2126
+    /**
2127
+     * @return \OCP\Share\IManager
2128
+     */
2129
+    public function getShareManager() {
2130
+        return $this->query(\OCP\Share\IManager::class);
2131
+    }
2132
+
2133
+    /**
2134
+     * @return \OCP\Collaboration\Collaborators\ISearch
2135
+     */
2136
+    public function getCollaboratorSearch() {
2137
+        return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2138
+    }
2139
+
2140
+    /**
2141
+     * @return \OCP\Collaboration\AutoComplete\IManager
2142
+     */
2143
+    public function getAutoCompleteManager() {
2144
+        return $this->query(IManager::class);
2145
+    }
2146
+
2147
+    /**
2148
+     * Returns the LDAP Provider
2149
+     *
2150
+     * @return \OCP\LDAP\ILDAPProvider
2151
+     */
2152
+    public function getLDAPProvider() {
2153
+        return $this->query('LDAPProvider');
2154
+    }
2155
+
2156
+    /**
2157
+     * @return \OCP\Settings\IManager
2158
+     */
2159
+    public function getSettingsManager() {
2160
+        return $this->query('SettingsManager');
2161
+    }
2162
+
2163
+    /**
2164
+     * @return \OCP\Files\IAppData
2165
+     */
2166
+    public function getAppDataDir($app) {
2167
+        /** @var \OC\Files\AppData\Factory $factory */
2168
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
2169
+        return $factory->get($app);
2170
+    }
2171
+
2172
+    /**
2173
+     * @return \OCP\Lockdown\ILockdownManager
2174
+     */
2175
+    public function getLockdownManager() {
2176
+        return $this->query('LockdownManager');
2177
+    }
2178
+
2179
+    /**
2180
+     * @return \OCP\Federation\ICloudIdManager
2181
+     */
2182
+    public function getCloudIdManager() {
2183
+        return $this->query(ICloudIdManager::class);
2184
+    }
2185
+
2186
+    /**
2187
+     * @return \OCP\GlobalScale\IConfig
2188
+     */
2189
+    public function getGlobalScaleConfig() {
2190
+        return $this->query(IConfig::class);
2191
+    }
2192
+
2193
+    /**
2194
+     * @return \OCP\Federation\ICloudFederationProviderManager
2195
+     */
2196
+    public function getCloudFederationProviderManager() {
2197
+        return $this->query(ICloudFederationProviderManager::class);
2198
+    }
2199
+
2200
+    /**
2201
+     * @return \OCP\Remote\Api\IApiFactory
2202
+     */
2203
+    public function getRemoteApiFactory() {
2204
+        return $this->query(IApiFactory::class);
2205
+    }
2206
+
2207
+    /**
2208
+     * @return \OCP\Federation\ICloudFederationFactory
2209
+     */
2210
+    public function getCloudFederationFactory() {
2211
+        return $this->query(ICloudFederationFactory::class);
2212
+    }
2213
+
2214
+    /**
2215
+     * @return \OCP\Remote\IInstanceFactory
2216
+     */
2217
+    public function getRemoteInstanceFactory() {
2218
+        return $this->query(IInstanceFactory::class);
2219
+    }
2220
+
2221
+    /**
2222
+     * @return IStorageFactory
2223
+     */
2224
+    public function getStorageFactory() {
2225
+        return $this->query(IStorageFactory::class);
2226
+    }
2227
+
2228
+    /**
2229
+     * Get the Preview GeneratorHelper
2230
+     *
2231
+     * @return GeneratorHelper
2232
+     * @since 17.0.0
2233
+     */
2234
+    public function getGeneratorHelper() {
2235
+        return $this->query(\OC\Preview\GeneratorHelper::class);
2236
+    }
2237
+
2238
+    private function registerDeprecatedAlias(string $alias, string $target) {
2239
+        $this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2240
+            try {
2241
+                /** @var ILogger $logger */
2242
+                $logger = $container->query(ILogger::class);
2243
+                $logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2244
+            } catch (QueryException $e) {
2245
+                // Could not get logger. Continue
2246
+            }
2247
+
2248
+            return $container->query($target);
2249
+        }, false);
2250
+    }
2251 2251
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php 2 patches
Indentation   +345 added lines, -345 removed lines patch added patch discarded remove patch
@@ -51,349 +51,349 @@
 block discarded – undo
51 51
 
52 52
 class RefreshWebcalService {
53 53
 
54
-	/** @var CalDavBackend */
55
-	private $calDavBackend;
56
-
57
-	/** @var IClientService */
58
-	private $clientService;
59
-
60
-	/** @var IConfig */
61
-	private $config;
62
-
63
-	/** @var ILogger */
64
-	private $logger;
65
-
66
-	public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
67
-	public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
68
-	public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
69
-	public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
70
-
71
-	/**
72
-	 * RefreshWebcalJob constructor.
73
-	 *
74
-	 * @param CalDavBackend $calDavBackend
75
-	 * @param IClientService $clientService
76
-	 * @param IConfig $config
77
-	 * @param ILogger $logger
78
-	 */
79
-	public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) {
80
-		$this->calDavBackend = $calDavBackend;
81
-		$this->clientService = $clientService;
82
-		$this->config = $config;
83
-		$this->logger = $logger;
84
-	}
85
-
86
-	/**
87
-	 * @param string $principalUri
88
-	 * @param string $uri
89
-	 */
90
-	public function refreshSubscription(string $principalUri, string $uri) {
91
-		$subscription = $this->getSubscription($principalUri, $uri);
92
-		$mutations = [];
93
-		if (!$subscription) {
94
-			return;
95
-		}
96
-
97
-		$webcalData = $this->queryWebcalFeed($subscription, $mutations);
98
-		if (!$webcalData) {
99
-			return;
100
-		}
101
-
102
-		$stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
103
-		$stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
104
-		$stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
105
-
106
-		try {
107
-			$splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
108
-
109
-			// we wait with deleting all outdated events till we parsed the new ones
110
-			// in case the new calendar is broken and `new ICalendar` throws a ParseException
111
-			// the user will still see the old data
112
-			$this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
113
-
114
-			while ($vObject = $splitter->getNext()) {
115
-				/** @var Component $vObject */
116
-				$compName = null;
117
-
118
-				foreach ($vObject->getComponents() as $component) {
119
-					if ($component->name === 'VTIMEZONE') {
120
-						continue;
121
-					}
122
-
123
-					$compName = $component->name;
124
-
125
-					if ($stripAlarms) {
126
-						unset($component->{'VALARM'});
127
-					}
128
-					if ($stripAttachments) {
129
-						unset($component->{'ATTACH'});
130
-					}
131
-				}
132
-
133
-				if ($stripTodos && $compName === 'VTODO') {
134
-					continue;
135
-				}
136
-
137
-				$uri = $this->getRandomCalendarObjectUri();
138
-				$calendarData = $vObject->serialize();
139
-				try {
140
-					$this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
141
-				} catch (BadRequest $ex) {
142
-					$this->logger->logException($ex);
143
-				}
144
-			}
145
-
146
-			$newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
147
-			if ($newRefreshRate) {
148
-				$mutations[self::REFRESH_RATE] = $newRefreshRate;
149
-			}
150
-
151
-			$this->updateSubscription($subscription, $mutations);
152
-		} catch (ParseException $ex) {
153
-			$subscriptionId = $subscription['id'];
154
-
155
-			$this->logger->logException($ex);
156
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
157
-		}
158
-	}
159
-
160
-	/**
161
-	 * loads subscription from backend
162
-	 *
163
-	 * @param string $principalUri
164
-	 * @param string $uri
165
-	 * @return array|null
166
-	 */
167
-	public function getSubscription(string $principalUri, string $uri) {
168
-		$subscriptions = array_values(array_filter(
169
-			$this->calDavBackend->getSubscriptionsForUser($principalUri),
170
-			function ($sub) use ($uri) {
171
-				return $sub['uri'] === $uri;
172
-			}
173
-		));
174
-
175
-		if (count($subscriptions) === 0) {
176
-			return null;
177
-		}
178
-
179
-		return $subscriptions[0];
180
-	}
181
-
182
-	/**
183
-	 * gets webcal feed from remote server
184
-	 *
185
-	 * @param array $subscription
186
-	 * @param array &$mutations
187
-	 * @return null|string
188
-	 */
189
-	private function queryWebcalFeed(array $subscription, array &$mutations) {
190
-		$client = $this->clientService->newClient();
191
-
192
-		$didBreak301Chain = false;
193
-		$latestLocation = null;
194
-
195
-		$handlerStack = HandlerStack::create();
196
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
197
-			return $request
198
-				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
199
-				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
200
-		}));
201
-		$handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
202
-			if (!$didBreak301Chain) {
203
-				if ($response->getStatusCode() !== 301) {
204
-					$didBreak301Chain = true;
205
-				} else {
206
-					$latestLocation = $response->getHeader('Location');
207
-				}
208
-			}
209
-			return $response;
210
-		}));
211
-
212
-		$allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
213
-		$subscriptionId = $subscription['id'];
214
-		$url = $this->cleanURL($subscription['source']);
215
-		if ($url === null) {
216
-			return null;
217
-		}
218
-
219
-		try {
220
-			$params = [
221
-				'allow_redirects' => [
222
-					'redirects' => 10
223
-				],
224
-				'handler' => $handlerStack,
225
-				'nextcloud' => [
226
-					'allow_local_address' => $allowLocalAccess === 'yes',
227
-				]
228
-			];
229
-
230
-			$user = parse_url($subscription['source'], PHP_URL_USER);
231
-			$pass = parse_url($subscription['source'], PHP_URL_PASS);
232
-			if ($user !== null && $pass !== null) {
233
-				$params['auth'] = [$user, $pass];
234
-			}
235
-
236
-			$response = $client->get($url, $params);
237
-			$body = $response->getBody();
238
-
239
-			if ($latestLocation) {
240
-				$mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
241
-			}
242
-
243
-			$contentType = $response->getHeader('Content-Type');
244
-			$contentType = explode(';', $contentType, 2)[0];
245
-			switch ($contentType) {
246
-				case 'application/calendar+json':
247
-					try {
248
-						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
249
-					} catch (Exception $ex) {
250
-						// In case of a parsing error return null
251
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
252
-						return null;
253
-					}
254
-					return $jCalendar->serialize();
255
-
256
-				case 'application/calendar+xml':
257
-					try {
258
-						$xCalendar = Reader::readXML($body);
259
-					} catch (Exception $ex) {
260
-						// In case of a parsing error return null
261
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
262
-						return null;
263
-					}
264
-					return $xCalendar->serialize();
265
-
266
-				case 'text/calendar':
267
-				default:
268
-					try {
269
-						$vCalendar = Reader::read($body);
270
-					} catch (Exception $ex) {
271
-						// In case of a parsing error return null
272
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
273
-						return null;
274
-					}
275
-					return $vCalendar->serialize();
276
-			}
277
-		} catch (LocalServerException $ex) {
278
-			$this->logger->logException($ex, [
279
-				'message' => "Subscription $subscriptionId was not refreshed because it violates local access rules",
280
-				'level' => ILogger::WARN,
281
-			]);
282
-
283
-			return null;
284
-		} catch (Exception $ex) {
285
-			$this->logger->logException($ex, [
286
-				'message' => "Subscription $subscriptionId could not be refreshed due to a network error",
287
-				'level' => ILogger::WARN,
288
-			]);
289
-
290
-			return null;
291
-		}
292
-	}
293
-
294
-	/**
295
-	 * check if:
296
-	 *  - current subscription stores a refreshrate
297
-	 *  - the webcal feed suggests a refreshrate
298
-	 *  - return suggested refreshrate if user didn't set a custom one
299
-	 *
300
-	 * @param array $subscription
301
-	 * @param string $webcalData
302
-	 * @return string|null
303
-	 */
304
-	private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
305
-		// if there is no refreshrate stored in the database, check the webcal feed
306
-		// whether it suggests any refresh rate and store that in the database
307
-		if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
308
-			return null;
309
-		}
310
-
311
-		/** @var Component\VCalendar $vCalendar */
312
-		$vCalendar = Reader::read($webcalData);
313
-
314
-		$newRefreshRate = null;
315
-		if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
316
-			$newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
317
-		}
318
-		if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
319
-			$newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
320
-		}
321
-
322
-		if (!$newRefreshRate) {
323
-			return null;
324
-		}
325
-
326
-		// check if new refresh rate is even valid
327
-		try {
328
-			DateTimeParser::parseDuration($newRefreshRate);
329
-		} catch (InvalidDataException $ex) {
330
-			return null;
331
-		}
332
-
333
-		return $newRefreshRate;
334
-	}
335
-
336
-	/**
337
-	 * update subscription stored in database
338
-	 * used to set:
339
-	 *  - refreshrate
340
-	 *  - source
341
-	 *
342
-	 * @param array $subscription
343
-	 * @param array $mutations
344
-	 */
345
-	private function updateSubscription(array $subscription, array $mutations) {
346
-		if (empty($mutations)) {
347
-			return;
348
-		}
349
-
350
-		$propPatch = new PropPatch($mutations);
351
-		$this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
352
-		$propPatch->commit();
353
-	}
354
-
355
-	/**
356
-	 * This method will strip authentication information and replace the
357
-	 * 'webcal' or 'webcals' protocol scheme
358
-	 *
359
-	 * @param string $url
360
-	 * @return string|null
361
-	 */
362
-	private function cleanURL(string $url) {
363
-		$parsed = parse_url($url);
364
-		if ($parsed === false) {
365
-			return null;
366
-		}
367
-
368
-		if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
369
-			$scheme = 'http';
370
-		} else {
371
-			$scheme = 'https';
372
-		}
373
-
374
-		$host = $parsed['host'] ?? '';
375
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
376
-		$path = $parsed['path'] ?? '';
377
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
378
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
379
-
380
-		$cleanURL = "$scheme://$host$port$path$query$fragment";
381
-		// parse_url is giving some weird results if no url and no :// is given,
382
-		// so let's test the url again
383
-		$parsedClean = parse_url($cleanURL);
384
-		if ($parsedClean === false || !isset($parsedClean['host'])) {
385
-			return null;
386
-		}
387
-
388
-		return $cleanURL;
389
-	}
390
-
391
-	/**
392
-	 * Returns a random uri for a calendar-object
393
-	 *
394
-	 * @return string
395
-	 */
396
-	public function getRandomCalendarObjectUri():string {
397
-		return UUIDUtil::getUUID() . '.ics';
398
-	}
54
+    /** @var CalDavBackend */
55
+    private $calDavBackend;
56
+
57
+    /** @var IClientService */
58
+    private $clientService;
59
+
60
+    /** @var IConfig */
61
+    private $config;
62
+
63
+    /** @var ILogger */
64
+    private $logger;
65
+
66
+    public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
67
+    public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
68
+    public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
69
+    public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
70
+
71
+    /**
72
+     * RefreshWebcalJob constructor.
73
+     *
74
+     * @param CalDavBackend $calDavBackend
75
+     * @param IClientService $clientService
76
+     * @param IConfig $config
77
+     * @param ILogger $logger
78
+     */
79
+    public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) {
80
+        $this->calDavBackend = $calDavBackend;
81
+        $this->clientService = $clientService;
82
+        $this->config = $config;
83
+        $this->logger = $logger;
84
+    }
85
+
86
+    /**
87
+     * @param string $principalUri
88
+     * @param string $uri
89
+     */
90
+    public function refreshSubscription(string $principalUri, string $uri) {
91
+        $subscription = $this->getSubscription($principalUri, $uri);
92
+        $mutations = [];
93
+        if (!$subscription) {
94
+            return;
95
+        }
96
+
97
+        $webcalData = $this->queryWebcalFeed($subscription, $mutations);
98
+        if (!$webcalData) {
99
+            return;
100
+        }
101
+
102
+        $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
103
+        $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
104
+        $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
105
+
106
+        try {
107
+            $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
108
+
109
+            // we wait with deleting all outdated events till we parsed the new ones
110
+            // in case the new calendar is broken and `new ICalendar` throws a ParseException
111
+            // the user will still see the old data
112
+            $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
113
+
114
+            while ($vObject = $splitter->getNext()) {
115
+                /** @var Component $vObject */
116
+                $compName = null;
117
+
118
+                foreach ($vObject->getComponents() as $component) {
119
+                    if ($component->name === 'VTIMEZONE') {
120
+                        continue;
121
+                    }
122
+
123
+                    $compName = $component->name;
124
+
125
+                    if ($stripAlarms) {
126
+                        unset($component->{'VALARM'});
127
+                    }
128
+                    if ($stripAttachments) {
129
+                        unset($component->{'ATTACH'});
130
+                    }
131
+                }
132
+
133
+                if ($stripTodos && $compName === 'VTODO') {
134
+                    continue;
135
+                }
136
+
137
+                $uri = $this->getRandomCalendarObjectUri();
138
+                $calendarData = $vObject->serialize();
139
+                try {
140
+                    $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
141
+                } catch (BadRequest $ex) {
142
+                    $this->logger->logException($ex);
143
+                }
144
+            }
145
+
146
+            $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
147
+            if ($newRefreshRate) {
148
+                $mutations[self::REFRESH_RATE] = $newRefreshRate;
149
+            }
150
+
151
+            $this->updateSubscription($subscription, $mutations);
152
+        } catch (ParseException $ex) {
153
+            $subscriptionId = $subscription['id'];
154
+
155
+            $this->logger->logException($ex);
156
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
157
+        }
158
+    }
159
+
160
+    /**
161
+     * loads subscription from backend
162
+     *
163
+     * @param string $principalUri
164
+     * @param string $uri
165
+     * @return array|null
166
+     */
167
+    public function getSubscription(string $principalUri, string $uri) {
168
+        $subscriptions = array_values(array_filter(
169
+            $this->calDavBackend->getSubscriptionsForUser($principalUri),
170
+            function ($sub) use ($uri) {
171
+                return $sub['uri'] === $uri;
172
+            }
173
+        ));
174
+
175
+        if (count($subscriptions) === 0) {
176
+            return null;
177
+        }
178
+
179
+        return $subscriptions[0];
180
+    }
181
+
182
+    /**
183
+     * gets webcal feed from remote server
184
+     *
185
+     * @param array $subscription
186
+     * @param array &$mutations
187
+     * @return null|string
188
+     */
189
+    private function queryWebcalFeed(array $subscription, array &$mutations) {
190
+        $client = $this->clientService->newClient();
191
+
192
+        $didBreak301Chain = false;
193
+        $latestLocation = null;
194
+
195
+        $handlerStack = HandlerStack::create();
196
+        $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
197
+            return $request
198
+                ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
199
+                ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
200
+        }));
201
+        $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
202
+            if (!$didBreak301Chain) {
203
+                if ($response->getStatusCode() !== 301) {
204
+                    $didBreak301Chain = true;
205
+                } else {
206
+                    $latestLocation = $response->getHeader('Location');
207
+                }
208
+            }
209
+            return $response;
210
+        }));
211
+
212
+        $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
213
+        $subscriptionId = $subscription['id'];
214
+        $url = $this->cleanURL($subscription['source']);
215
+        if ($url === null) {
216
+            return null;
217
+        }
218
+
219
+        try {
220
+            $params = [
221
+                'allow_redirects' => [
222
+                    'redirects' => 10
223
+                ],
224
+                'handler' => $handlerStack,
225
+                'nextcloud' => [
226
+                    'allow_local_address' => $allowLocalAccess === 'yes',
227
+                ]
228
+            ];
229
+
230
+            $user = parse_url($subscription['source'], PHP_URL_USER);
231
+            $pass = parse_url($subscription['source'], PHP_URL_PASS);
232
+            if ($user !== null && $pass !== null) {
233
+                $params['auth'] = [$user, $pass];
234
+            }
235
+
236
+            $response = $client->get($url, $params);
237
+            $body = $response->getBody();
238
+
239
+            if ($latestLocation) {
240
+                $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
241
+            }
242
+
243
+            $contentType = $response->getHeader('Content-Type');
244
+            $contentType = explode(';', $contentType, 2)[0];
245
+            switch ($contentType) {
246
+                case 'application/calendar+json':
247
+                    try {
248
+                        $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
249
+                    } catch (Exception $ex) {
250
+                        // In case of a parsing error return null
251
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
252
+                        return null;
253
+                    }
254
+                    return $jCalendar->serialize();
255
+
256
+                case 'application/calendar+xml':
257
+                    try {
258
+                        $xCalendar = Reader::readXML($body);
259
+                    } catch (Exception $ex) {
260
+                        // In case of a parsing error return null
261
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
262
+                        return null;
263
+                    }
264
+                    return $xCalendar->serialize();
265
+
266
+                case 'text/calendar':
267
+                default:
268
+                    try {
269
+                        $vCalendar = Reader::read($body);
270
+                    } catch (Exception $ex) {
271
+                        // In case of a parsing error return null
272
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
273
+                        return null;
274
+                    }
275
+                    return $vCalendar->serialize();
276
+            }
277
+        } catch (LocalServerException $ex) {
278
+            $this->logger->logException($ex, [
279
+                'message' => "Subscription $subscriptionId was not refreshed because it violates local access rules",
280
+                'level' => ILogger::WARN,
281
+            ]);
282
+
283
+            return null;
284
+        } catch (Exception $ex) {
285
+            $this->logger->logException($ex, [
286
+                'message' => "Subscription $subscriptionId could not be refreshed due to a network error",
287
+                'level' => ILogger::WARN,
288
+            ]);
289
+
290
+            return null;
291
+        }
292
+    }
293
+
294
+    /**
295
+     * check if:
296
+     *  - current subscription stores a refreshrate
297
+     *  - the webcal feed suggests a refreshrate
298
+     *  - return suggested refreshrate if user didn't set a custom one
299
+     *
300
+     * @param array $subscription
301
+     * @param string $webcalData
302
+     * @return string|null
303
+     */
304
+    private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
305
+        // if there is no refreshrate stored in the database, check the webcal feed
306
+        // whether it suggests any refresh rate and store that in the database
307
+        if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
308
+            return null;
309
+        }
310
+
311
+        /** @var Component\VCalendar $vCalendar */
312
+        $vCalendar = Reader::read($webcalData);
313
+
314
+        $newRefreshRate = null;
315
+        if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
316
+            $newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
317
+        }
318
+        if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
319
+            $newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
320
+        }
321
+
322
+        if (!$newRefreshRate) {
323
+            return null;
324
+        }
325
+
326
+        // check if new refresh rate is even valid
327
+        try {
328
+            DateTimeParser::parseDuration($newRefreshRate);
329
+        } catch (InvalidDataException $ex) {
330
+            return null;
331
+        }
332
+
333
+        return $newRefreshRate;
334
+    }
335
+
336
+    /**
337
+     * update subscription stored in database
338
+     * used to set:
339
+     *  - refreshrate
340
+     *  - source
341
+     *
342
+     * @param array $subscription
343
+     * @param array $mutations
344
+     */
345
+    private function updateSubscription(array $subscription, array $mutations) {
346
+        if (empty($mutations)) {
347
+            return;
348
+        }
349
+
350
+        $propPatch = new PropPatch($mutations);
351
+        $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
352
+        $propPatch->commit();
353
+    }
354
+
355
+    /**
356
+     * This method will strip authentication information and replace the
357
+     * 'webcal' or 'webcals' protocol scheme
358
+     *
359
+     * @param string $url
360
+     * @return string|null
361
+     */
362
+    private function cleanURL(string $url) {
363
+        $parsed = parse_url($url);
364
+        if ($parsed === false) {
365
+            return null;
366
+        }
367
+
368
+        if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
369
+            $scheme = 'http';
370
+        } else {
371
+            $scheme = 'https';
372
+        }
373
+
374
+        $host = $parsed['host'] ?? '';
375
+        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
376
+        $path = $parsed['path'] ?? '';
377
+        $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
378
+        $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
379
+
380
+        $cleanURL = "$scheme://$host$port$path$query$fragment";
381
+        // parse_url is giving some weird results if no url and no :// is given,
382
+        // so let's test the url again
383
+        $parsedClean = parse_url($cleanURL);
384
+        if ($parsedClean === false || !isset($parsedClean['host'])) {
385
+            return null;
386
+        }
387
+
388
+        return $cleanURL;
389
+    }
390
+
391
+    /**
392
+     * Returns a random uri for a calendar-object
393
+     *
394
+     * @return string
395
+     */
396
+    public function getRandomCalendarObjectUri():string {
397
+        return UUIDUtil::getUUID() . '.ics';
398
+    }
399 399
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	public function getSubscription(string $principalUri, string $uri) {
168 168
 		$subscriptions = array_values(array_filter(
169 169
 			$this->calDavBackend->getSubscriptionsForUser($principalUri),
170
-			function ($sub) use ($uri) {
170
+			function($sub) use ($uri) {
171 171
 				return $sub['uri'] === $uri;
172 172
 			}
173 173
 		));
@@ -193,12 +193,12 @@  discard block
 block discarded – undo
193 193
 		$latestLocation = null;
194 194
 
195 195
 		$handlerStack = HandlerStack::create();
196
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
196
+		$handlerStack->push(Middleware::mapRequest(function(RequestInterface $request) {
197 197
 			return $request
198 198
 				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
199 199
 				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
200 200
 		}));
201
-		$handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
201
+		$handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
202 202
 			if (!$didBreak301Chain) {
203 203
 				if ($response->getStatusCode() !== 301) {
204 204
 					$didBreak301Chain = true;
@@ -372,10 +372,10 @@  discard block
 block discarded – undo
372 372
 		}
373 373
 
374 374
 		$host = $parsed['host'] ?? '';
375
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
375
+		$port = isset($parsed['port']) ? ':'.$parsed['port'] : '';
376 376
 		$path = $parsed['path'] ?? '';
377
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
378
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
377
+		$query = isset($parsed['query']) ? '?'.$parsed['query'] : '';
378
+		$fragment = isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
379 379
 
380 380
 		$cleanURL = "$scheme://$host$port$path$query$fragment";
381 381
 		// parse_url is giving some weird results if no url and no :// is given,
@@ -394,6 +394,6 @@  discard block
 block discarded – undo
394 394
 	 * @return string
395 395
 	 */
396 396
 	public function getRandomCalendarObjectUri():string {
397
-		return UUIDUtil::getUUID() . '.ics';
397
+		return UUIDUtil::getUUID().'.ics';
398 398
 	}
399 399
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ExternalSharesController.php 1 patch
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -40,115 +40,115 @@
 block discarded – undo
40 40
  */
41 41
 class ExternalSharesController extends Controller {
42 42
 
43
-	/** @var \OCA\Files_Sharing\External\Manager */
44
-	private $externalManager;
45
-	/** @var IClientService */
46
-	private $clientService;
43
+    /** @var \OCA\Files_Sharing\External\Manager */
44
+    private $externalManager;
45
+    /** @var IClientService */
46
+    private $clientService;
47 47
 
48
-	/**
49
-	 * @param string $appName
50
-	 * @param IRequest $request
51
-	 * @param \OCA\Files_Sharing\External\Manager $externalManager
52
-	 * @param IClientService $clientService
53
-	 */
54
-	public function __construct($appName,
55
-								IRequest $request,
56
-								\OCA\Files_Sharing\External\Manager $externalManager,
57
-								IClientService $clientService) {
58
-		parent::__construct($appName, $request);
59
-		$this->externalManager = $externalManager;
60
-		$this->clientService = $clientService;
61
-	}
48
+    /**
49
+     * @param string $appName
50
+     * @param IRequest $request
51
+     * @param \OCA\Files_Sharing\External\Manager $externalManager
52
+     * @param IClientService $clientService
53
+     */
54
+    public function __construct($appName,
55
+                                IRequest $request,
56
+                                \OCA\Files_Sharing\External\Manager $externalManager,
57
+                                IClientService $clientService) {
58
+        parent::__construct($appName, $request);
59
+        $this->externalManager = $externalManager;
60
+        $this->clientService = $clientService;
61
+    }
62 62
 
63
-	/**
64
-	 * @NoAdminRequired
65
-	 * @NoOutgoingFederatedSharingRequired
66
-	 *
67
-	 * @return JSONResponse
68
-	 */
69
-	public function index() {
70
-		return new JSONResponse($this->externalManager->getOpenShares());
71
-	}
63
+    /**
64
+     * @NoAdminRequired
65
+     * @NoOutgoingFederatedSharingRequired
66
+     *
67
+     * @return JSONResponse
68
+     */
69
+    public function index() {
70
+        return new JSONResponse($this->externalManager->getOpenShares());
71
+    }
72 72
 
73
-	/**
74
-	 * @NoAdminRequired
75
-	 * @NoOutgoingFederatedSharingRequired
76
-	 *
77
-	 * @param int $id
78
-	 * @return JSONResponse
79
-	 */
80
-	public function create($id) {
81
-		$this->externalManager->acceptShare($id);
82
-		return new JSONResponse();
83
-	}
73
+    /**
74
+     * @NoAdminRequired
75
+     * @NoOutgoingFederatedSharingRequired
76
+     *
77
+     * @param int $id
78
+     * @return JSONResponse
79
+     */
80
+    public function create($id) {
81
+        $this->externalManager->acceptShare($id);
82
+        return new JSONResponse();
83
+    }
84 84
 
85
-	/**
86
-	 * @NoAdminRequired
87
-	 * @NoOutgoingFederatedSharingRequired
88
-	 *
89
-	 * @param integer $id
90
-	 * @return JSONResponse
91
-	 */
92
-	public function destroy($id) {
93
-		$this->externalManager->declineShare($id);
94
-		return new JSONResponse();
95
-	}
85
+    /**
86
+     * @NoAdminRequired
87
+     * @NoOutgoingFederatedSharingRequired
88
+     *
89
+     * @param integer $id
90
+     * @return JSONResponse
91
+     */
92
+    public function destroy($id) {
93
+        $this->externalManager->declineShare($id);
94
+        return new JSONResponse();
95
+    }
96 96
 
97
-	/**
98
-	 * Test whether the specified remote is accessible
99
-	 *
100
-	 * @param string $remote
101
-	 * @param bool $checkVersion
102
-	 * @return bool
103
-	 */
104
-	protected function testUrl($remote, $checkVersion = false) {
105
-		try {
106
-			$client = $this->clientService->newClient();
107
-			$response = json_decode($client->get(
108
-				$remote,
109
-				[
110
-					'timeout' => 3,
111
-					'connect_timeout' => 3,
112
-				]
113
-			)->getBody());
97
+    /**
98
+     * Test whether the specified remote is accessible
99
+     *
100
+     * @param string $remote
101
+     * @param bool $checkVersion
102
+     * @return bool
103
+     */
104
+    protected function testUrl($remote, $checkVersion = false) {
105
+        try {
106
+            $client = $this->clientService->newClient();
107
+            $response = json_decode($client->get(
108
+                $remote,
109
+                [
110
+                    'timeout' => 3,
111
+                    'connect_timeout' => 3,
112
+                ]
113
+            )->getBody());
114 114
 
115
-			if ($checkVersion) {
116
-				return !empty($response->version) && version_compare($response->version, '7.0.0', '>=');
117
-			} else {
118
-				return is_object($response);
119
-			}
120
-		} catch (\Exception $e) {
121
-			return false;
122
-		}
123
-	}
115
+            if ($checkVersion) {
116
+                return !empty($response->version) && version_compare($response->version, '7.0.0', '>=');
117
+            } else {
118
+                return is_object($response);
119
+            }
120
+        } catch (\Exception $e) {
121
+            return false;
122
+        }
123
+    }
124 124
 
125
-	/**
126
-	 * @PublicPage
127
-	 * @NoOutgoingFederatedSharingRequired
128
-	 * @NoIncomingFederatedSharingRequired
129
-	 *
130
-	 * @param string $remote
131
-	 * @return DataResponse
132
-	 */
133
-	public function testRemote($remote) {
134
-		if (strpos($remote, '#') !== false || strpos($remote, '?') !== false || strpos($remote, ';') !== false) {
135
-			return new DataResponse(false);
136
-		}
125
+    /**
126
+     * @PublicPage
127
+     * @NoOutgoingFederatedSharingRequired
128
+     * @NoIncomingFederatedSharingRequired
129
+     *
130
+     * @param string $remote
131
+     * @return DataResponse
132
+     */
133
+    public function testRemote($remote) {
134
+        if (strpos($remote, '#') !== false || strpos($remote, '?') !== false || strpos($remote, ';') !== false) {
135
+            return new DataResponse(false);
136
+        }
137 137
 
138
-		if (
139
-			$this->testUrl('https://' . $remote . '/ocs-provider/') ||
140
-			$this->testUrl('https://' . $remote . '/ocs-provider/index.php') ||
141
-			$this->testUrl('https://' . $remote . '/status.php', true)
142
-		) {
143
-			return new DataResponse('https');
144
-		} elseif (
145
-			$this->testUrl('http://' . $remote . '/ocs-provider/') ||
146
-			$this->testUrl('http://' . $remote . '/ocs-provider/index.php') ||
147
-			$this->testUrl('http://' . $remote . '/status.php', true)
148
-		) {
149
-			return new DataResponse('http');
150
-		} else {
151
-			return new DataResponse(false);
152
-		}
153
-	}
138
+        if (
139
+            $this->testUrl('https://' . $remote . '/ocs-provider/') ||
140
+            $this->testUrl('https://' . $remote . '/ocs-provider/index.php') ||
141
+            $this->testUrl('https://' . $remote . '/status.php', true)
142
+        ) {
143
+            return new DataResponse('https');
144
+        } elseif (
145
+            $this->testUrl('http://' . $remote . '/ocs-provider/') ||
146
+            $this->testUrl('http://' . $remote . '/ocs-provider/index.php') ||
147
+            $this->testUrl('http://' . $remote . '/status.php', true)
148
+        ) {
149
+            return new DataResponse('http');
150
+        } else {
151
+            return new DataResponse(false);
152
+        }
153
+    }
154 154
 }
Please login to merge, or discard this patch.