Completed
Push — master ( f8fd11...1da29c )
by
unknown
24:33
created
tests/lib/Template/CSSResourceLocatorTest.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -25,98 +25,98 @@
 block discarded – undo
25 25
 use Psr\Log\LoggerInterface;
26 26
 
27 27
 class CSSResourceLocatorTest extends \Test\TestCase {
28
-	private IAppData&MockObject $appData;
29
-	private IURLGenerator&MockObject $urlGenerator;
30
-	private IConfig&MockObject $config;
31
-	private ThemingDefaults&MockObject $themingDefaults;
32
-	private ICacheFactory&MockObject $cacheFactory;
33
-	private LoggerInterface&MockObject $logger;
34
-	private ITimeFactory&MockObject $timeFactory;
35
-	private AppConfig&MockObject $appConfig;
36
-
37
-	protected function setUp(): void {
38
-		parent::setUp();
39
-
40
-		$this->logger = $this->createMock(LoggerInterface::class);
41
-		$this->appData = $this->createMock(AppData::class);
42
-		$this->urlGenerator = $this->createMock(IURLGenerator::class);
43
-		$this->config = $this->createMock(IConfig::class);
44
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
45
-		$this->themingDefaults = $this->createMock(ThemingDefaults::class);
46
-		$this->timeFactory = $this->createMock(ITimeFactory::class);
47
-		$this->appConfig = $this->createMock(AppConfig::class);
48
-	}
49
-
50
-	private function cssResourceLocator() {
51
-		/** @var Factory|\PHPUnit\Framework\MockObject\MockObject $factory */
52
-		$factory = $this->createMock(Factory::class);
53
-		$factory->method('get')->with('css')->willReturn($this->appData);
54
-		return new CSSResourceLocator(
55
-			$this->logger,
56
-			$this->createMock(IConfig::class),
57
-			Server::get(IAppManager::class),
58
-			'theme',
59
-			['core' => 'map'],
60
-			['3rd' => 'party'],
61
-		);
62
-	}
63
-
64
-	private function rrmdir($directory) {
65
-		$files = array_diff(scandir($directory), ['.','..']);
66
-		foreach ($files as $file) {
67
-			if (is_dir($directory . '/' . $file)) {
68
-				$this->rrmdir($directory . '/' . $file);
69
-			} else {
70
-				unlink($directory . '/' . $file);
71
-			}
72
-		}
73
-		return rmdir($directory);
74
-	}
75
-
76
-	private function randomString(): string {
77
-		return sha1(random_bytes(10));
78
-	}
79
-
80
-	public function testFindWithAppPathSymlink(): void {
81
-		// First create new apps path, and a symlink to it
82
-		$apps_dirname = $this->randomString();
83
-		$new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
84
-		$new_apps_path_symlink = $new_apps_path . '_link';
85
-		mkdir($new_apps_path);
86
-		symlink($apps_dirname, $new_apps_path_symlink);
87
-
88
-		// Create an app within that path
89
-		mkdir($new_apps_path . '/' . 'test_css_app');
90
-
91
-		// Use the symlink as the app path
92
-		\OC::$APPSROOTS[] = [
93
-			'path' => $new_apps_path_symlink,
94
-			'url' => '/css-apps-test',
95
-			'writable' => false,
96
-		];
97
-
98
-		$locator = $this->cssResourceLocator();
99
-		$locator->find(['test_css_app/test-file']);
100
-
101
-		$resources = $locator->getResources();
102
-		$this->assertCount(1, $resources);
103
-		$resource = $resources[0];
104
-		$this->assertCount(3, $resource);
105
-		$root = $resource[0];
106
-		$webRoot = $resource[1];
107
-		$file = $resource[2];
108
-
109
-		$expectedRoot = $new_apps_path . '/test_css_app';
110
-		$expectedWebRoot = \OC::$WEBROOT . '/css-apps-test/test_css_app';
111
-		$expectedFile = 'test-file.css';
112
-
113
-		$this->assertEquals($expectedRoot, $root,
114
-			'Ensure the app path symlink is resolved into the real path');
115
-		$this->assertEquals($expectedWebRoot, $webRoot);
116
-		$this->assertEquals($expectedFile, $file);
117
-
118
-		array_pop(\OC::$APPSROOTS);
119
-		unlink($new_apps_path_symlink);
120
-		$this->rrmdir($new_apps_path);
121
-	}
28
+    private IAppData&MockObject $appData;
29
+    private IURLGenerator&MockObject $urlGenerator;
30
+    private IConfig&MockObject $config;
31
+    private ThemingDefaults&MockObject $themingDefaults;
32
+    private ICacheFactory&MockObject $cacheFactory;
33
+    private LoggerInterface&MockObject $logger;
34
+    private ITimeFactory&MockObject $timeFactory;
35
+    private AppConfig&MockObject $appConfig;
36
+
37
+    protected function setUp(): void {
38
+        parent::setUp();
39
+
40
+        $this->logger = $this->createMock(LoggerInterface::class);
41
+        $this->appData = $this->createMock(AppData::class);
42
+        $this->urlGenerator = $this->createMock(IURLGenerator::class);
43
+        $this->config = $this->createMock(IConfig::class);
44
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
45
+        $this->themingDefaults = $this->createMock(ThemingDefaults::class);
46
+        $this->timeFactory = $this->createMock(ITimeFactory::class);
47
+        $this->appConfig = $this->createMock(AppConfig::class);
48
+    }
49
+
50
+    private function cssResourceLocator() {
51
+        /** @var Factory|\PHPUnit\Framework\MockObject\MockObject $factory */
52
+        $factory = $this->createMock(Factory::class);
53
+        $factory->method('get')->with('css')->willReturn($this->appData);
54
+        return new CSSResourceLocator(
55
+            $this->logger,
56
+            $this->createMock(IConfig::class),
57
+            Server::get(IAppManager::class),
58
+            'theme',
59
+            ['core' => 'map'],
60
+            ['3rd' => 'party'],
61
+        );
62
+    }
63
+
64
+    private function rrmdir($directory) {
65
+        $files = array_diff(scandir($directory), ['.','..']);
66
+        foreach ($files as $file) {
67
+            if (is_dir($directory . '/' . $file)) {
68
+                $this->rrmdir($directory . '/' . $file);
69
+            } else {
70
+                unlink($directory . '/' . $file);
71
+            }
72
+        }
73
+        return rmdir($directory);
74
+    }
75
+
76
+    private function randomString(): string {
77
+        return sha1(random_bytes(10));
78
+    }
79
+
80
+    public function testFindWithAppPathSymlink(): void {
81
+        // First create new apps path, and a symlink to it
82
+        $apps_dirname = $this->randomString();
83
+        $new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
84
+        $new_apps_path_symlink = $new_apps_path . '_link';
85
+        mkdir($new_apps_path);
86
+        symlink($apps_dirname, $new_apps_path_symlink);
87
+
88
+        // Create an app within that path
89
+        mkdir($new_apps_path . '/' . 'test_css_app');
90
+
91
+        // Use the symlink as the app path
92
+        \OC::$APPSROOTS[] = [
93
+            'path' => $new_apps_path_symlink,
94
+            'url' => '/css-apps-test',
95
+            'writable' => false,
96
+        ];
97
+
98
+        $locator = $this->cssResourceLocator();
99
+        $locator->find(['test_css_app/test-file']);
100
+
101
+        $resources = $locator->getResources();
102
+        $this->assertCount(1, $resources);
103
+        $resource = $resources[0];
104
+        $this->assertCount(3, $resource);
105
+        $root = $resource[0];
106
+        $webRoot = $resource[1];
107
+        $file = $resource[2];
108
+
109
+        $expectedRoot = $new_apps_path . '/test_css_app';
110
+        $expectedWebRoot = \OC::$WEBROOT . '/css-apps-test/test_css_app';
111
+        $expectedFile = 'test-file.css';
112
+
113
+        $this->assertEquals($expectedRoot, $root,
114
+            'Ensure the app path symlink is resolved into the real path');
115
+        $this->assertEquals($expectedWebRoot, $webRoot);
116
+        $this->assertEquals($expectedFile, $file);
117
+
118
+        array_pop(\OC::$APPSROOTS);
119
+        unlink($new_apps_path_symlink);
120
+        $this->rrmdir($new_apps_path);
121
+    }
122 122
 }
Please login to merge, or discard this patch.
tests/lib/Template/JSCombinerTest.php 1 patch
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -25,511 +25,511 @@
 block discarded – undo
25 25
 use Psr\Log\LoggerInterface;
26 26
 
27 27
 class JSCombinerTest extends \Test\TestCase {
28
-	private IAppData&MockObject $appData;
29
-	private IURLGenerator&MockObject $urlGenerator;
30
-	private IConfig&MockObject $config;
31
-	private ICache&MockObject $depsCache;
32
-	private LoggerInterface&MockObject $logger;
33
-	private ICacheFactory&MockObject $cacheFactory;
34
-
35
-	private JSCombiner $jsCombiner;
36
-
37
-	protected function setUp(): void {
38
-		parent::setUp();
39
-
40
-		$this->appData = $this->createMock(IAppData::class);
41
-		$this->urlGenerator = $this->createMock(IURLGenerator::class);
42
-		$this->config = $this->createMock(IConfig::class);
43
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
44
-		$this->depsCache = $this->createMock(ICache::class);
45
-		$this->cacheFactory->expects($this->atLeastOnce())
46
-			->method('createDistributed')
47
-			->willReturn($this->depsCache);
48
-		$this->logger = $this->createMock(LoggerInterface::class);
49
-		$this->jsCombiner = new JSCombiner(
50
-			$this->appData,
51
-			$this->urlGenerator,
52
-			$this->cacheFactory,
53
-			$this->config,
54
-			$this->logger
55
-		);
56
-	}
57
-
58
-	public function testProcessDebugMode(): void {
59
-		$this->config
60
-			->expects($this->once())
61
-			->method('getSystemValueBool')
62
-			->with('debug')
63
-			->willReturn(true);
64
-
65
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
66
-		$this->assertFalse($actual);
67
-	}
68
-
69
-	public function testProcessNotInstalled(): void {
70
-		$this->config
71
-			->expects($this->exactly(2))
72
-			->method('getSystemValueBool')
73
-			->willReturnMap([
74
-				['debug', false],
75
-				['installed', false]
76
-			]);
77
-
78
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
79
-		$this->assertFalse($actual);
80
-	}
81
-
82
-	public function testProcessUncachedFileNoAppDataFolder(): void {
83
-		$this->config
84
-			->expects($this->exactly(2))
85
-			->method('getSystemValueBool')
86
-			->willReturnMap([
87
-				['debug', false],
88
-				['installed', true],
89
-			]);
90
-		$folder = $this->createMock(ISimpleFolder::class);
91
-		$this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willThrowException(new NotFoundException());
92
-		$this->appData->expects($this->once())->method('newFolder')->with('awesomeapp')->willReturn($folder);
93
-		$file = $this->createMock(ISimpleFile::class);
94
-		$gzfile = $this->createMock(ISimpleFile::class);
95
-
96
-		$fileDeps = $this->createMock(ISimpleFile::class);
97
-
98
-		$folder->method('getFile')
99
-			->willReturnCallback(function ($path) use ($file, $gzfile) {
100
-				if ($path === 'combine.js') {
101
-					return $file;
102
-				} elseif ($path === 'combine.js.deps') {
103
-					throw new NotFoundException();
104
-				} elseif ($path === 'combine.js.gzip') {
105
-					return $gzfile;
106
-				}
107
-				$this->fail();
108
-			});
109
-		$folder->expects($this->once())
110
-			->method('newFile')
111
-			->with('combine.js.deps')
112
-			->willReturn($fileDeps);
113
-
114
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
115
-		$this->assertTrue($actual);
116
-	}
117
-
118
-	public function testProcessUncachedFile(): void {
119
-		$this->config
120
-			->expects($this->exactly(2))
121
-			->method('getSystemValueBool')
122
-			->willReturnMap([
123
-				['debug', false],
124
-				['installed', true],
125
-			]);
126
-		$folder = $this->createMock(ISimpleFolder::class);
127
-		$this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder);
128
-		$file = $this->createMock(ISimpleFile::class);
129
-		$fileDeps = $this->createMock(ISimpleFile::class);
130
-		$gzfile = $this->createMock(ISimpleFile::class);
131
-
132
-		$folder->method('getFile')
133
-			->willReturnCallback(function ($path) use ($file, $gzfile) {
134
-				if ($path === 'combine.js') {
135
-					return $file;
136
-				} elseif ($path === 'combine.js.deps') {
137
-					throw new NotFoundException();
138
-				} elseif ($path === 'combine.js.gzip') {
139
-					return $gzfile;
140
-				}
141
-				$this->fail();
142
-			});
143
-		$folder->expects($this->once())
144
-			->method('newFile')
145
-			->with('combine.js.deps')
146
-			->willReturn($fileDeps);
147
-
148
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
149
-		$this->assertTrue($actual);
150
-	}
151
-
152
-	public function testProcessCachedFile(): void {
153
-		$this->config
154
-			->expects($this->exactly(2))
155
-			->method('getSystemValueBool')
156
-			->willReturnMap([
157
-				['debug', false],
158
-				['installed', true],
159
-			]);
160
-		$folder = $this->createMock(ISimpleFolder::class);
161
-		$this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder);
162
-		$file = $this->createMock(ISimpleFile::class);
163
-
164
-		$fileDeps = $this->createMock(ISimpleFile::class);
165
-
166
-		$fileDeps->expects($this->once())->method('getContent')->willReturn('{}');
167
-
168
-		$folder->method('fileExists')
169
-			->with('combine.js')
170
-			->willReturn(true);
171
-
172
-		$folder->method('getFile')
173
-			->willReturnCallback(function ($path) use ($file, $fileDeps) {
174
-				if ($path === 'combine.js') {
175
-					return $file;
176
-				}
177
-
178
-				if ($path === 'combine.js.deps') {
179
-					return $fileDeps;
180
-				}
181
-
182
-				$this->fail();
183
-			});
184
-
185
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
186
-		$this->assertTrue($actual);
187
-	}
188
-
189
-	public function testProcessCachedFileMemcache(): void {
190
-		$this->config
191
-			->expects($this->exactly(2))
192
-			->method('getSystemValueBool')
193
-			->willReturnMap([
194
-				['debug', false],
195
-				['installed', true],
196
-			]);
197
-		$folder = $this->createMock(ISimpleFolder::class);
198
-		$this->appData->expects($this->once())
199
-			->method('getFolder')
200
-			->with('awesomeapp')
201
-			->willReturn($folder);
202
-		$folder->method('getName')
203
-			->willReturn('awesomeapp');
204
-		$folder->method('fileExists')
205
-			->with('combine.js')
206
-			->willReturn(true);
207
-
208
-		$file = $this->createMock(ISimpleFile::class);
209
-
210
-		$this->depsCache->method('get')
211
-			->with('awesomeapp-combine.js.deps')
212
-			->willReturn('{}');
213
-
214
-		$folder->method('getFile')
215
-			->willReturnCallback(function ($path) use ($file) {
216
-				if ($path === 'combine.js') {
217
-					return $file;
218
-				}
219
-				$this->fail();
220
-			});
221
-
222
-		$actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
223
-		$this->assertTrue($actual);
224
-	}
225
-
226
-	public function testIsCachedNoDepsFile(): void {
227
-		$fileName = 'combine.json';
228
-		$folder = $this->createMock(ISimpleFolder::class);
229
-		$file = $this->createMock(ISimpleFile::class);
230
-
231
-		$folder->method('getFile')
232
-			->willReturnCallback(function ($path) use ($file) {
233
-				if ($path === 'combine.js') {
234
-					return $file;
235
-				}
236
-				if ($path === 'combine.js.deps') {
237
-					throw new NotFoundException();
238
-				}
239
-				$this->fail();
240
-			});
241
-
242
-		$actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
243
-		$this->assertFalse($actual);
244
-	}
245
-
246
-	public function testIsCachedWithNotExistingFile(): void {
247
-		$fileName = 'combine.json';
248
-		$folder = $this->createMock(ISimpleFolder::class);
249
-		$folder->method('fileExists')
250
-			->with('combine.js')
251
-			->willReturn(true);
252
-		$file = $this->createMock(ISimpleFile::class);
253
-		$folder->method('getFile')
254
-			->with('combine.js.deps')
255
-			->willReturn($file);
256
-		$file->expects($this->once())
257
-			->method('getContent')
258
-			->willReturn(json_encode(['/etc/certainlynotexisting/file/ihope' => 10000]));
259
-
260
-		$actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
261
-		$this->assertFalse($actual);
262
-	}
263
-
264
-	public function testIsCachedWithOlderMtime(): void {
265
-		$fileName = 'combine.json';
266
-		$folder = $this->createMock(ISimpleFolder::class);
267
-		$folder->method('fileExists')
268
-			->with('combine.js')
269
-			->willReturn(true);
270
-		$file = $this->createMock(ISimpleFile::class);
271
-		$folder->method('getFile')
272
-			->with('combine.js.deps')
273
-			->willReturn($file);
274
-		$file->expects($this->once())
275
-			->method('getContent')
276
-			->willReturn(json_encode([__FILE__ => 1234]));
277
-
278
-		$actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
279
-		$this->assertFalse($actual);
280
-	}
281
-
282
-	public function testIsCachedWithoutContent(): void {
283
-		$fileName = 'combine.json';
284
-		$folder = $this->createMock(ISimpleFolder::class);
285
-		$folder->method('fileExists')
286
-			->with('combine.js')
287
-			->willReturn(true);
288
-		$file = $this->createMock(ISimpleFile::class);
289
-		$folder->method('getFile')
290
-			->with('combine.js.deps')
291
-			->willReturn($file);
292
-		$file->expects($this->once())
293
-			->method('getContent')
294
-			->willReturn('');
295
-		$this->logger->expects($this->once())
296
-			->method('info')
297
-			->with('JSCombiner: deps file empty: combine.js.deps');
298
-		$actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
299
-		$this->assertFalse($actual);
300
-	}
301
-
302
-	public function testCacheNoFile(): void {
303
-		$fileName = 'combine.js';
304
-
305
-		$folder = $this->createMock(ISimpleFolder::class);
306
-		$file = $this->createMock(ISimpleFile::class);
307
-		$depsFile = $this->createMock(ISimpleFile::class);
308
-		$gzFile = $this->createMock(ISimpleFile::class);
309
-
310
-		$path = __DIR__ . '/data/';
311
-
312
-		$folder->method('getFile')->willThrowException(new NotFoundException());
313
-
314
-		$folder->method('newFile')->willReturnCallback(
315
-			function ($filename) use ($file, $depsFile, $gzFile) {
316
-				if ($filename === 'combine.js') {
317
-					return $file;
318
-				} elseif ($filename === 'combine.js.deps') {
319
-					return $depsFile;
320
-				} elseif ($filename === 'combine.js.gzip') {
321
-					return $gzFile;
322
-				}
323
-				$this->fail();
324
-			}
325
-		);
326
-
327
-		$file->expects($this->once())->method('putContent');
328
-		$depsFile->expects($this->once())->method('putContent');
329
-		$gzFile->expects($this->once())->method('putContent');
330
-
331
-		$actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
332
-		$this->assertTrue($actual);
333
-	}
334
-
335
-	public function testCache(): void {
336
-		$fileName = 'combine.js';
337
-
338
-		$folder = $this->createMock(ISimpleFolder::class);
339
-		$file = $this->createMock(ISimpleFile::class);
340
-		$depsFile = $this->createMock(ISimpleFile::class);
341
-		$gzFile = $this->createMock(ISimpleFile::class);
342
-
343
-		$path = __DIR__ . '/data/';
344
-
345
-		$folder->method('getFile')->willReturnCallback(
346
-			function ($filename) use ($file, $depsFile, $gzFile) {
347
-				if ($filename === 'combine.js') {
348
-					return $file;
349
-				} elseif ($filename === 'combine.js.deps') {
350
-					return $depsFile;
351
-				} elseif ($filename === 'combine.js.gzip') {
352
-					return $gzFile;
353
-				}
354
-				$this->fail();
355
-			}
356
-		);
357
-
358
-		$file->expects($this->once())->method('putContent');
359
-		$depsFile->expects($this->once())->method('putContent');
360
-		$gzFile->expects($this->once())->method('putContent');
361
-
362
-		$actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
363
-		$this->assertTrue($actual);
364
-	}
365
-
366
-	public function testCacheNotPermittedException(): void {
367
-		$fileName = 'combine.js';
368
-
369
-		$folder = $this->createMock(ISimpleFolder::class);
370
-		$file = $this->createMock(ISimpleFile::class);
371
-		$depsFile = $this->createMock(ISimpleFile::class);
372
-		$gzFile = $this->createMock(ISimpleFile::class);
373
-
374
-		$path = __DIR__ . '/data/';
375
-
376
-		$folder->expects($this->exactly(3))
377
-			->method('getFile')
378
-			->willReturnMap([
379
-				[$fileName, $file],
380
-				[$fileName . '.deps', $depsFile],
381
-				[$fileName . '.gzip', $gzFile]
382
-			]);
383
-
384
-		$file->expects($this->once())
385
-			->method('putContent')
386
-			->with('var a = \'hello\';
28
+    private IAppData&MockObject $appData;
29
+    private IURLGenerator&MockObject $urlGenerator;
30
+    private IConfig&MockObject $config;
31
+    private ICache&MockObject $depsCache;
32
+    private LoggerInterface&MockObject $logger;
33
+    private ICacheFactory&MockObject $cacheFactory;
34
+
35
+    private JSCombiner $jsCombiner;
36
+
37
+    protected function setUp(): void {
38
+        parent::setUp();
39
+
40
+        $this->appData = $this->createMock(IAppData::class);
41
+        $this->urlGenerator = $this->createMock(IURLGenerator::class);
42
+        $this->config = $this->createMock(IConfig::class);
43
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
44
+        $this->depsCache = $this->createMock(ICache::class);
45
+        $this->cacheFactory->expects($this->atLeastOnce())
46
+            ->method('createDistributed')
47
+            ->willReturn($this->depsCache);
48
+        $this->logger = $this->createMock(LoggerInterface::class);
49
+        $this->jsCombiner = new JSCombiner(
50
+            $this->appData,
51
+            $this->urlGenerator,
52
+            $this->cacheFactory,
53
+            $this->config,
54
+            $this->logger
55
+        );
56
+    }
57
+
58
+    public function testProcessDebugMode(): void {
59
+        $this->config
60
+            ->expects($this->once())
61
+            ->method('getSystemValueBool')
62
+            ->with('debug')
63
+            ->willReturn(true);
64
+
65
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
66
+        $this->assertFalse($actual);
67
+    }
68
+
69
+    public function testProcessNotInstalled(): void {
70
+        $this->config
71
+            ->expects($this->exactly(2))
72
+            ->method('getSystemValueBool')
73
+            ->willReturnMap([
74
+                ['debug', false],
75
+                ['installed', false]
76
+            ]);
77
+
78
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
79
+        $this->assertFalse($actual);
80
+    }
81
+
82
+    public function testProcessUncachedFileNoAppDataFolder(): void {
83
+        $this->config
84
+            ->expects($this->exactly(2))
85
+            ->method('getSystemValueBool')
86
+            ->willReturnMap([
87
+                ['debug', false],
88
+                ['installed', true],
89
+            ]);
90
+        $folder = $this->createMock(ISimpleFolder::class);
91
+        $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willThrowException(new NotFoundException());
92
+        $this->appData->expects($this->once())->method('newFolder')->with('awesomeapp')->willReturn($folder);
93
+        $file = $this->createMock(ISimpleFile::class);
94
+        $gzfile = $this->createMock(ISimpleFile::class);
95
+
96
+        $fileDeps = $this->createMock(ISimpleFile::class);
97
+
98
+        $folder->method('getFile')
99
+            ->willReturnCallback(function ($path) use ($file, $gzfile) {
100
+                if ($path === 'combine.js') {
101
+                    return $file;
102
+                } elseif ($path === 'combine.js.deps') {
103
+                    throw new NotFoundException();
104
+                } elseif ($path === 'combine.js.gzip') {
105
+                    return $gzfile;
106
+                }
107
+                $this->fail();
108
+            });
109
+        $folder->expects($this->once())
110
+            ->method('newFile')
111
+            ->with('combine.js.deps')
112
+            ->willReturn($fileDeps);
113
+
114
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
115
+        $this->assertTrue($actual);
116
+    }
117
+
118
+    public function testProcessUncachedFile(): void {
119
+        $this->config
120
+            ->expects($this->exactly(2))
121
+            ->method('getSystemValueBool')
122
+            ->willReturnMap([
123
+                ['debug', false],
124
+                ['installed', true],
125
+            ]);
126
+        $folder = $this->createMock(ISimpleFolder::class);
127
+        $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder);
128
+        $file = $this->createMock(ISimpleFile::class);
129
+        $fileDeps = $this->createMock(ISimpleFile::class);
130
+        $gzfile = $this->createMock(ISimpleFile::class);
131
+
132
+        $folder->method('getFile')
133
+            ->willReturnCallback(function ($path) use ($file, $gzfile) {
134
+                if ($path === 'combine.js') {
135
+                    return $file;
136
+                } elseif ($path === 'combine.js.deps') {
137
+                    throw new NotFoundException();
138
+                } elseif ($path === 'combine.js.gzip') {
139
+                    return $gzfile;
140
+                }
141
+                $this->fail();
142
+            });
143
+        $folder->expects($this->once())
144
+            ->method('newFile')
145
+            ->with('combine.js.deps')
146
+            ->willReturn($fileDeps);
147
+
148
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
149
+        $this->assertTrue($actual);
150
+    }
151
+
152
+    public function testProcessCachedFile(): void {
153
+        $this->config
154
+            ->expects($this->exactly(2))
155
+            ->method('getSystemValueBool')
156
+            ->willReturnMap([
157
+                ['debug', false],
158
+                ['installed', true],
159
+            ]);
160
+        $folder = $this->createMock(ISimpleFolder::class);
161
+        $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder);
162
+        $file = $this->createMock(ISimpleFile::class);
163
+
164
+        $fileDeps = $this->createMock(ISimpleFile::class);
165
+
166
+        $fileDeps->expects($this->once())->method('getContent')->willReturn('{}');
167
+
168
+        $folder->method('fileExists')
169
+            ->with('combine.js')
170
+            ->willReturn(true);
171
+
172
+        $folder->method('getFile')
173
+            ->willReturnCallback(function ($path) use ($file, $fileDeps) {
174
+                if ($path === 'combine.js') {
175
+                    return $file;
176
+                }
177
+
178
+                if ($path === 'combine.js.deps') {
179
+                    return $fileDeps;
180
+                }
181
+
182
+                $this->fail();
183
+            });
184
+
185
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
186
+        $this->assertTrue($actual);
187
+    }
188
+
189
+    public function testProcessCachedFileMemcache(): void {
190
+        $this->config
191
+            ->expects($this->exactly(2))
192
+            ->method('getSystemValueBool')
193
+            ->willReturnMap([
194
+                ['debug', false],
195
+                ['installed', true],
196
+            ]);
197
+        $folder = $this->createMock(ISimpleFolder::class);
198
+        $this->appData->expects($this->once())
199
+            ->method('getFolder')
200
+            ->with('awesomeapp')
201
+            ->willReturn($folder);
202
+        $folder->method('getName')
203
+            ->willReturn('awesomeapp');
204
+        $folder->method('fileExists')
205
+            ->with('combine.js')
206
+            ->willReturn(true);
207
+
208
+        $file = $this->createMock(ISimpleFile::class);
209
+
210
+        $this->depsCache->method('get')
211
+            ->with('awesomeapp-combine.js.deps')
212
+            ->willReturn('{}');
213
+
214
+        $folder->method('getFile')
215
+            ->willReturnCallback(function ($path) use ($file) {
216
+                if ($path === 'combine.js') {
217
+                    return $file;
218
+                }
219
+                $this->fail();
220
+            });
221
+
222
+        $actual = $this->jsCombiner->process(__DIR__, '/data/combine.json', 'awesomeapp');
223
+        $this->assertTrue($actual);
224
+    }
225
+
226
+    public function testIsCachedNoDepsFile(): void {
227
+        $fileName = 'combine.json';
228
+        $folder = $this->createMock(ISimpleFolder::class);
229
+        $file = $this->createMock(ISimpleFile::class);
230
+
231
+        $folder->method('getFile')
232
+            ->willReturnCallback(function ($path) use ($file) {
233
+                if ($path === 'combine.js') {
234
+                    return $file;
235
+                }
236
+                if ($path === 'combine.js.deps') {
237
+                    throw new NotFoundException();
238
+                }
239
+                $this->fail();
240
+            });
241
+
242
+        $actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
243
+        $this->assertFalse($actual);
244
+    }
245
+
246
+    public function testIsCachedWithNotExistingFile(): void {
247
+        $fileName = 'combine.json';
248
+        $folder = $this->createMock(ISimpleFolder::class);
249
+        $folder->method('fileExists')
250
+            ->with('combine.js')
251
+            ->willReturn(true);
252
+        $file = $this->createMock(ISimpleFile::class);
253
+        $folder->method('getFile')
254
+            ->with('combine.js.deps')
255
+            ->willReturn($file);
256
+        $file->expects($this->once())
257
+            ->method('getContent')
258
+            ->willReturn(json_encode(['/etc/certainlynotexisting/file/ihope' => 10000]));
259
+
260
+        $actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
261
+        $this->assertFalse($actual);
262
+    }
263
+
264
+    public function testIsCachedWithOlderMtime(): void {
265
+        $fileName = 'combine.json';
266
+        $folder = $this->createMock(ISimpleFolder::class);
267
+        $folder->method('fileExists')
268
+            ->with('combine.js')
269
+            ->willReturn(true);
270
+        $file = $this->createMock(ISimpleFile::class);
271
+        $folder->method('getFile')
272
+            ->with('combine.js.deps')
273
+            ->willReturn($file);
274
+        $file->expects($this->once())
275
+            ->method('getContent')
276
+            ->willReturn(json_encode([__FILE__ => 1234]));
277
+
278
+        $actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
279
+        $this->assertFalse($actual);
280
+    }
281
+
282
+    public function testIsCachedWithoutContent(): void {
283
+        $fileName = 'combine.json';
284
+        $folder = $this->createMock(ISimpleFolder::class);
285
+        $folder->method('fileExists')
286
+            ->with('combine.js')
287
+            ->willReturn(true);
288
+        $file = $this->createMock(ISimpleFile::class);
289
+        $folder->method('getFile')
290
+            ->with('combine.js.deps')
291
+            ->willReturn($file);
292
+        $file->expects($this->once())
293
+            ->method('getContent')
294
+            ->willReturn('');
295
+        $this->logger->expects($this->once())
296
+            ->method('info')
297
+            ->with('JSCombiner: deps file empty: combine.js.deps');
298
+        $actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]);
299
+        $this->assertFalse($actual);
300
+    }
301
+
302
+    public function testCacheNoFile(): void {
303
+        $fileName = 'combine.js';
304
+
305
+        $folder = $this->createMock(ISimpleFolder::class);
306
+        $file = $this->createMock(ISimpleFile::class);
307
+        $depsFile = $this->createMock(ISimpleFile::class);
308
+        $gzFile = $this->createMock(ISimpleFile::class);
309
+
310
+        $path = __DIR__ . '/data/';
311
+
312
+        $folder->method('getFile')->willThrowException(new NotFoundException());
313
+
314
+        $folder->method('newFile')->willReturnCallback(
315
+            function ($filename) use ($file, $depsFile, $gzFile) {
316
+                if ($filename === 'combine.js') {
317
+                    return $file;
318
+                } elseif ($filename === 'combine.js.deps') {
319
+                    return $depsFile;
320
+                } elseif ($filename === 'combine.js.gzip') {
321
+                    return $gzFile;
322
+                }
323
+                $this->fail();
324
+            }
325
+        );
326
+
327
+        $file->expects($this->once())->method('putContent');
328
+        $depsFile->expects($this->once())->method('putContent');
329
+        $gzFile->expects($this->once())->method('putContent');
330
+
331
+        $actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
332
+        $this->assertTrue($actual);
333
+    }
334
+
335
+    public function testCache(): void {
336
+        $fileName = 'combine.js';
337
+
338
+        $folder = $this->createMock(ISimpleFolder::class);
339
+        $file = $this->createMock(ISimpleFile::class);
340
+        $depsFile = $this->createMock(ISimpleFile::class);
341
+        $gzFile = $this->createMock(ISimpleFile::class);
342
+
343
+        $path = __DIR__ . '/data/';
344
+
345
+        $folder->method('getFile')->willReturnCallback(
346
+            function ($filename) use ($file, $depsFile, $gzFile) {
347
+                if ($filename === 'combine.js') {
348
+                    return $file;
349
+                } elseif ($filename === 'combine.js.deps') {
350
+                    return $depsFile;
351
+                } elseif ($filename === 'combine.js.gzip') {
352
+                    return $gzFile;
353
+                }
354
+                $this->fail();
355
+            }
356
+        );
357
+
358
+        $file->expects($this->once())->method('putContent');
359
+        $depsFile->expects($this->once())->method('putContent');
360
+        $gzFile->expects($this->once())->method('putContent');
361
+
362
+        $actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
363
+        $this->assertTrue($actual);
364
+    }
365
+
366
+    public function testCacheNotPermittedException(): void {
367
+        $fileName = 'combine.js';
368
+
369
+        $folder = $this->createMock(ISimpleFolder::class);
370
+        $file = $this->createMock(ISimpleFile::class);
371
+        $depsFile = $this->createMock(ISimpleFile::class);
372
+        $gzFile = $this->createMock(ISimpleFile::class);
373
+
374
+        $path = __DIR__ . '/data/';
375
+
376
+        $folder->expects($this->exactly(3))
377
+            ->method('getFile')
378
+            ->willReturnMap([
379
+                [$fileName, $file],
380
+                [$fileName . '.deps', $depsFile],
381
+                [$fileName . '.gzip', $gzFile]
382
+            ]);
383
+
384
+        $file->expects($this->once())
385
+            ->method('putContent')
386
+            ->with('var a = \'hello\';
387 387
 
388 388
 
389 389
 var b = \'world\';
390 390
 
391 391
 
392 392
 ');
393
-		$depsFile
394
-			->expects($this->once())
395
-			->method('putContent')
396
-			->with($this->callback(
397
-				function ($content) {
398
-					$deps = json_decode($content, true);
399
-					return array_key_exists(__DIR__ . '/data//1.js', $deps)
400
-						&& array_key_exists(__DIR__ . '/data//2.js', $deps);
401
-				}))
402
-			->willThrowException(new NotPermittedException());
403
-
404
-		$actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
405
-		$this->assertFalse($actual);
406
-	}
407
-
408
-	public function testCacheSuccess(): void {
409
-		$fileName = 'combine.js';
410
-
411
-		$folder = $this->createMock(ISimpleFolder::class);
412
-		$file = $this->createMock(ISimpleFile::class);
413
-		$depsFile = $this->createMock(ISimpleFile::class);
414
-		$gzFile = $this->createMock(ISimpleFile::class);
415
-
416
-		$path = __DIR__ . '/data/';
417
-
418
-
419
-		$folder->method('getFile')->willReturnCallback(
420
-			function ($filename) use ($file, $depsFile, $gzFile) {
421
-				if ($filename === 'combine.js') {
422
-					return $file;
423
-				} elseif ($filename === 'combine.js.deps') {
424
-					return $depsFile;
425
-				} elseif ($filename === 'combine.js.gzip') {
426
-					return $gzFile;
427
-				}
428
-				$this->fail();
429
-			}
430
-		);
431
-
432
-		$file->expects($this->once())
433
-			->method('putContent')
434
-			->with('var a = \'hello\';
393
+        $depsFile
394
+            ->expects($this->once())
395
+            ->method('putContent')
396
+            ->with($this->callback(
397
+                function ($content) {
398
+                    $deps = json_decode($content, true);
399
+                    return array_key_exists(__DIR__ . '/data//1.js', $deps)
400
+                        && array_key_exists(__DIR__ . '/data//2.js', $deps);
401
+                }))
402
+            ->willThrowException(new NotPermittedException());
403
+
404
+        $actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
405
+        $this->assertFalse($actual);
406
+    }
407
+
408
+    public function testCacheSuccess(): void {
409
+        $fileName = 'combine.js';
410
+
411
+        $folder = $this->createMock(ISimpleFolder::class);
412
+        $file = $this->createMock(ISimpleFile::class);
413
+        $depsFile = $this->createMock(ISimpleFile::class);
414
+        $gzFile = $this->createMock(ISimpleFile::class);
415
+
416
+        $path = __DIR__ . '/data/';
417
+
418
+
419
+        $folder->method('getFile')->willReturnCallback(
420
+            function ($filename) use ($file, $depsFile, $gzFile) {
421
+                if ($filename === 'combine.js') {
422
+                    return $file;
423
+                } elseif ($filename === 'combine.js.deps') {
424
+                    return $depsFile;
425
+                } elseif ($filename === 'combine.js.gzip') {
426
+                    return $gzFile;
427
+                }
428
+                $this->fail();
429
+            }
430
+        );
431
+
432
+        $file->expects($this->once())
433
+            ->method('putContent')
434
+            ->with('var a = \'hello\';
435 435
 
436 436
 
437 437
 var b = \'world\';
438 438
 
439 439
 
440 440
 ');
441
-		$depsFile->expects($this->once())->method('putContent')->with($this->callback(
442
-			function ($content) {
443
-				$deps = json_decode($content, true);
444
-				return array_key_exists(__DIR__ . '/data//1.js', $deps)
445
-					&& array_key_exists(__DIR__ . '/data//2.js', $deps);
446
-			}));
447
-		$gzFile->expects($this->once())->method('putContent')->with($this->callback(
448
-			function ($content) {
449
-				return gzdecode($content) === 'var a = \'hello\';
441
+        $depsFile->expects($this->once())->method('putContent')->with($this->callback(
442
+            function ($content) {
443
+                $deps = json_decode($content, true);
444
+                return array_key_exists(__DIR__ . '/data//1.js', $deps)
445
+                    && array_key_exists(__DIR__ . '/data//2.js', $deps);
446
+            }));
447
+        $gzFile->expects($this->once())->method('putContent')->with($this->callback(
448
+            function ($content) {
449
+                return gzdecode($content) === 'var a = \'hello\';
450 450
 
451 451
 
452 452
 var b = \'world\';
453 453
 
454 454
 
455 455
 ';
456
-			}
457
-		));
458
-
459
-		$actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
460
-		$this->assertTrue($actual);
461
-	}
462
-
463
-	public static function dataGetCachedSCSS(): array {
464
-		return [
465
-			['awesomeapp', 'core/js/foo.json', '/js/core/foo.js'],
466
-			['files', 'apps/files/js/foo.json', '/js/files/foo.js']
467
-		];
468
-	}
469
-
470
-	/**
471
-	 * @param $appName
472
-	 * @param $fileName
473
-	 * @param $result
474
-	 */
475
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataGetCachedSCSS')]
476
-	public function testGetCachedSCSS($appName, $fileName, $result): void {
477
-		$this->urlGenerator->expects($this->once())
478
-			->method('linkToRoute')
479
-			->with('core.Js.getJs', [
480
-				'fileName' => 'foo.js',
481
-				'appName' => $appName
482
-			])
483
-			->willReturn(\OC::$WEBROOT . $result);
484
-
485
-		$actual = $this->jsCombiner->getCachedJS($appName, $fileName);
486
-		$this->assertEquals(substr($result, 1), $actual);
487
-	}
488
-
489
-	public function testGetContent(): void {
490
-		// Create temporary file with some content
491
-		$tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest');
492
-		$pathInfo = pathinfo($tmpFile);
493
-		file_put_contents($tmpFile, json_encode(['/foo/bar/test', $pathInfo['dirname'] . '/js/mytest.js']));
494
-		$tmpFilePathArray = explode('/', $pathInfo['basename']);
495
-		array_pop($tmpFilePathArray);
496
-
497
-		$expected = [
498
-			'//foo/bar/test',
499
-			'/' . implode('/', $tmpFilePathArray) . $pathInfo['dirname'] . '/js/mytest.js',
500
-		];
501
-		$this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
502
-	}
503
-
504
-	public function testGetContentInvalidJson(): void {
505
-		// Create temporary file with some content
506
-		$tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest');
507
-		$pathInfo = pathinfo($tmpFile);
508
-		file_put_contents($tmpFile, 'CertainlyNotJson');
509
-		$expected = [];
510
-		$this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
511
-	}
512
-
513
-	public function testResetCache(): void {
514
-		$file = $this->createMock(ISimpleFile::class);
515
-		$file->expects($this->once())
516
-			->method('delete');
517
-
518
-		$folder = $this->createMock(ISimpleFolder::class);
519
-		$folder->expects($this->once())
520
-			->method('getDirectoryListing')
521
-			->willReturn([$file]);
522
-
523
-		$cache = $this->createMock(ICache::class);
524
-		$this->cacheFactory->expects($this->once())
525
-			->method('createDistributed')
526
-			->willReturn($cache);
527
-		$cache->expects($this->never())
528
-			->method('clear');
529
-		$this->appData->expects($this->once())
530
-			->method('getDirectoryListing')
531
-			->willReturn([$folder]);
532
-
533
-		$this->jsCombiner->resetCache();
534
-	}
456
+            }
457
+        ));
458
+
459
+        $actual = self::invokePrivate($this->jsCombiner, 'cache', [$path, 'combine.json', $folder]);
460
+        $this->assertTrue($actual);
461
+    }
462
+
463
+    public static function dataGetCachedSCSS(): array {
464
+        return [
465
+            ['awesomeapp', 'core/js/foo.json', '/js/core/foo.js'],
466
+            ['files', 'apps/files/js/foo.json', '/js/files/foo.js']
467
+        ];
468
+    }
469
+
470
+    /**
471
+     * @param $appName
472
+     * @param $fileName
473
+     * @param $result
474
+     */
475
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCachedSCSS')]
476
+    public function testGetCachedSCSS($appName, $fileName, $result): void {
477
+        $this->urlGenerator->expects($this->once())
478
+            ->method('linkToRoute')
479
+            ->with('core.Js.getJs', [
480
+                'fileName' => 'foo.js',
481
+                'appName' => $appName
482
+            ])
483
+            ->willReturn(\OC::$WEBROOT . $result);
484
+
485
+        $actual = $this->jsCombiner->getCachedJS($appName, $fileName);
486
+        $this->assertEquals(substr($result, 1), $actual);
487
+    }
488
+
489
+    public function testGetContent(): void {
490
+        // Create temporary file with some content
491
+        $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest');
492
+        $pathInfo = pathinfo($tmpFile);
493
+        file_put_contents($tmpFile, json_encode(['/foo/bar/test', $pathInfo['dirname'] . '/js/mytest.js']));
494
+        $tmpFilePathArray = explode('/', $pathInfo['basename']);
495
+        array_pop($tmpFilePathArray);
496
+
497
+        $expected = [
498
+            '//foo/bar/test',
499
+            '/' . implode('/', $tmpFilePathArray) . $pathInfo['dirname'] . '/js/mytest.js',
500
+        ];
501
+        $this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
502
+    }
503
+
504
+    public function testGetContentInvalidJson(): void {
505
+        // Create temporary file with some content
506
+        $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('JSCombinerTest');
507
+        $pathInfo = pathinfo($tmpFile);
508
+        file_put_contents($tmpFile, 'CertainlyNotJson');
509
+        $expected = [];
510
+        $this->assertEquals($expected, $this->jsCombiner->getContent($pathInfo['dirname'], $pathInfo['basename']));
511
+    }
512
+
513
+    public function testResetCache(): void {
514
+        $file = $this->createMock(ISimpleFile::class);
515
+        $file->expects($this->once())
516
+            ->method('delete');
517
+
518
+        $folder = $this->createMock(ISimpleFolder::class);
519
+        $folder->expects($this->once())
520
+            ->method('getDirectoryListing')
521
+            ->willReturn([$file]);
522
+
523
+        $cache = $this->createMock(ICache::class);
524
+        $this->cacheFactory->expects($this->once())
525
+            ->method('createDistributed')
526
+            ->willReturn($cache);
527
+        $cache->expects($this->never())
528
+            ->method('clear');
529
+        $this->appData->expects($this->once())
530
+            ->method('getDirectoryListing')
531
+            ->willReturn([$folder]);
532
+
533
+        $this->jsCombiner->resetCache();
534
+    }
535 535
 }
Please login to merge, or discard this patch.
tests/lib/Template/JSResourceLocatorTest.php 1 patch
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -21,161 +21,161 @@
 block discarded – undo
21 21
 use Psr\Log\LoggerInterface;
22 22
 
23 23
 class JSResourceLocatorTest extends \Test\TestCase {
24
-	private IAppData&MockObject $appData;
25
-	private IURLGenerator&MockObject $urlGenerator;
26
-	private IConfig&MockObject $config;
27
-	private ICacheFactory&MockObject $cacheFactory;
28
-	private LoggerInterface&MockObject $logger;
29
-	private IAppManager&MockObject $appManager;
30
-
31
-	protected function setUp(): void {
32
-		parent::setUp();
33
-
34
-		$this->appData = $this->createMock(IAppData::class);
35
-		$this->urlGenerator = $this->createMock(IURLGenerator::class);
36
-		$this->config = $this->createMock(IConfig::class);
37
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
38
-		$this->logger = $this->createMock(LoggerInterface::class);
39
-		$this->appManager = $this->createMock(IAppManager::class);
40
-	}
41
-
42
-	private function jsResourceLocator(): JSResourceLocator {
43
-		$jsCombiner = new JSCombiner(
44
-			$this->appData,
45
-			$this->urlGenerator,
46
-			$this->cacheFactory,
47
-			$this->config,
48
-			$this->logger
49
-		);
50
-		return new JSResourceLocator(
51
-			$this->logger,
52
-			$this->config,
53
-			$jsCombiner,
54
-			$this->appManager,
55
-		);
56
-	}
57
-
58
-	private function rrmdir($directory) {
59
-		$files = array_diff(scandir($directory), ['.','..']);
60
-		foreach ($files as $file) {
61
-			if (is_dir($directory . '/' . $file)) {
62
-				$this->rrmdir($directory . '/' . $file);
63
-			} else {
64
-				unlink($directory . '/' . $file);
65
-			}
66
-		}
67
-		return rmdir($directory);
68
-	}
69
-
70
-	private function randomString(): string {
71
-		return sha1(random_bytes(10));
72
-	}
73
-
74
-	public function testFindWithAppPathSymlink(): void {
75
-		$appName = 'test-js-app';
76
-
77
-		// First create new apps path, and a symlink to it
78
-		$apps_dirname = $this->randomString();
79
-		$new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
80
-		$new_apps_path_symlink = $new_apps_path . '_link';
81
-		$this->assertTrue((
82
-			mkdir($new_apps_path) && symlink($apps_dirname, $new_apps_path_symlink)
83
-		), 'Setup of apps path failed');
84
-
85
-		// Create an app within that path
86
-		$this->assertTrue((
87
-			mkdir($new_apps_path . '/' . $appName) && touch($new_apps_path . '/' . $appName . '/' . 'test-file.js')
88
-		), 'Setup of app within the new apps path failed');
89
-
90
-		// Use the symlink as the app path
91
-		$this->appManager->expects($this->once())
92
-			->method('getAppPath')
93
-			->with($appName)
94
-			->willReturn("$new_apps_path_symlink/$appName");
95
-		$this->appManager->expects($this->once())
96
-			->method('getAppWebPath')
97
-			->with($appName)
98
-			->willReturn("/js-apps-test/$appName");
99
-
100
-		// Run the tests
101
-		$locator = $this->jsResourceLocator();
102
-		$locator->find(["$appName/test-file"]);
103
-
104
-		$resources = $locator->getResources();
105
-		$this->assertCount(1, $resources);
106
-		$resource = $resources[0];
107
-		$this->assertCount(3, $resource);
108
-		$root = $resource[0];
109
-		$webRoot = $resource[1];
110
-		$file = $resource[2];
111
-
112
-		$expectedRoot = $new_apps_path;
113
-		$expectedWebRoot = \OC::$WEBROOT . '/js-apps-test';
114
-		$expectedFile = $appName . '/test-file.js';
115
-
116
-		$this->assertEquals($expectedRoot, $root,
117
-			'Ensure the app path symlink is resolved into the real path');
118
-		$this->assertEquals($expectedWebRoot, $webRoot);
119
-		$this->assertEquals($expectedFile, $file);
120
-
121
-		unlink($new_apps_path_symlink);
122
-		$this->rrmdir($new_apps_path);
123
-	}
124
-
125
-	public function testNotExistingTranslationHandledSilent(): void {
126
-		$this->appManager->expects($this->once())
127
-			->method('getAppPath')
128
-			->with('core')
129
-			->willThrowException(new AppPathNotFoundException());
130
-		$this->appManager->expects($this->atMost(1))
131
-			->method('getAppWebPath')
132
-			->with('core')
133
-			->willThrowException(new AppPathNotFoundException());
134
-		// Assert logger is not called
135
-		$this->logger->expects($this->never())
136
-			->method('error');
137
-
138
-		// Run the tests
139
-		$locator = $this->jsResourceLocator();
140
-		$locator->find(['core/l10n/en.js']);
141
-
142
-		$resources = $locator->getResources();
143
-		$this->assertCount(0, $resources);
144
-	}
145
-
146
-	public function testFindModuleJSWithFallback(): void {
147
-		// First create new apps path, and a symlink to it
148
-		$apps_dirname = $this->randomString();
149
-		$new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
150
-		mkdir($new_apps_path);
151
-
152
-		// Create an app within that path
153
-		mkdir("$new_apps_path/test-js-app");
154
-		touch("$new_apps_path/test-js-app/module.mjs");
155
-		touch("$new_apps_path/test-js-app/both.mjs");
156
-		touch("$new_apps_path/test-js-app/both.js");
157
-		touch("$new_apps_path/test-js-app/plain.js");
158
-
159
-		// Use the app path
160
-		$this->appManager->expects($this->any())
161
-			->method('getAppPath')
162
-			->with('test-js-app')
163
-			->willReturn("$new_apps_path/test-js-app");
164
-
165
-		$locator = $this->jsResourceLocator();
166
-		$locator->find(['test-js-app/module', 'test-js-app/both', 'test-js-app/plain']);
167
-
168
-		$resources = $locator->getResources();
169
-		$this->assertCount(3, $resources);
170
-
171
-		$expectedWebRoot = \OC::$WEBROOT . '/js-apps-test/test-js-app';
172
-		$expectedFiles = ['module.mjs', 'both.mjs', 'plain.js'];
173
-
174
-		for ($idx = 0; $idx++; $idx < 3) {
175
-			$this->assertEquals($expectedWebRoot, $resources[$idx][1]);
176
-			$this->assertEquals($expectedFiles[$idx], $resources[$idx][2]);
177
-		}
178
-
179
-		$this->rrmdir($new_apps_path);
180
-	}
24
+    private IAppData&MockObject $appData;
25
+    private IURLGenerator&MockObject $urlGenerator;
26
+    private IConfig&MockObject $config;
27
+    private ICacheFactory&MockObject $cacheFactory;
28
+    private LoggerInterface&MockObject $logger;
29
+    private IAppManager&MockObject $appManager;
30
+
31
+    protected function setUp(): void {
32
+        parent::setUp();
33
+
34
+        $this->appData = $this->createMock(IAppData::class);
35
+        $this->urlGenerator = $this->createMock(IURLGenerator::class);
36
+        $this->config = $this->createMock(IConfig::class);
37
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
38
+        $this->logger = $this->createMock(LoggerInterface::class);
39
+        $this->appManager = $this->createMock(IAppManager::class);
40
+    }
41
+
42
+    private function jsResourceLocator(): JSResourceLocator {
43
+        $jsCombiner = new JSCombiner(
44
+            $this->appData,
45
+            $this->urlGenerator,
46
+            $this->cacheFactory,
47
+            $this->config,
48
+            $this->logger
49
+        );
50
+        return new JSResourceLocator(
51
+            $this->logger,
52
+            $this->config,
53
+            $jsCombiner,
54
+            $this->appManager,
55
+        );
56
+    }
57
+
58
+    private function rrmdir($directory) {
59
+        $files = array_diff(scandir($directory), ['.','..']);
60
+        foreach ($files as $file) {
61
+            if (is_dir($directory . '/' . $file)) {
62
+                $this->rrmdir($directory . '/' . $file);
63
+            } else {
64
+                unlink($directory . '/' . $file);
65
+            }
66
+        }
67
+        return rmdir($directory);
68
+    }
69
+
70
+    private function randomString(): string {
71
+        return sha1(random_bytes(10));
72
+    }
73
+
74
+    public function testFindWithAppPathSymlink(): void {
75
+        $appName = 'test-js-app';
76
+
77
+        // First create new apps path, and a symlink to it
78
+        $apps_dirname = $this->randomString();
79
+        $new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
80
+        $new_apps_path_symlink = $new_apps_path . '_link';
81
+        $this->assertTrue((
82
+            mkdir($new_apps_path) && symlink($apps_dirname, $new_apps_path_symlink)
83
+        ), 'Setup of apps path failed');
84
+
85
+        // Create an app within that path
86
+        $this->assertTrue((
87
+            mkdir($new_apps_path . '/' . $appName) && touch($new_apps_path . '/' . $appName . '/' . 'test-file.js')
88
+        ), 'Setup of app within the new apps path failed');
89
+
90
+        // Use the symlink as the app path
91
+        $this->appManager->expects($this->once())
92
+            ->method('getAppPath')
93
+            ->with($appName)
94
+            ->willReturn("$new_apps_path_symlink/$appName");
95
+        $this->appManager->expects($this->once())
96
+            ->method('getAppWebPath')
97
+            ->with($appName)
98
+            ->willReturn("/js-apps-test/$appName");
99
+
100
+        // Run the tests
101
+        $locator = $this->jsResourceLocator();
102
+        $locator->find(["$appName/test-file"]);
103
+
104
+        $resources = $locator->getResources();
105
+        $this->assertCount(1, $resources);
106
+        $resource = $resources[0];
107
+        $this->assertCount(3, $resource);
108
+        $root = $resource[0];
109
+        $webRoot = $resource[1];
110
+        $file = $resource[2];
111
+
112
+        $expectedRoot = $new_apps_path;
113
+        $expectedWebRoot = \OC::$WEBROOT . '/js-apps-test';
114
+        $expectedFile = $appName . '/test-file.js';
115
+
116
+        $this->assertEquals($expectedRoot, $root,
117
+            'Ensure the app path symlink is resolved into the real path');
118
+        $this->assertEquals($expectedWebRoot, $webRoot);
119
+        $this->assertEquals($expectedFile, $file);
120
+
121
+        unlink($new_apps_path_symlink);
122
+        $this->rrmdir($new_apps_path);
123
+    }
124
+
125
+    public function testNotExistingTranslationHandledSilent(): void {
126
+        $this->appManager->expects($this->once())
127
+            ->method('getAppPath')
128
+            ->with('core')
129
+            ->willThrowException(new AppPathNotFoundException());
130
+        $this->appManager->expects($this->atMost(1))
131
+            ->method('getAppWebPath')
132
+            ->with('core')
133
+            ->willThrowException(new AppPathNotFoundException());
134
+        // Assert logger is not called
135
+        $this->logger->expects($this->never())
136
+            ->method('error');
137
+
138
+        // Run the tests
139
+        $locator = $this->jsResourceLocator();
140
+        $locator->find(['core/l10n/en.js']);
141
+
142
+        $resources = $locator->getResources();
143
+        $this->assertCount(0, $resources);
144
+    }
145
+
146
+    public function testFindModuleJSWithFallback(): void {
147
+        // First create new apps path, and a symlink to it
148
+        $apps_dirname = $this->randomString();
149
+        $new_apps_path = sys_get_temp_dir() . '/' . $apps_dirname;
150
+        mkdir($new_apps_path);
151
+
152
+        // Create an app within that path
153
+        mkdir("$new_apps_path/test-js-app");
154
+        touch("$new_apps_path/test-js-app/module.mjs");
155
+        touch("$new_apps_path/test-js-app/both.mjs");
156
+        touch("$new_apps_path/test-js-app/both.js");
157
+        touch("$new_apps_path/test-js-app/plain.js");
158
+
159
+        // Use the app path
160
+        $this->appManager->expects($this->any())
161
+            ->method('getAppPath')
162
+            ->with('test-js-app')
163
+            ->willReturn("$new_apps_path/test-js-app");
164
+
165
+        $locator = $this->jsResourceLocator();
166
+        $locator->find(['test-js-app/module', 'test-js-app/both', 'test-js-app/plain']);
167
+
168
+        $resources = $locator->getResources();
169
+        $this->assertCount(3, $resources);
170
+
171
+        $expectedWebRoot = \OC::$WEBROOT . '/js-apps-test/test-js-app';
172
+        $expectedFiles = ['module.mjs', 'both.mjs', 'plain.js'];
173
+
174
+        for ($idx = 0; $idx++; $idx < 3) {
175
+            $this->assertEquals($expectedWebRoot, $resources[$idx][1]);
176
+            $this->assertEquals($expectedFiles[$idx], $resources[$idx][2]);
177
+        }
178
+
179
+        $this->rrmdir($new_apps_path);
180
+    }
181 181
 }
Please login to merge, or discard this patch.
tests/lib/Template/ResourceLocatorTest.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -17,64 +17,64 @@
 block discarded – undo
17 17
 use Psr\Log\LoggerInterface;
18 18
 
19 19
 class ResourceLocatorTest extends \Test\TestCase {
20
-	private LoggerInterface&MockObject $logger;
21
-	private IConfig&MockObject $config;
20
+    private LoggerInterface&MockObject $logger;
21
+    private IConfig&MockObject $config;
22 22
 
23
-	protected function setUp(): void {
24
-		parent::setUp();
25
-		$this->logger = $this->createMock(LoggerInterface::class);
26
-		$this->config = $this->createMock(IConfig::class);
27
-	}
23
+    protected function setUp(): void {
24
+        parent::setUp();
25
+        $this->logger = $this->createMock(LoggerInterface::class);
26
+        $this->config = $this->createMock(IConfig::class);
27
+    }
28 28
 
29
-	public function getResourceLocator(string $theme): ResourceLocator&MockObject {
30
-		$this->config
31
-			->expects($this->any())
32
-			->method('getSystemValueString')
33
-			->with('theme', '')
34
-			->willReturn($theme);
35
-		return $this->getMockForAbstractClass(ResourceLocator::class,
36
-			[$this->logger, $this->config],
37
-			'', true, true, true, []);
38
-	}
29
+    public function getResourceLocator(string $theme): ResourceLocator&MockObject {
30
+        $this->config
31
+            ->expects($this->any())
32
+            ->method('getSystemValueString')
33
+            ->with('theme', '')
34
+            ->willReturn($theme);
35
+        return $this->getMockForAbstractClass(ResourceLocator::class,
36
+            [$this->logger, $this->config],
37
+            '', true, true, true, []);
38
+    }
39 39
 
40
-	public function testFind(): void {
41
-		$locator = $this->getResourceLocator('theme');
42
-		$locator->expects($this->once())
43
-			->method('doFind')
44
-			->with('foo');
45
-		$locator->expects($this->once())
46
-			->method('doFindTheme')
47
-			->with('foo');
48
-		$locator->find(['foo']);
49
-	}
40
+    public function testFind(): void {
41
+        $locator = $this->getResourceLocator('theme');
42
+        $locator->expects($this->once())
43
+            ->method('doFind')
44
+            ->with('foo');
45
+        $locator->expects($this->once())
46
+            ->method('doFindTheme')
47
+            ->with('foo');
48
+        $locator->find(['foo']);
49
+    }
50 50
 
51
-	public function testFindNotFound(): void {
52
-		$locator = $this->getResourceLocator('theme',
53
-			['core' => 'map'], ['3rd' => 'party'], ['foo' => 'bar']);
54
-		$locator->expects($this->once())
55
-			->method('doFind')
56
-			->with('foo')
57
-			->willThrowException(new ResourceNotFoundException('foo', 'map'));
58
-		$locator->expects($this->once())
59
-			->method('doFindTheme')
60
-			->with('foo')
61
-			->willThrowException(new ResourceNotFoundException('foo', 'map'));
62
-		$this->logger->expects($this->exactly(2))
63
-			->method('debug')
64
-			->with($this->stringContains('map/foo'));
65
-		$locator->find(['foo']);
66
-	}
51
+    public function testFindNotFound(): void {
52
+        $locator = $this->getResourceLocator('theme',
53
+            ['core' => 'map'], ['3rd' => 'party'], ['foo' => 'bar']);
54
+        $locator->expects($this->once())
55
+            ->method('doFind')
56
+            ->with('foo')
57
+            ->willThrowException(new ResourceNotFoundException('foo', 'map'));
58
+        $locator->expects($this->once())
59
+            ->method('doFindTheme')
60
+            ->with('foo')
61
+            ->willThrowException(new ResourceNotFoundException('foo', 'map'));
62
+        $this->logger->expects($this->exactly(2))
63
+            ->method('debug')
64
+            ->with($this->stringContains('map/foo'));
65
+        $locator->find(['foo']);
66
+    }
67 67
 
68
-	public function testAppendIfExist(): void {
69
-		$locator = $this->getResourceLocator('theme');
70
-		$method = new \ReflectionMethod($locator, 'appendIfExist');
71
-		$method->setAccessible(true);
68
+    public function testAppendIfExist(): void {
69
+        $locator = $this->getResourceLocator('theme');
70
+        $method = new \ReflectionMethod($locator, 'appendIfExist');
71
+        $method->setAccessible(true);
72 72
 
73
-		$method->invoke($locator, __DIR__, basename(__FILE__), 'webroot');
74
-		$resource1 = [__DIR__, 'webroot', basename(__FILE__)];
75
-		$this->assertEquals([$resource1], $locator->getResources());
73
+        $method->invoke($locator, __DIR__, basename(__FILE__), 'webroot');
74
+        $resource1 = [__DIR__, 'webroot', basename(__FILE__)];
75
+        $this->assertEquals([$resource1], $locator->getResources());
76 76
 
77
-		$method->invoke($locator, __DIR__, 'does-not-exist');
78
-		$this->assertEquals([$resource1], $locator->getResources());
79
-	}
77
+        $method->invoke($locator, __DIR__, 'does-not-exist');
78
+        $this->assertEquals([$resource1], $locator->getResources());
79
+    }
80 80
 }
Please login to merge, or discard this patch.
tests/lib/TemplateLayoutTest.php 2 patches
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -21,97 +21,97 @@
 block discarded – undo
21 21
 use PHPUnit\Framework\MockObject\MockObject;
22 22
 
23 23
 class TemplateLayoutTest extends \Test\TestCase {
24
-	private IConfig&MockObject $config;
25
-	private IAppConfig&MockObject $appConfig;
26
-	private IAppManager&MockObject $appManager;
27
-	private InitialStateService&MockObject $initialState;
28
-	private INavigationManager&MockObject $navigationManager;
29
-	private ITemplateManager&MockObject $templateManager;
30
-	private ServerVersion&MockObject $serverVersion;
31
-
32
-	private TemplateLayout $templateLayout;
33
-
34
-	protected function setUp(): void {
35
-		parent::setUp();
36
-
37
-		$this->config = $this->createMock(IConfig::class);
38
-		$this->appConfig = $this->createMock(IAppConfig::class);
39
-		$this->appManager = $this->createMock(IAppManager::class);
40
-		$this->initialState = $this->createMock(InitialStateService::class);
41
-		$this->navigationManager = $this->createMock(INavigationManager::class);
42
-		$this->templateManager = $this->createMock(ITemplateManager::class);
43
-		$this->serverVersion = $this->createMock(ServerVersion::class);
44
-	}
45
-
46
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataVersionHash')]
47
-	public function testVersionHash(
48
-		string|false $path,
49
-		string|false $file,
50
-		bool $installed,
51
-		bool $debug,
52
-		string $expected,
53
-	): void {
54
-		$this->appManager->expects(self::any())
55
-			->method('getAppVersion')
56
-			->willReturnCallback(fn ($appId) => match ($appId) {
57
-				'shippedApp' => 'shipped_1',
58
-				'otherApp' => 'other_2',
59
-				default => "$appId",
60
-			});
61
-		$this->appManager->expects(self::any())
62
-			->method('isShipped')
63
-			->willReturnCallback(fn (string $app) => $app === 'shippedApp');
64
-
65
-		$this->config->expects(self::atLeastOnce())
66
-			->method('getSystemValueBool')
67
-			->willReturnMap([
68
-				['installed', $installed],
69
-				['debug', $debug],
70
-			]);
71
-		$this->config->expects(self::any())
72
-			->method('getAppValue')
73
-			->with('theming', 'cachebuster', '0')
74
-			->willReturn('42');
75
-
76
-		$this->templateLayout = $this->getMockBuilder(TemplateLayout::class)
77
-			->onlyMethods(['getAppNamefromPath'])
78
-			->setConstructorArgs([
79
-				$this->config,
80
-				$this->appConfig,
81
-				$this->appManager,
82
-				$this->initialState,
83
-				$this->navigationManager,
84
-				$this->templateManager,
85
-				$this->serverVersion,
86
-			])
87
-			->getMock();
88
-
89
-		$layout = $this->templateLayout->getPageTemplate(TemplateResponse::RENDER_AS_ERROR, '');
90
-
91
-		self::invokePrivate(TemplateLayout::class, 'versionHash', ['version_hash']);
92
-
93
-		$this->templateLayout->expects(self::any())
94
-			->method('getAppNamefromPath')
95
-			->willReturnCallback(fn ($appName) => match($appName) {
96
-				'apps/shipped' => 'shippedApp',
97
-				'other/app.css' => 'otherApp',
98
-				default => false,
99
-			});
100
-
101
-		$hash = self::invokePrivate($this->templateLayout, 'getVersionHashSuffix', [$path, $file]);
102
-		self::assertEquals($expected, $hash);
103
-	}
104
-
105
-	public static function dataVersionHash() {
106
-		return [
107
-			'no hash if in debug mode' => ['apps/shipped', 'style.css', true, true, ''],
108
-			'only version hash if not installed' => ['apps/shipped', 'style.css', false, false, '?v=version_hash'],
109
-			'version hash with cache buster if app not found' => ['unknown/path', '', true, false, '?v=version_hash-42'],
110
-			'version hash with cache buster if neither path nor file provided' => [false, false, true, false, '?v=version_hash-42'],
111
-			'app version hash if external app' => ['', 'other/app.css', true, false, '?v=' . substr(md5('other_2'), 0, 8) . '-42'],
112
-			'app version and version hash if shipped app' => ['apps/shipped', 'style.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
113
-			'prefer path over file' => ['apps/shipped', 'other/app.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
114
-		];
115
-	}
24
+    private IConfig&MockObject $config;
25
+    private IAppConfig&MockObject $appConfig;
26
+    private IAppManager&MockObject $appManager;
27
+    private InitialStateService&MockObject $initialState;
28
+    private INavigationManager&MockObject $navigationManager;
29
+    private ITemplateManager&MockObject $templateManager;
30
+    private ServerVersion&MockObject $serverVersion;
31
+
32
+    private TemplateLayout $templateLayout;
33
+
34
+    protected function setUp(): void {
35
+        parent::setUp();
36
+
37
+        $this->config = $this->createMock(IConfig::class);
38
+        $this->appConfig = $this->createMock(IAppConfig::class);
39
+        $this->appManager = $this->createMock(IAppManager::class);
40
+        $this->initialState = $this->createMock(InitialStateService::class);
41
+        $this->navigationManager = $this->createMock(INavigationManager::class);
42
+        $this->templateManager = $this->createMock(ITemplateManager::class);
43
+        $this->serverVersion = $this->createMock(ServerVersion::class);
44
+    }
45
+
46
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataVersionHash')]
47
+    public function testVersionHash(
48
+        string|false $path,
49
+        string|false $file,
50
+        bool $installed,
51
+        bool $debug,
52
+        string $expected,
53
+    ): void {
54
+        $this->appManager->expects(self::any())
55
+            ->method('getAppVersion')
56
+            ->willReturnCallback(fn ($appId) => match ($appId) {
57
+                'shippedApp' => 'shipped_1',
58
+                'otherApp' => 'other_2',
59
+                default => "$appId",
60
+            });
61
+        $this->appManager->expects(self::any())
62
+            ->method('isShipped')
63
+            ->willReturnCallback(fn (string $app) => $app === 'shippedApp');
64
+
65
+        $this->config->expects(self::atLeastOnce())
66
+            ->method('getSystemValueBool')
67
+            ->willReturnMap([
68
+                ['installed', $installed],
69
+                ['debug', $debug],
70
+            ]);
71
+        $this->config->expects(self::any())
72
+            ->method('getAppValue')
73
+            ->with('theming', 'cachebuster', '0')
74
+            ->willReturn('42');
75
+
76
+        $this->templateLayout = $this->getMockBuilder(TemplateLayout::class)
77
+            ->onlyMethods(['getAppNamefromPath'])
78
+            ->setConstructorArgs([
79
+                $this->config,
80
+                $this->appConfig,
81
+                $this->appManager,
82
+                $this->initialState,
83
+                $this->navigationManager,
84
+                $this->templateManager,
85
+                $this->serverVersion,
86
+            ])
87
+            ->getMock();
88
+
89
+        $layout = $this->templateLayout->getPageTemplate(TemplateResponse::RENDER_AS_ERROR, '');
90
+
91
+        self::invokePrivate(TemplateLayout::class, 'versionHash', ['version_hash']);
92
+
93
+        $this->templateLayout->expects(self::any())
94
+            ->method('getAppNamefromPath')
95
+            ->willReturnCallback(fn ($appName) => match($appName) {
96
+                'apps/shipped' => 'shippedApp',
97
+                'other/app.css' => 'otherApp',
98
+                default => false,
99
+            });
100
+
101
+        $hash = self::invokePrivate($this->templateLayout, 'getVersionHashSuffix', [$path, $file]);
102
+        self::assertEquals($expected, $hash);
103
+    }
104
+
105
+    public static function dataVersionHash() {
106
+        return [
107
+            'no hash if in debug mode' => ['apps/shipped', 'style.css', true, true, ''],
108
+            'only version hash if not installed' => ['apps/shipped', 'style.css', false, false, '?v=version_hash'],
109
+            'version hash with cache buster if app not found' => ['unknown/path', '', true, false, '?v=version_hash-42'],
110
+            'version hash with cache buster if neither path nor file provided' => [false, false, true, false, '?v=version_hash-42'],
111
+            'app version hash if external app' => ['', 'other/app.css', true, false, '?v=' . substr(md5('other_2'), 0, 8) . '-42'],
112
+            'app version and version hash if shipped app' => ['apps/shipped', 'style.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
113
+            'prefer path over file' => ['apps/shipped', 'other/app.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
114
+        ];
115
+    }
116 116
 
117 117
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -45,8 +45,8 @@  discard block
 block discarded – undo
45 45
 
46 46
 	#[\PHPUnit\Framework\Attributes\DataProvider('dataVersionHash')]
47 47
 	public function testVersionHash(
48
-		string|false $path,
49
-		string|false $file,
48
+		string | false $path,
49
+		string | false $file,
50 50
 		bool $installed,
51 51
 		bool $debug,
52 52
 		string $expected,
@@ -108,9 +108,9 @@  discard block
 block discarded – undo
108 108
 			'only version hash if not installed' => ['apps/shipped', 'style.css', false, false, '?v=version_hash'],
109 109
 			'version hash with cache buster if app not found' => ['unknown/path', '', true, false, '?v=version_hash-42'],
110 110
 			'version hash with cache buster if neither path nor file provided' => [false, false, true, false, '?v=version_hash-42'],
111
-			'app version hash if external app' => ['', 'other/app.css', true, false, '?v=' . substr(md5('other_2'), 0, 8) . '-42'],
112
-			'app version and version hash if shipped app' => ['apps/shipped', 'style.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
113
-			'prefer path over file' => ['apps/shipped', 'other/app.css', true, false, '?v=' . substr(md5('shipped_1-version_hash'), 0, 8) . '-42'],
111
+			'app version hash if external app' => ['', 'other/app.css', true, false, '?v='.substr(md5('other_2'), 0, 8).'-42'],
112
+			'app version and version hash if shipped app' => ['apps/shipped', 'style.css', true, false, '?v='.substr(md5('shipped_1-version_hash'), 0, 8).'-42'],
113
+			'prefer path over file' => ['apps/shipped', 'other/app.css', true, false, '?v='.substr(md5('shipped_1-version_hash'), 0, 8).'-42'],
114 114
 		];
115 115
 	}
116 116
 
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1372 added lines, -1372 removed lines patch added patch discarded remove patch
@@ -248,1417 +248,1417 @@
 block discarded – undo
248 248
  * TODO: hookup all manager classes
249 249
  */
250 250
 class Server extends ServerContainer implements IServerContainer {
251
-	/** @var string */
252
-	private $webRoot;
253
-
254
-	/**
255
-	 * @param string $webRoot
256
-	 * @param \OC\Config $config
257
-	 */
258
-	public function __construct($webRoot, \OC\Config $config) {
259
-		parent::__construct();
260
-		$this->webRoot = $webRoot;
261
-
262
-		// To find out if we are running from CLI or not
263
-		$this->registerParameter('isCLI', \OC::$CLI);
264
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
265
-
266
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
267
-			return $c;
268
-		});
269
-		$this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
270
-
271
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
272
-
273
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
274
-
275
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
276
-
277
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
278
-
279
-		$this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
280
-
281
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
282
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
283
-		$this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
284
-
285
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
286
-
287
-		$this->registerService(View::class, function (Server $c) {
288
-			return new View();
289
-		}, false);
290
-
291
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
292
-			return new PreviewManager(
293
-				$c->get(\OCP\IConfig::class),
294
-				$c->get(IRootFolder::class),
295
-				new \OC\Preview\Storage\Root(
296
-					$c->get(IRootFolder::class),
297
-					$c->get(SystemConfig::class)
298
-				),
299
-				$c->get(IEventDispatcher::class),
300
-				$c->get(GeneratorHelper::class),
301
-				$c->get(ISession::class)->get('user_id'),
302
-				$c->get(Coordinator::class),
303
-				$c->get(IServerContainer::class),
304
-				$c->get(IBinaryFinder::class),
305
-				$c->get(IMagickSupport::class)
306
-			);
307
-		});
308
-		$this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
309
-
310
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
311
-			return new \OC\Preview\Watcher(
312
-				new \OC\Preview\Storage\Root(
313
-					$c->get(IRootFolder::class),
314
-					$c->get(SystemConfig::class)
315
-				)
316
-			);
317
-		});
318
-
319
-		$this->registerService(IProfiler::class, function (Server $c) {
320
-			return new Profiler($c->get(SystemConfig::class));
321
-		});
322
-
323
-		$this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
324
-			$view = new View();
325
-			$util = new Encryption\Util(
326
-				$view,
327
-				$c->get(IUserManager::class),
328
-				$c->get(IGroupManager::class),
329
-				$c->get(\OCP\IConfig::class)
330
-			);
331
-			return new Encryption\Manager(
332
-				$c->get(\OCP\IConfig::class),
333
-				$c->get(LoggerInterface::class),
334
-				$c->getL10N('core'),
335
-				new View(),
336
-				$util,
337
-				new ArrayCache()
338
-			);
339
-		});
340
-		$this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
341
-
342
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
343
-			$util = new Encryption\Util(
344
-				new View(),
345
-				$c->get(IUserManager::class),
346
-				$c->get(IGroupManager::class),
347
-				$c->get(\OCP\IConfig::class)
348
-			);
349
-			return new Encryption\File(
350
-				$util,
351
-				$c->get(IRootFolder::class),
352
-				$c->get(\OCP\Share\IManager::class)
353
-			);
354
-		});
355
-
356
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
357
-			$view = new View();
358
-			$util = new Encryption\Util(
359
-				$view,
360
-				$c->get(IUserManager::class),
361
-				$c->get(IGroupManager::class),
362
-				$c->get(\OCP\IConfig::class)
363
-			);
364
-
365
-			return new Encryption\Keys\Storage(
366
-				$view,
367
-				$util,
368
-				$c->get(ICrypto::class),
369
-				$c->get(\OCP\IConfig::class)
370
-			);
371
-		});
372
-
373
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
374
-
375
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
376
-			/** @var \OCP\IConfig $config */
377
-			$config = $c->get(\OCP\IConfig::class);
378
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
379
-			return new $factoryClass($this);
380
-		});
381
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
382
-			return $c->get('SystemTagManagerFactory')->getManager();
383
-		});
384
-		/** @deprecated 19.0.0 */
385
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
386
-
387
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
388
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
389
-		});
390
-		$this->registerAlias(IFileAccess::class, FileAccess::class);
391
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
392
-			$manager = \OC\Files\Filesystem::getMountManager();
393
-			$view = new View();
394
-			/** @var IUserSession $userSession */
395
-			$userSession = $c->get(IUserSession::class);
396
-			$root = new Root(
397
-				$manager,
398
-				$view,
399
-				$userSession->getUser(),
400
-				$c->get(IUserMountCache::class),
401
-				$this->get(LoggerInterface::class),
402
-				$this->get(IUserManager::class),
403
-				$this->get(IEventDispatcher::class),
404
-				$this->get(ICacheFactory::class),
405
-			);
406
-
407
-			$previewConnector = new \OC\Preview\WatcherConnector(
408
-				$root,
409
-				$c->get(SystemConfig::class),
410
-				$this->get(IEventDispatcher::class)
411
-			);
412
-			$previewConnector->connectWatcher();
413
-
414
-			return $root;
415
-		});
416
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
417
-			return new HookConnector(
418
-				$c->get(IRootFolder::class),
419
-				new View(),
420
-				$c->get(IEventDispatcher::class),
421
-				$c->get(LoggerInterface::class)
422
-			);
423
-		});
424
-
425
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
426
-			return new LazyRoot(function () use ($c) {
427
-				return $c->get('RootFolder');
428
-			});
429
-		});
430
-
431
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
432
-
433
-		$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
434
-			return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
435
-		});
436
-
437
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
438
-			$groupManager = new \OC\Group\Manager(
439
-				$this->get(IUserManager::class),
440
-				$this->get(IEventDispatcher::class),
441
-				$this->get(LoggerInterface::class),
442
-				$this->get(ICacheFactory::class),
443
-				$this->get(IRemoteAddress::class),
444
-			);
445
-			return $groupManager;
446
-		});
447
-
448
-		$this->registerService(Store::class, function (ContainerInterface $c) {
449
-			$session = $c->get(ISession::class);
450
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
451
-				$tokenProvider = $c->get(IProvider::class);
452
-			} else {
453
-				$tokenProvider = null;
454
-			}
455
-			$logger = $c->get(LoggerInterface::class);
456
-			$crypto = $c->get(ICrypto::class);
457
-			return new Store($session, $logger, $crypto, $tokenProvider);
458
-		});
459
-		$this->registerAlias(IStore::class, Store::class);
460
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
461
-		$this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
462
-
463
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
464
-			$manager = $c->get(IUserManager::class);
465
-			$session = new \OC\Session\Memory();
466
-			$timeFactory = new TimeFactory();
467
-			// Token providers might require a working database. This code
468
-			// might however be called when Nextcloud is not yet setup.
469
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
470
-				$provider = $c->get(IProvider::class);
471
-			} else {
472
-				$provider = null;
473
-			}
474
-
475
-			$userSession = new \OC\User\Session(
476
-				$manager,
477
-				$session,
478
-				$timeFactory,
479
-				$provider,
480
-				$c->get(\OCP\IConfig::class),
481
-				$c->get(ISecureRandom::class),
482
-				$c->get('LockdownManager'),
483
-				$c->get(LoggerInterface::class),
484
-				$c->get(IEventDispatcher::class),
485
-			);
486
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
487
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
488
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
489
-			});
490
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
491
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
492
-				/** @var \OC\User\User $user */
493
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
494
-			});
495
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
496
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
497
-				/** @var \OC\User\User $user */
498
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
499
-			});
500
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
501
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
502
-				/** @var \OC\User\User $user */
503
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
504
-			});
505
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
506
-				/** @var \OC\User\User $user */
507
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
508
-			});
509
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
510
-				/** @var \OC\User\User $user */
511
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
512
-			});
513
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
514
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
515
-
516
-				/** @var IEventDispatcher $dispatcher */
517
-				$dispatcher = $this->get(IEventDispatcher::class);
518
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
519
-			});
520
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
521
-				/** @var \OC\User\User $user */
522
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
523
-
524
-				/** @var IEventDispatcher $dispatcher */
525
-				$dispatcher = $this->get(IEventDispatcher::class);
526
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
527
-			});
528
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
529
-				/** @var IEventDispatcher $dispatcher */
530
-				$dispatcher = $this->get(IEventDispatcher::class);
531
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
532
-			});
533
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
534
-				/** @var \OC\User\User $user */
535
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
536
-
537
-				/** @var IEventDispatcher $dispatcher */
538
-				$dispatcher = $this->get(IEventDispatcher::class);
539
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
540
-			});
541
-			$userSession->listen('\OC\User', 'logout', function ($user) {
542
-				\OC_Hook::emit('OC_User', 'logout', []);
543
-
544
-				/** @var IEventDispatcher $dispatcher */
545
-				$dispatcher = $this->get(IEventDispatcher::class);
546
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
547
-			});
548
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
549
-				/** @var IEventDispatcher $dispatcher */
550
-				$dispatcher = $this->get(IEventDispatcher::class);
551
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
552
-			});
553
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
554
-				/** @var \OC\User\User $user */
555
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
556
-			});
557
-			return $userSession;
558
-		});
559
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
560
-
561
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
562
-
563
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
564
-
565
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
566
-
567
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
568
-			return new \OC\SystemConfig($config);
569
-		});
570
-
571
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
572
-		$this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
573
-		$this->registerAlias(IAppManager::class, AppManager::class);
574
-
575
-		$this->registerService(IFactory::class, function (Server $c) {
576
-			return new \OC\L10N\Factory(
577
-				$c->get(\OCP\IConfig::class),
578
-				$c->getRequest(),
579
-				$c->get(IUserSession::class),
580
-				$c->get(ICacheFactory::class),
581
-				\OC::$SERVERROOT,
582
-				$c->get(IAppManager::class),
583
-			);
584
-		});
585
-
586
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
587
-
588
-		$this->registerAlias(ICache::class, Cache\File::class);
589
-		$this->registerService(Factory::class, function (Server $c) {
590
-			$profiler = $c->get(IProfiler::class);
591
-			$logger = $c->get(LoggerInterface::class);
592
-			$serverVersion = $c->get(ServerVersion::class);
593
-			/** @var SystemConfig $config */
594
-			$config = $c->get(SystemConfig::class);
595
-			if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
596
-				return new \OC\Memcache\Factory(
597
-					$logger,
598
-					$profiler,
599
-					$serverVersion,
600
-					ArrayCache::class,
601
-					ArrayCache::class,
602
-					ArrayCache::class
603
-				);
604
-			}
605
-
606
-			return new \OC\Memcache\Factory(
607
-				$logger,
608
-				$profiler,
609
-				$serverVersion,
610
-				/** @psalm-taint-escape callable */
611
-				$config->getValue('memcache.local', null),
612
-				/** @psalm-taint-escape callable */
613
-				$config->getValue('memcache.distributed', null),
614
-				/** @psalm-taint-escape callable */
615
-				$config->getValue('memcache.locking', null),
616
-				/** @psalm-taint-escape callable */
617
-				$config->getValue('redis_log_file')
618
-			);
619
-		});
620
-		$this->registerAlias(ICacheFactory::class, Factory::class);
621
-
622
-		$this->registerService('RedisFactory', function (Server $c) {
623
-			$systemConfig = $c->get(SystemConfig::class);
624
-			return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
625
-		});
626
-
627
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
628
-			$l10n = $this->get(IFactory::class)->get('lib');
629
-			return new \OC\Activity\Manager(
630
-				$c->getRequest(),
631
-				$c->get(IUserSession::class),
632
-				$c->get(\OCP\IConfig::class),
633
-				$c->get(IValidator::class),
634
-				$c->get(IRichTextFormatter::class),
635
-				$l10n,
636
-				$c->get(ITimeFactory::class),
637
-			);
638
-		});
639
-
640
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
641
-			return new \OC\Activity\EventMerger(
642
-				$c->getL10N('lib')
643
-			);
644
-		});
645
-		$this->registerAlias(IValidator::class, Validator::class);
646
-
647
-		$this->registerService(AvatarManager::class, function (Server $c) {
648
-			return new AvatarManager(
649
-				$c->get(IUserSession::class),
650
-				$c->get(\OC\User\Manager::class),
651
-				$c->getAppDataDir('avatar'),
652
-				$c->getL10N('lib'),
653
-				$c->get(LoggerInterface::class),
654
-				$c->get(\OCP\IConfig::class),
655
-				$c->get(IAccountManager::class),
656
-				$c->get(KnownUserService::class)
657
-			);
658
-		});
659
-
660
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
661
-
662
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
663
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
664
-		$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
665
-
666
-		/** Only used by the PsrLoggerAdapter should not be used by apps */
667
-		$this->registerService(\OC\Log::class, function (Server $c) {
668
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
669
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
670
-			$logger = $factory->get($logType);
671
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
672
-
673
-			return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
674
-		});
675
-		// PSR-3 logger
676
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
677
-
678
-		$this->registerService(ILogFactory::class, function (Server $c) {
679
-			return new LogFactory($c, $this->get(SystemConfig::class));
680
-		});
681
-
682
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
683
-
684
-		$this->registerService(Router::class, function (Server $c) {
685
-			$cacheFactory = $c->get(ICacheFactory::class);
686
-			if ($cacheFactory->isLocalCacheAvailable()) {
687
-				$router = $c->resolve(CachingRouter::class);
688
-			} else {
689
-				$router = $c->resolve(Router::class);
690
-			}
691
-			return $router;
692
-		});
693
-		$this->registerAlias(IRouter::class, Router::class);
694
-
695
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
696
-			$config = $c->get(\OCP\IConfig::class);
697
-			if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
698
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
699
-					$c->get(AllConfig::class),
700
-					$this->get(ICacheFactory::class),
701
-					new \OC\AppFramework\Utility\TimeFactory()
702
-				);
703
-			} else {
704
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
705
-					$c->get(AllConfig::class),
706
-					$c->get(IDBConnection::class),
707
-					new \OC\AppFramework\Utility\TimeFactory()
708
-				);
709
-			}
710
-
711
-			return $backend;
712
-		});
713
-
714
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
715
-		$this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
716
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
717
-
718
-		$this->registerAlias(ICrypto::class, Crypto::class);
719
-
720
-		$this->registerAlias(IHasher::class, Hasher::class);
721
-
722
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
723
-
724
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
725
-		$this->registerService(Connection::class, function (Server $c) {
726
-			$systemConfig = $c->get(SystemConfig::class);
727
-			$factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
728
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
729
-			if (!$factory->isValidType($type)) {
730
-				throw new \OC\DatabaseException('Invalid database type');
731
-			}
732
-			$connection = $factory->getConnection($type, []);
733
-			return $connection;
734
-		});
735
-
736
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
737
-		$this->registerAlias(IClientService::class, ClientService::class);
738
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
739
-			return new NegativeDnsCache(
740
-				$c->get(ICacheFactory::class),
741
-			);
742
-		});
743
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
744
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
745
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
746
-		});
747
-
748
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
749
-			$queryLogger = new QueryLogger();
750
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
751
-				// In debug mode, module is being activated by default
752
-				$queryLogger->activate();
753
-			}
754
-			return $queryLogger;
755
-		});
756
-
757
-		$this->registerAlias(ITempManager::class, TempManager::class);
758
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
759
-
760
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
761
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
762
-
763
-			return new DateTimeFormatter(
764
-				$c->get(IDateTimeZone::class)->getTimeZone(),
765
-				$c->getL10N('lib', $language)
766
-			);
767
-		});
768
-
769
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
770
-			$mountCache = $c->get(UserMountCache::class);
771
-			$listener = new UserMountCacheListener($mountCache);
772
-			$listener->listen($c->get(IUserManager::class));
773
-			return $mountCache;
774
-		});
775
-
776
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
777
-			$loader = $c->get(IStorageFactory::class);
778
-			$mountCache = $c->get(IUserMountCache::class);
779
-			$eventLogger = $c->get(IEventLogger::class);
780
-			$manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
781
-
782
-			// builtin providers
783
-
784
-			$config = $c->get(\OCP\IConfig::class);
785
-			$logger = $c->get(LoggerInterface::class);
786
-			$objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
787
-			$manager->registerProvider(new CacheMountProvider($config));
788
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
789
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
790
-			$manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
791
-			$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
792
-
793
-			return $manager;
794
-		});
795
-
796
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
797
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
798
-			if ($busClass) {
799
-				[$app, $class] = explode('::', $busClass, 2);
800
-				if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
801
-					$c->get(IAppManager::class)->loadApp($app);
802
-					return $c->get($class);
803
-				} else {
804
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
805
-				}
806
-			} else {
807
-				$jobList = $c->get(IJobList::class);
808
-				return new CronBus($jobList);
809
-			}
810
-		});
811
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
812
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
813
-		$this->registerAlias(IThrottler::class, Throttler::class);
814
-
815
-		$this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
816
-			$config = $c->get(\OCP\IConfig::class);
817
-			if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
818
-				&& ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
819
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
820
-			} else {
821
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
822
-			}
823
-
824
-			return $backend;
825
-		});
826
-
827
-		$this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
828
-		$this->registerService(Checker::class, function (ContainerInterface $c) {
829
-			// IConfig requires a working database. This code
830
-			// might however be called when Nextcloud is not yet setup.
831
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
832
-				$config = $c->get(\OCP\IConfig::class);
833
-				$appConfig = $c->get(\OCP\IAppConfig::class);
834
-			} else {
835
-				$config = null;
836
-				$appConfig = null;
837
-			}
838
-
839
-			return new Checker(
840
-				$c->get(ServerVersion::class),
841
-				$c->get(EnvironmentHelper::class),
842
-				new FileAccessHelper(),
843
-				$config,
844
-				$appConfig,
845
-				$c->get(ICacheFactory::class),
846
-				$c->get(IAppManager::class),
847
-				$c->get(IMimeTypeDetector::class)
848
-			);
849
-		});
850
-		$this->registerService(Request::class, function (ContainerInterface $c) {
851
-			if (isset($this['urlParams'])) {
852
-				$urlParams = $this['urlParams'];
853
-			} else {
854
-				$urlParams = [];
855
-			}
856
-
857
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
858
-				&& in_array('fakeinput', stream_get_wrappers())
859
-			) {
860
-				$stream = 'fakeinput://data';
861
-			} else {
862
-				$stream = 'php://input';
863
-			}
864
-
865
-			return new Request(
866
-				[
867
-					'get' => $_GET,
868
-					'post' => $_POST,
869
-					'files' => $_FILES,
870
-					'server' => $_SERVER,
871
-					'env' => $_ENV,
872
-					'cookies' => $_COOKIE,
873
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
-						? $_SERVER['REQUEST_METHOD']
875
-						: '',
876
-					'urlParams' => $urlParams,
877
-				],
878
-				$this->get(IRequestId::class),
879
-				$this->get(\OCP\IConfig::class),
880
-				$this->get(CsrfTokenManager::class),
881
-				$stream
882
-			);
883
-		});
884
-		$this->registerAlias(\OCP\IRequest::class, Request::class);
885
-
886
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
887
-			return new RequestId(
888
-				$_SERVER['UNIQUE_ID'] ?? '',
889
-				$this->get(ISecureRandom::class)
890
-			);
891
-		});
892
-
893
-		/** @since 32.0.0 */
894
-		$this->registerAlias(IEmailValidator::class, EmailValidator::class);
895
-
896
-		$this->registerService(IMailer::class, function (Server $c) {
897
-			return new Mailer(
898
-				$c->get(\OCP\IConfig::class),
899
-				$c->get(LoggerInterface::class),
900
-				$c->get(Defaults::class),
901
-				$c->get(IURLGenerator::class),
902
-				$c->getL10N('lib'),
903
-				$c->get(IEventDispatcher::class),
904
-				$c->get(IFactory::class),
905
-				$c->get(IEmailValidator::class),
906
-			);
907
-		});
908
-
909
-		/** @since 30.0.0 */
910
-		$this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
911
-
912
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
913
-			$config = $c->get(\OCP\IConfig::class);
914
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
915
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
916
-				return new NullLDAPProviderFactory($this);
917
-			}
918
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
919
-			return new $factoryClass($this);
920
-		});
921
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
922
-			$factory = $c->get(ILDAPProviderFactory::class);
923
-			return $factory->getLDAPProvider();
924
-		});
925
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
926
-			$ini = $c->get(IniGetWrapper::class);
927
-			$config = $c->get(\OCP\IConfig::class);
928
-			$ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
929
-			if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
930
-				/** @var \OC\Memcache\Factory $memcacheFactory */
931
-				$memcacheFactory = $c->get(ICacheFactory::class);
932
-				$memcache = $memcacheFactory->createLocking('lock');
933
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
934
-					$timeFactory = $c->get(ITimeFactory::class);
935
-					return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
936
-				}
937
-				return new DBLockingProvider(
938
-					$c->get(IDBConnection::class),
939
-					new TimeFactory(),
940
-					$ttl,
941
-					!\OC::$CLI
942
-				);
943
-			}
944
-			return new NoopLockingProvider();
945
-		});
946
-
947
-		$this->registerService(ILockManager::class, function (Server $c): LockManager {
948
-			return new LockManager();
949
-		});
950
-
951
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
952
-		$this->registerService(SetupManager::class, function ($c) {
953
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
954
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
955
-		});
956
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
957
-
958
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
959
-			return new \OC\Files\Type\Detection(
960
-				$c->get(IURLGenerator::class),
961
-				$c->get(LoggerInterface::class),
962
-				\OC::$configDir,
963
-				\OC::$SERVERROOT . '/resources/config/'
964
-			);
965
-		});
966
-
967
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
968
-		$this->registerService(BundleFetcher::class, function () {
969
-			return new BundleFetcher($this->getL10N('lib'));
970
-		});
971
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
972
-
973
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
974
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
975
-			$manager->registerCapability(function () use ($c) {
976
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
977
-			});
978
-			$manager->registerCapability(function () use ($c) {
979
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
980
-			});
981
-			return $manager;
982
-		});
983
-
984
-		$this->registerService(ICommentsManager::class, function (Server $c) {
985
-			$config = $c->get(\OCP\IConfig::class);
986
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
987
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
988
-			$factory = new $factoryClass($this);
989
-			$manager = $factory->getManager();
990
-
991
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
992
-				$manager = $c->get(IUserManager::class);
993
-				$userDisplayName = $manager->getDisplayName($id);
994
-				if ($userDisplayName === null) {
995
-					$l = $c->get(IFactory::class)->get('core');
996
-					return $l->t('Unknown account');
997
-				}
998
-				return $userDisplayName;
999
-			});
1000
-
1001
-			return $manager;
1002
-		});
1003
-
1004
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1005
-		$this->registerService('ThemingDefaults', function (Server $c) {
1006
-			try {
1007
-				$classExists = class_exists('OCA\Theming\ThemingDefaults');
1008
-			} catch (\OCP\AutoloadNotAllowedException $e) {
1009
-				// App disabled or in maintenance mode
1010
-				$classExists = false;
1011
-			}
1012
-
1013
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1014
-				$backgroundService = new BackgroundService(
1015
-					$c->get(IRootFolder::class),
1016
-					$c->getAppDataDir('theming'),
1017
-					$c->get(IAppConfig::class),
1018
-					$c->get(\OCP\IConfig::class),
1019
-					$c->get(ISession::class)->get('user_id'),
1020
-				);
1021
-				$imageManager = new ImageManager(
1022
-					$c->get(\OCP\IConfig::class),
1023
-					$c->getAppDataDir('theming'),
1024
-					$c->get(IURLGenerator::class),
1025
-					$c->get(ICacheFactory::class),
1026
-					$c->get(LoggerInterface::class),
1027
-					$c->get(ITempManager::class),
1028
-					$backgroundService,
1029
-				);
1030
-				return new ThemingDefaults(
1031
-					$c->get(\OCP\IConfig::class),
1032
-					$c->get(\OCP\IAppConfig::class),
1033
-					$c->getL10N('theming'),
1034
-					$c->get(IUserSession::class),
1035
-					$c->get(IURLGenerator::class),
1036
-					$c->get(ICacheFactory::class),
1037
-					new Util($c->get(ServerVersion::class), $c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1038
-					$imageManager,
1039
-					$c->get(IAppManager::class),
1040
-					$c->get(INavigationManager::class),
1041
-					$backgroundService,
1042
-				);
1043
-			}
1044
-			return new \OC_Defaults();
1045
-		});
1046
-		$this->registerService(JSCombiner::class, function (Server $c) {
1047
-			return new JSCombiner(
1048
-				$c->getAppDataDir('js'),
1049
-				$c->get(IURLGenerator::class),
1050
-				$this->get(ICacheFactory::class),
1051
-				$c->get(\OCP\IConfig::class),
1052
-				$c->get(LoggerInterface::class)
1053
-			);
1054
-		});
1055
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1056
-
1057
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1058
-			// FIXME: Instantiated here due to cyclic dependency
1059
-			$request = new Request(
1060
-				[
1061
-					'get' => $_GET,
1062
-					'post' => $_POST,
1063
-					'files' => $_FILES,
1064
-					'server' => $_SERVER,
1065
-					'env' => $_ENV,
1066
-					'cookies' => $_COOKIE,
1067
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1068
-						? $_SERVER['REQUEST_METHOD']
1069
-						: null,
1070
-				],
1071
-				$c->get(IRequestId::class),
1072
-				$c->get(\OCP\IConfig::class)
1073
-			);
1074
-
1075
-			return new CryptoWrapper(
1076
-				$c->get(ICrypto::class),
1077
-				$c->get(ISecureRandom::class),
1078
-				$request
1079
-			);
1080
-		});
1081
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1082
-			return new SessionStorage($c->get(ISession::class));
1083
-		});
1084
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1085
-
1086
-		$this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1087
-			$config = $c->get(\OCP\IConfig::class);
1088
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1089
-			/** @var \OCP\Share\IProviderFactory $factory */
1090
-			return $c->get($factoryClass);
1091
-		});
1092
-
1093
-		$this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1094
-
1095
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1096
-			$instance = new Collaboration\Collaborators\Search($c);
1097
-
1098
-			// register default plugins
1099
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1100
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1101
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1102
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1103
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1104
-
1105
-			return $instance;
1106
-		});
1107
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1108
-
1109
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1110
-
1111
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1112
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1113
-
1114
-		$this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1115
-		$this->registerAlias(ITeamManager::class, TeamManager::class);
1116
-
1117
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1118
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1119
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1120
-			return new \OC\Files\AppData\Factory(
1121
-				$c->get(IRootFolder::class),
1122
-				$c->get(SystemConfig::class)
1123
-			);
1124
-		});
1125
-
1126
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1127
-			return new LockdownManager(function () use ($c) {
1128
-				return $c->get(ISession::class);
1129
-			});
1130
-		});
1131
-
1132
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1133
-			return new DiscoveryService(
1134
-				$c->get(ICacheFactory::class),
1135
-				$c->get(IClientService::class)
1136
-			);
1137
-		});
1138
-		$this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1139
-
1140
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1141
-			return new CloudIdManager(
1142
-				$c->get(ICacheFactory::class),
1143
-				$c->get(IEventDispatcher::class),
1144
-				$c->get(\OCP\Contacts\IManager::class),
1145
-				$c->get(IURLGenerator::class),
1146
-				$c->get(IUserManager::class),
1147
-			);
1148
-		});
251
+    /** @var string */
252
+    private $webRoot;
253
+
254
+    /**
255
+     * @param string $webRoot
256
+     * @param \OC\Config $config
257
+     */
258
+    public function __construct($webRoot, \OC\Config $config) {
259
+        parent::__construct();
260
+        $this->webRoot = $webRoot;
261
+
262
+        // To find out if we are running from CLI or not
263
+        $this->registerParameter('isCLI', \OC::$CLI);
264
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
265
+
266
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
267
+            return $c;
268
+        });
269
+        $this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
270
+
271
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
272
+
273
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
274
+
275
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
276
+
277
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
278
+
279
+        $this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
280
+
281
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
282
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
283
+        $this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
284
+
285
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
286
+
287
+        $this->registerService(View::class, function (Server $c) {
288
+            return new View();
289
+        }, false);
290
+
291
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
292
+            return new PreviewManager(
293
+                $c->get(\OCP\IConfig::class),
294
+                $c->get(IRootFolder::class),
295
+                new \OC\Preview\Storage\Root(
296
+                    $c->get(IRootFolder::class),
297
+                    $c->get(SystemConfig::class)
298
+                ),
299
+                $c->get(IEventDispatcher::class),
300
+                $c->get(GeneratorHelper::class),
301
+                $c->get(ISession::class)->get('user_id'),
302
+                $c->get(Coordinator::class),
303
+                $c->get(IServerContainer::class),
304
+                $c->get(IBinaryFinder::class),
305
+                $c->get(IMagickSupport::class)
306
+            );
307
+        });
308
+        $this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
309
+
310
+        $this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
311
+            return new \OC\Preview\Watcher(
312
+                new \OC\Preview\Storage\Root(
313
+                    $c->get(IRootFolder::class),
314
+                    $c->get(SystemConfig::class)
315
+                )
316
+            );
317
+        });
318
+
319
+        $this->registerService(IProfiler::class, function (Server $c) {
320
+            return new Profiler($c->get(SystemConfig::class));
321
+        });
322
+
323
+        $this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
324
+            $view = new View();
325
+            $util = new Encryption\Util(
326
+                $view,
327
+                $c->get(IUserManager::class),
328
+                $c->get(IGroupManager::class),
329
+                $c->get(\OCP\IConfig::class)
330
+            );
331
+            return new Encryption\Manager(
332
+                $c->get(\OCP\IConfig::class),
333
+                $c->get(LoggerInterface::class),
334
+                $c->getL10N('core'),
335
+                new View(),
336
+                $util,
337
+                new ArrayCache()
338
+            );
339
+        });
340
+        $this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
341
+
342
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
343
+            $util = new Encryption\Util(
344
+                new View(),
345
+                $c->get(IUserManager::class),
346
+                $c->get(IGroupManager::class),
347
+                $c->get(\OCP\IConfig::class)
348
+            );
349
+            return new Encryption\File(
350
+                $util,
351
+                $c->get(IRootFolder::class),
352
+                $c->get(\OCP\Share\IManager::class)
353
+            );
354
+        });
355
+
356
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
357
+            $view = new View();
358
+            $util = new Encryption\Util(
359
+                $view,
360
+                $c->get(IUserManager::class),
361
+                $c->get(IGroupManager::class),
362
+                $c->get(\OCP\IConfig::class)
363
+            );
364
+
365
+            return new Encryption\Keys\Storage(
366
+                $view,
367
+                $util,
368
+                $c->get(ICrypto::class),
369
+                $c->get(\OCP\IConfig::class)
370
+            );
371
+        });
372
+
373
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
374
+
375
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
376
+            /** @var \OCP\IConfig $config */
377
+            $config = $c->get(\OCP\IConfig::class);
378
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
379
+            return new $factoryClass($this);
380
+        });
381
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
382
+            return $c->get('SystemTagManagerFactory')->getManager();
383
+        });
384
+        /** @deprecated 19.0.0 */
385
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
386
+
387
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
388
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
389
+        });
390
+        $this->registerAlias(IFileAccess::class, FileAccess::class);
391
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
392
+            $manager = \OC\Files\Filesystem::getMountManager();
393
+            $view = new View();
394
+            /** @var IUserSession $userSession */
395
+            $userSession = $c->get(IUserSession::class);
396
+            $root = new Root(
397
+                $manager,
398
+                $view,
399
+                $userSession->getUser(),
400
+                $c->get(IUserMountCache::class),
401
+                $this->get(LoggerInterface::class),
402
+                $this->get(IUserManager::class),
403
+                $this->get(IEventDispatcher::class),
404
+                $this->get(ICacheFactory::class),
405
+            );
406
+
407
+            $previewConnector = new \OC\Preview\WatcherConnector(
408
+                $root,
409
+                $c->get(SystemConfig::class),
410
+                $this->get(IEventDispatcher::class)
411
+            );
412
+            $previewConnector->connectWatcher();
413
+
414
+            return $root;
415
+        });
416
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
417
+            return new HookConnector(
418
+                $c->get(IRootFolder::class),
419
+                new View(),
420
+                $c->get(IEventDispatcher::class),
421
+                $c->get(LoggerInterface::class)
422
+            );
423
+        });
424
+
425
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
426
+            return new LazyRoot(function () use ($c) {
427
+                return $c->get('RootFolder');
428
+            });
429
+        });
430
+
431
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
432
+
433
+        $this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
434
+            return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
435
+        });
436
+
437
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
438
+            $groupManager = new \OC\Group\Manager(
439
+                $this->get(IUserManager::class),
440
+                $this->get(IEventDispatcher::class),
441
+                $this->get(LoggerInterface::class),
442
+                $this->get(ICacheFactory::class),
443
+                $this->get(IRemoteAddress::class),
444
+            );
445
+            return $groupManager;
446
+        });
447
+
448
+        $this->registerService(Store::class, function (ContainerInterface $c) {
449
+            $session = $c->get(ISession::class);
450
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
451
+                $tokenProvider = $c->get(IProvider::class);
452
+            } else {
453
+                $tokenProvider = null;
454
+            }
455
+            $logger = $c->get(LoggerInterface::class);
456
+            $crypto = $c->get(ICrypto::class);
457
+            return new Store($session, $logger, $crypto, $tokenProvider);
458
+        });
459
+        $this->registerAlias(IStore::class, Store::class);
460
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
461
+        $this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
462
+
463
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
464
+            $manager = $c->get(IUserManager::class);
465
+            $session = new \OC\Session\Memory();
466
+            $timeFactory = new TimeFactory();
467
+            // Token providers might require a working database. This code
468
+            // might however be called when Nextcloud is not yet setup.
469
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
470
+                $provider = $c->get(IProvider::class);
471
+            } else {
472
+                $provider = null;
473
+            }
474
+
475
+            $userSession = new \OC\User\Session(
476
+                $manager,
477
+                $session,
478
+                $timeFactory,
479
+                $provider,
480
+                $c->get(\OCP\IConfig::class),
481
+                $c->get(ISecureRandom::class),
482
+                $c->get('LockdownManager'),
483
+                $c->get(LoggerInterface::class),
484
+                $c->get(IEventDispatcher::class),
485
+            );
486
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
487
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
488
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
489
+            });
490
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
491
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
492
+                /** @var \OC\User\User $user */
493
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
494
+            });
495
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
496
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
497
+                /** @var \OC\User\User $user */
498
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
499
+            });
500
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
501
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
502
+                /** @var \OC\User\User $user */
503
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
504
+            });
505
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
506
+                /** @var \OC\User\User $user */
507
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
508
+            });
509
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
510
+                /** @var \OC\User\User $user */
511
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
512
+            });
513
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
514
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
515
+
516
+                /** @var IEventDispatcher $dispatcher */
517
+                $dispatcher = $this->get(IEventDispatcher::class);
518
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
519
+            });
520
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
521
+                /** @var \OC\User\User $user */
522
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
523
+
524
+                /** @var IEventDispatcher $dispatcher */
525
+                $dispatcher = $this->get(IEventDispatcher::class);
526
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
527
+            });
528
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
529
+                /** @var IEventDispatcher $dispatcher */
530
+                $dispatcher = $this->get(IEventDispatcher::class);
531
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
532
+            });
533
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
534
+                /** @var \OC\User\User $user */
535
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
536
+
537
+                /** @var IEventDispatcher $dispatcher */
538
+                $dispatcher = $this->get(IEventDispatcher::class);
539
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
540
+            });
541
+            $userSession->listen('\OC\User', 'logout', function ($user) {
542
+                \OC_Hook::emit('OC_User', 'logout', []);
543
+
544
+                /** @var IEventDispatcher $dispatcher */
545
+                $dispatcher = $this->get(IEventDispatcher::class);
546
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
547
+            });
548
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
549
+                /** @var IEventDispatcher $dispatcher */
550
+                $dispatcher = $this->get(IEventDispatcher::class);
551
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
552
+            });
553
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
554
+                /** @var \OC\User\User $user */
555
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
556
+            });
557
+            return $userSession;
558
+        });
559
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
560
+
561
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
562
+
563
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
564
+
565
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
566
+
567
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
568
+            return new \OC\SystemConfig($config);
569
+        });
570
+
571
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
572
+        $this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
573
+        $this->registerAlias(IAppManager::class, AppManager::class);
574
+
575
+        $this->registerService(IFactory::class, function (Server $c) {
576
+            return new \OC\L10N\Factory(
577
+                $c->get(\OCP\IConfig::class),
578
+                $c->getRequest(),
579
+                $c->get(IUserSession::class),
580
+                $c->get(ICacheFactory::class),
581
+                \OC::$SERVERROOT,
582
+                $c->get(IAppManager::class),
583
+            );
584
+        });
585
+
586
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
587
+
588
+        $this->registerAlias(ICache::class, Cache\File::class);
589
+        $this->registerService(Factory::class, function (Server $c) {
590
+            $profiler = $c->get(IProfiler::class);
591
+            $logger = $c->get(LoggerInterface::class);
592
+            $serverVersion = $c->get(ServerVersion::class);
593
+            /** @var SystemConfig $config */
594
+            $config = $c->get(SystemConfig::class);
595
+            if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
596
+                return new \OC\Memcache\Factory(
597
+                    $logger,
598
+                    $profiler,
599
+                    $serverVersion,
600
+                    ArrayCache::class,
601
+                    ArrayCache::class,
602
+                    ArrayCache::class
603
+                );
604
+            }
605
+
606
+            return new \OC\Memcache\Factory(
607
+                $logger,
608
+                $profiler,
609
+                $serverVersion,
610
+                /** @psalm-taint-escape callable */
611
+                $config->getValue('memcache.local', null),
612
+                /** @psalm-taint-escape callable */
613
+                $config->getValue('memcache.distributed', null),
614
+                /** @psalm-taint-escape callable */
615
+                $config->getValue('memcache.locking', null),
616
+                /** @psalm-taint-escape callable */
617
+                $config->getValue('redis_log_file')
618
+            );
619
+        });
620
+        $this->registerAlias(ICacheFactory::class, Factory::class);
621
+
622
+        $this->registerService('RedisFactory', function (Server $c) {
623
+            $systemConfig = $c->get(SystemConfig::class);
624
+            return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
625
+        });
626
+
627
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
628
+            $l10n = $this->get(IFactory::class)->get('lib');
629
+            return new \OC\Activity\Manager(
630
+                $c->getRequest(),
631
+                $c->get(IUserSession::class),
632
+                $c->get(\OCP\IConfig::class),
633
+                $c->get(IValidator::class),
634
+                $c->get(IRichTextFormatter::class),
635
+                $l10n,
636
+                $c->get(ITimeFactory::class),
637
+            );
638
+        });
639
+
640
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
641
+            return new \OC\Activity\EventMerger(
642
+                $c->getL10N('lib')
643
+            );
644
+        });
645
+        $this->registerAlias(IValidator::class, Validator::class);
646
+
647
+        $this->registerService(AvatarManager::class, function (Server $c) {
648
+            return new AvatarManager(
649
+                $c->get(IUserSession::class),
650
+                $c->get(\OC\User\Manager::class),
651
+                $c->getAppDataDir('avatar'),
652
+                $c->getL10N('lib'),
653
+                $c->get(LoggerInterface::class),
654
+                $c->get(\OCP\IConfig::class),
655
+                $c->get(IAccountManager::class),
656
+                $c->get(KnownUserService::class)
657
+            );
658
+        });
659
+
660
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
661
+
662
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
663
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
664
+        $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
665
+
666
+        /** Only used by the PsrLoggerAdapter should not be used by apps */
667
+        $this->registerService(\OC\Log::class, function (Server $c) {
668
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
669
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
670
+            $logger = $factory->get($logType);
671
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
672
+
673
+            return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
674
+        });
675
+        // PSR-3 logger
676
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
677
+
678
+        $this->registerService(ILogFactory::class, function (Server $c) {
679
+            return new LogFactory($c, $this->get(SystemConfig::class));
680
+        });
681
+
682
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
683
+
684
+        $this->registerService(Router::class, function (Server $c) {
685
+            $cacheFactory = $c->get(ICacheFactory::class);
686
+            if ($cacheFactory->isLocalCacheAvailable()) {
687
+                $router = $c->resolve(CachingRouter::class);
688
+            } else {
689
+                $router = $c->resolve(Router::class);
690
+            }
691
+            return $router;
692
+        });
693
+        $this->registerAlias(IRouter::class, Router::class);
694
+
695
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
696
+            $config = $c->get(\OCP\IConfig::class);
697
+            if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
698
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
699
+                    $c->get(AllConfig::class),
700
+                    $this->get(ICacheFactory::class),
701
+                    new \OC\AppFramework\Utility\TimeFactory()
702
+                );
703
+            } else {
704
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
705
+                    $c->get(AllConfig::class),
706
+                    $c->get(IDBConnection::class),
707
+                    new \OC\AppFramework\Utility\TimeFactory()
708
+                );
709
+            }
710
+
711
+            return $backend;
712
+        });
713
+
714
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
715
+        $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
716
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
717
+
718
+        $this->registerAlias(ICrypto::class, Crypto::class);
719
+
720
+        $this->registerAlias(IHasher::class, Hasher::class);
721
+
722
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
723
+
724
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
725
+        $this->registerService(Connection::class, function (Server $c) {
726
+            $systemConfig = $c->get(SystemConfig::class);
727
+            $factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
728
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
729
+            if (!$factory->isValidType($type)) {
730
+                throw new \OC\DatabaseException('Invalid database type');
731
+            }
732
+            $connection = $factory->getConnection($type, []);
733
+            return $connection;
734
+        });
735
+
736
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
737
+        $this->registerAlias(IClientService::class, ClientService::class);
738
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
739
+            return new NegativeDnsCache(
740
+                $c->get(ICacheFactory::class),
741
+            );
742
+        });
743
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
744
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
745
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
746
+        });
747
+
748
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
749
+            $queryLogger = new QueryLogger();
750
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
751
+                // In debug mode, module is being activated by default
752
+                $queryLogger->activate();
753
+            }
754
+            return $queryLogger;
755
+        });
756
+
757
+        $this->registerAlias(ITempManager::class, TempManager::class);
758
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
759
+
760
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
761
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
762
+
763
+            return new DateTimeFormatter(
764
+                $c->get(IDateTimeZone::class)->getTimeZone(),
765
+                $c->getL10N('lib', $language)
766
+            );
767
+        });
768
+
769
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
770
+            $mountCache = $c->get(UserMountCache::class);
771
+            $listener = new UserMountCacheListener($mountCache);
772
+            $listener->listen($c->get(IUserManager::class));
773
+            return $mountCache;
774
+        });
775
+
776
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
777
+            $loader = $c->get(IStorageFactory::class);
778
+            $mountCache = $c->get(IUserMountCache::class);
779
+            $eventLogger = $c->get(IEventLogger::class);
780
+            $manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
781
+
782
+            // builtin providers
783
+
784
+            $config = $c->get(\OCP\IConfig::class);
785
+            $logger = $c->get(LoggerInterface::class);
786
+            $objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
787
+            $manager->registerProvider(new CacheMountProvider($config));
788
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
789
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
790
+            $manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
791
+            $manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
792
+
793
+            return $manager;
794
+        });
795
+
796
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
797
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
798
+            if ($busClass) {
799
+                [$app, $class] = explode('::', $busClass, 2);
800
+                if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
801
+                    $c->get(IAppManager::class)->loadApp($app);
802
+                    return $c->get($class);
803
+                } else {
804
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
805
+                }
806
+            } else {
807
+                $jobList = $c->get(IJobList::class);
808
+                return new CronBus($jobList);
809
+            }
810
+        });
811
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
812
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
813
+        $this->registerAlias(IThrottler::class, Throttler::class);
814
+
815
+        $this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
816
+            $config = $c->get(\OCP\IConfig::class);
817
+            if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
818
+                && ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
819
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
820
+            } else {
821
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
822
+            }
823
+
824
+            return $backend;
825
+        });
826
+
827
+        $this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
828
+        $this->registerService(Checker::class, function (ContainerInterface $c) {
829
+            // IConfig requires a working database. This code
830
+            // might however be called when Nextcloud is not yet setup.
831
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
832
+                $config = $c->get(\OCP\IConfig::class);
833
+                $appConfig = $c->get(\OCP\IAppConfig::class);
834
+            } else {
835
+                $config = null;
836
+                $appConfig = null;
837
+            }
838
+
839
+            return new Checker(
840
+                $c->get(ServerVersion::class),
841
+                $c->get(EnvironmentHelper::class),
842
+                new FileAccessHelper(),
843
+                $config,
844
+                $appConfig,
845
+                $c->get(ICacheFactory::class),
846
+                $c->get(IAppManager::class),
847
+                $c->get(IMimeTypeDetector::class)
848
+            );
849
+        });
850
+        $this->registerService(Request::class, function (ContainerInterface $c) {
851
+            if (isset($this['urlParams'])) {
852
+                $urlParams = $this['urlParams'];
853
+            } else {
854
+                $urlParams = [];
855
+            }
856
+
857
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
858
+                && in_array('fakeinput', stream_get_wrappers())
859
+            ) {
860
+                $stream = 'fakeinput://data';
861
+            } else {
862
+                $stream = 'php://input';
863
+            }
864
+
865
+            return new Request(
866
+                [
867
+                    'get' => $_GET,
868
+                    'post' => $_POST,
869
+                    'files' => $_FILES,
870
+                    'server' => $_SERVER,
871
+                    'env' => $_ENV,
872
+                    'cookies' => $_COOKIE,
873
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
+                        ? $_SERVER['REQUEST_METHOD']
875
+                        : '',
876
+                    'urlParams' => $urlParams,
877
+                ],
878
+                $this->get(IRequestId::class),
879
+                $this->get(\OCP\IConfig::class),
880
+                $this->get(CsrfTokenManager::class),
881
+                $stream
882
+            );
883
+        });
884
+        $this->registerAlias(\OCP\IRequest::class, Request::class);
885
+
886
+        $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
887
+            return new RequestId(
888
+                $_SERVER['UNIQUE_ID'] ?? '',
889
+                $this->get(ISecureRandom::class)
890
+            );
891
+        });
892
+
893
+        /** @since 32.0.0 */
894
+        $this->registerAlias(IEmailValidator::class, EmailValidator::class);
895
+
896
+        $this->registerService(IMailer::class, function (Server $c) {
897
+            return new Mailer(
898
+                $c->get(\OCP\IConfig::class),
899
+                $c->get(LoggerInterface::class),
900
+                $c->get(Defaults::class),
901
+                $c->get(IURLGenerator::class),
902
+                $c->getL10N('lib'),
903
+                $c->get(IEventDispatcher::class),
904
+                $c->get(IFactory::class),
905
+                $c->get(IEmailValidator::class),
906
+            );
907
+        });
908
+
909
+        /** @since 30.0.0 */
910
+        $this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
911
+
912
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
913
+            $config = $c->get(\OCP\IConfig::class);
914
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
915
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
916
+                return new NullLDAPProviderFactory($this);
917
+            }
918
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
919
+            return new $factoryClass($this);
920
+        });
921
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
922
+            $factory = $c->get(ILDAPProviderFactory::class);
923
+            return $factory->getLDAPProvider();
924
+        });
925
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
926
+            $ini = $c->get(IniGetWrapper::class);
927
+            $config = $c->get(\OCP\IConfig::class);
928
+            $ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
929
+            if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
930
+                /** @var \OC\Memcache\Factory $memcacheFactory */
931
+                $memcacheFactory = $c->get(ICacheFactory::class);
932
+                $memcache = $memcacheFactory->createLocking('lock');
933
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
934
+                    $timeFactory = $c->get(ITimeFactory::class);
935
+                    return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
936
+                }
937
+                return new DBLockingProvider(
938
+                    $c->get(IDBConnection::class),
939
+                    new TimeFactory(),
940
+                    $ttl,
941
+                    !\OC::$CLI
942
+                );
943
+            }
944
+            return new NoopLockingProvider();
945
+        });
946
+
947
+        $this->registerService(ILockManager::class, function (Server $c): LockManager {
948
+            return new LockManager();
949
+        });
950
+
951
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
952
+        $this->registerService(SetupManager::class, function ($c) {
953
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
954
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
955
+        });
956
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
957
+
958
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
959
+            return new \OC\Files\Type\Detection(
960
+                $c->get(IURLGenerator::class),
961
+                $c->get(LoggerInterface::class),
962
+                \OC::$configDir,
963
+                \OC::$SERVERROOT . '/resources/config/'
964
+            );
965
+        });
966
+
967
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
968
+        $this->registerService(BundleFetcher::class, function () {
969
+            return new BundleFetcher($this->getL10N('lib'));
970
+        });
971
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
972
+
973
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
974
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
975
+            $manager->registerCapability(function () use ($c) {
976
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
977
+            });
978
+            $manager->registerCapability(function () use ($c) {
979
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
980
+            });
981
+            return $manager;
982
+        });
983
+
984
+        $this->registerService(ICommentsManager::class, function (Server $c) {
985
+            $config = $c->get(\OCP\IConfig::class);
986
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
987
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
988
+            $factory = new $factoryClass($this);
989
+            $manager = $factory->getManager();
990
+
991
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
992
+                $manager = $c->get(IUserManager::class);
993
+                $userDisplayName = $manager->getDisplayName($id);
994
+                if ($userDisplayName === null) {
995
+                    $l = $c->get(IFactory::class)->get('core');
996
+                    return $l->t('Unknown account');
997
+                }
998
+                return $userDisplayName;
999
+            });
1000
+
1001
+            return $manager;
1002
+        });
1003
+
1004
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1005
+        $this->registerService('ThemingDefaults', function (Server $c) {
1006
+            try {
1007
+                $classExists = class_exists('OCA\Theming\ThemingDefaults');
1008
+            } catch (\OCP\AutoloadNotAllowedException $e) {
1009
+                // App disabled or in maintenance mode
1010
+                $classExists = false;
1011
+            }
1012
+
1013
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1014
+                $backgroundService = new BackgroundService(
1015
+                    $c->get(IRootFolder::class),
1016
+                    $c->getAppDataDir('theming'),
1017
+                    $c->get(IAppConfig::class),
1018
+                    $c->get(\OCP\IConfig::class),
1019
+                    $c->get(ISession::class)->get('user_id'),
1020
+                );
1021
+                $imageManager = new ImageManager(
1022
+                    $c->get(\OCP\IConfig::class),
1023
+                    $c->getAppDataDir('theming'),
1024
+                    $c->get(IURLGenerator::class),
1025
+                    $c->get(ICacheFactory::class),
1026
+                    $c->get(LoggerInterface::class),
1027
+                    $c->get(ITempManager::class),
1028
+                    $backgroundService,
1029
+                );
1030
+                return new ThemingDefaults(
1031
+                    $c->get(\OCP\IConfig::class),
1032
+                    $c->get(\OCP\IAppConfig::class),
1033
+                    $c->getL10N('theming'),
1034
+                    $c->get(IUserSession::class),
1035
+                    $c->get(IURLGenerator::class),
1036
+                    $c->get(ICacheFactory::class),
1037
+                    new Util($c->get(ServerVersion::class), $c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1038
+                    $imageManager,
1039
+                    $c->get(IAppManager::class),
1040
+                    $c->get(INavigationManager::class),
1041
+                    $backgroundService,
1042
+                );
1043
+            }
1044
+            return new \OC_Defaults();
1045
+        });
1046
+        $this->registerService(JSCombiner::class, function (Server $c) {
1047
+            return new JSCombiner(
1048
+                $c->getAppDataDir('js'),
1049
+                $c->get(IURLGenerator::class),
1050
+                $this->get(ICacheFactory::class),
1051
+                $c->get(\OCP\IConfig::class),
1052
+                $c->get(LoggerInterface::class)
1053
+            );
1054
+        });
1055
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1056
+
1057
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1058
+            // FIXME: Instantiated here due to cyclic dependency
1059
+            $request = new Request(
1060
+                [
1061
+                    'get' => $_GET,
1062
+                    'post' => $_POST,
1063
+                    'files' => $_FILES,
1064
+                    'server' => $_SERVER,
1065
+                    'env' => $_ENV,
1066
+                    'cookies' => $_COOKIE,
1067
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1068
+                        ? $_SERVER['REQUEST_METHOD']
1069
+                        : null,
1070
+                ],
1071
+                $c->get(IRequestId::class),
1072
+                $c->get(\OCP\IConfig::class)
1073
+            );
1074
+
1075
+            return new CryptoWrapper(
1076
+                $c->get(ICrypto::class),
1077
+                $c->get(ISecureRandom::class),
1078
+                $request
1079
+            );
1080
+        });
1081
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1082
+            return new SessionStorage($c->get(ISession::class));
1083
+        });
1084
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1085
+
1086
+        $this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1087
+            $config = $c->get(\OCP\IConfig::class);
1088
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1089
+            /** @var \OCP\Share\IProviderFactory $factory */
1090
+            return $c->get($factoryClass);
1091
+        });
1092
+
1093
+        $this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1094
+
1095
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1096
+            $instance = new Collaboration\Collaborators\Search($c);
1097
+
1098
+            // register default plugins
1099
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1100
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1101
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1102
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1103
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1104
+
1105
+            return $instance;
1106
+        });
1107
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1108
+
1109
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1110
+
1111
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1112
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1113
+
1114
+        $this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1115
+        $this->registerAlias(ITeamManager::class, TeamManager::class);
1116
+
1117
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1118
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1119
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1120
+            return new \OC\Files\AppData\Factory(
1121
+                $c->get(IRootFolder::class),
1122
+                $c->get(SystemConfig::class)
1123
+            );
1124
+        });
1125
+
1126
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1127
+            return new LockdownManager(function () use ($c) {
1128
+                return $c->get(ISession::class);
1129
+            });
1130
+        });
1131
+
1132
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1133
+            return new DiscoveryService(
1134
+                $c->get(ICacheFactory::class),
1135
+                $c->get(IClientService::class)
1136
+            );
1137
+        });
1138
+        $this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1139
+
1140
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1141
+            return new CloudIdManager(
1142
+                $c->get(ICacheFactory::class),
1143
+                $c->get(IEventDispatcher::class),
1144
+                $c->get(\OCP\Contacts\IManager::class),
1145
+                $c->get(IURLGenerator::class),
1146
+                $c->get(IUserManager::class),
1147
+            );
1148
+        });
1149 1149
 
1150
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1151
-		$this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1152
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1153
-			return new CloudFederationFactory();
1154
-		});
1150
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1151
+        $this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1152
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1153
+            return new CloudFederationFactory();
1154
+        });
1155 1155
 
1156
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1156
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1157 1157
 
1158
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1159
-		$this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1158
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1159
+        $this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1160 1160
 
1161
-		$this->registerService(Defaults::class, function (Server $c) {
1162
-			return new Defaults(
1163
-				$c->get('ThemingDefaults')
1164
-			);
1165
-		});
1161
+        $this->registerService(Defaults::class, function (Server $c) {
1162
+            return new Defaults(
1163
+                $c->get('ThemingDefaults')
1164
+            );
1165
+        });
1166 1166
 
1167
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1168
-			return $c->get(\OCP\IUserSession::class)->getSession();
1169
-		}, false);
1167
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1168
+            return $c->get(\OCP\IUserSession::class)->getSession();
1169
+        }, false);
1170 1170
 
1171
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1172
-			return new ShareHelper(
1173
-				$c->get(\OCP\Share\IManager::class)
1174
-			);
1175
-		});
1171
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1172
+            return new ShareHelper(
1173
+                $c->get(\OCP\Share\IManager::class)
1174
+            );
1175
+        });
1176 1176
 
1177
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1178
-			return new ApiFactory($c->get(IClientService::class));
1179
-		});
1177
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1178
+            return new ApiFactory($c->get(IClientService::class));
1179
+        });
1180 1180
 
1181
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1182
-			$memcacheFactory = $c->get(ICacheFactory::class);
1183
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1184
-		});
1181
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1182
+            $memcacheFactory = $c->get(ICacheFactory::class);
1183
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1184
+        });
1185 1185
 
1186
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1187
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1186
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1187
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1188 1188
 
1189
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1189
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1190 1190
 
1191
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1191
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1192 1192
 
1193
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1194
-		$this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1193
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1194
+        $this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1195 1195
 
1196
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1196
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1197 1197
 
1198
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1198
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1199 1199
 
1200
-		$this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1200
+        $this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1201 1201
 
1202
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1202
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1203 1203
 
1204
-		$this->registerAlias(IBroker::class, Broker::class);
1204
+        $this->registerAlias(IBroker::class, Broker::class);
1205 1205
 
1206
-		$this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1206
+        $this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1207 1207
 
1208
-		$this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1208
+        $this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1209 1209
 
1210
-		$this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1210
+        $this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1211 1211
 
1212
-		$this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1212
+        $this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1213 1213
 
1214
-		$this->registerAlias(ITranslationManager::class, TranslationManager::class);
1214
+        $this->registerAlias(ITranslationManager::class, TranslationManager::class);
1215 1215
 
1216
-		$this->registerAlias(IConversionManager::class, ConversionManager::class);
1216
+        $this->registerAlias(IConversionManager::class, ConversionManager::class);
1217 1217
 
1218
-		$this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1218
+        $this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1219 1219
 
1220
-		$this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1220
+        $this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1221 1221
 
1222
-		$this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1222
+        $this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1223 1223
 
1224
-		$this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1224
+        $this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1225 1225
 
1226
-		$this->registerAlias(ILimiter::class, Limiter::class);
1226
+        $this->registerAlias(ILimiter::class, Limiter::class);
1227 1227
 
1228
-		$this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1228
+        $this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1229 1229
 
1230
-		// there is no reason for having OCMProvider as a Service
1231
-		$this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1232
-		$this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1230
+        // there is no reason for having OCMProvider as a Service
1231
+        $this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1232
+        $this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1233 1233
 
1234
-		$this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1234
+        $this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1235 1235
 
1236
-		$this->registerAlias(IProfileManager::class, ProfileManager::class);
1236
+        $this->registerAlias(IProfileManager::class, ProfileManager::class);
1237 1237
 
1238
-		$this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1238
+        $this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1239 1239
 
1240
-		$this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1240
+        $this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1241 1241
 
1242
-		$this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1242
+        $this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1243 1243
 
1244
-		$this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1244
+        $this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1245 1245
 
1246
-		$this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1246
+        $this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1247 1247
 
1248
-		$this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1248
+        $this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1249 1249
 
1250
-		$this->registerAlias(ISignatureManager::class, SignatureManager::class);
1250
+        $this->registerAlias(ISignatureManager::class, SignatureManager::class);
1251 1251
 
1252
-		$this->connectDispatcher();
1253
-	}
1252
+        $this->connectDispatcher();
1253
+    }
1254 1254
 
1255
-	public function boot() {
1256
-		/** @var HookConnector $hookConnector */
1257
-		$hookConnector = $this->get(HookConnector::class);
1258
-		$hookConnector->viewToNode();
1259
-	}
1260
-
1261
-	private function connectDispatcher(): void {
1262
-		/** @var IEventDispatcher $eventDispatcher */
1263
-		$eventDispatcher = $this->get(IEventDispatcher::class);
1264
-		$eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1265
-		$eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1266
-		$eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1267
-		$eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1268
-
1269
-		FilesMetadataManager::loadListeners($eventDispatcher);
1270
-		GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1271
-	}
1272
-
1273
-	/**
1274
-	 * @return \OCP\Contacts\IManager
1275
-	 * @deprecated 20.0.0
1276
-	 */
1277
-	public function getContactsManager() {
1278
-		return $this->get(\OCP\Contacts\IManager::class);
1279
-	}
1280
-
1281
-	/**
1282
-	 * @return \OC\Encryption\Manager
1283
-	 * @deprecated 20.0.0
1284
-	 */
1285
-	public function getEncryptionManager() {
1286
-		return $this->get(\OCP\Encryption\IManager::class);
1287
-	}
1288
-
1289
-	/**
1290
-	 * @return \OC\Encryption\File
1291
-	 * @deprecated 20.0.0
1292
-	 */
1293
-	public function getEncryptionFilesHelper() {
1294
-		return $this->get(IFile::class);
1295
-	}
1296
-
1297
-	/**
1298
-	 * The current request object holding all information about the request
1299
-	 * currently being processed is returned from this method.
1300
-	 * In case the current execution was not initiated by a web request null is returned
1301
-	 *
1302
-	 * @return \OCP\IRequest
1303
-	 * @deprecated 20.0.0
1304
-	 */
1305
-	public function getRequest() {
1306
-		return $this->get(IRequest::class);
1307
-	}
1308
-
1309
-	/**
1310
-	 * Returns the root folder of ownCloud's data directory
1311
-	 *
1312
-	 * @return IRootFolder
1313
-	 * @deprecated 20.0.0
1314
-	 */
1315
-	public function getRootFolder() {
1316
-		return $this->get(IRootFolder::class);
1317
-	}
1318
-
1319
-	/**
1320
-	 * Returns the root folder of ownCloud's data directory
1321
-	 * This is the lazy variant so this gets only initialized once it
1322
-	 * is actually used.
1323
-	 *
1324
-	 * @return IRootFolder
1325
-	 * @deprecated 20.0.0
1326
-	 */
1327
-	public function getLazyRootFolder() {
1328
-		return $this->get(IRootFolder::class);
1329
-	}
1330
-
1331
-	/**
1332
-	 * Returns a view to ownCloud's files folder
1333
-	 *
1334
-	 * @param string $userId user ID
1335
-	 * @return \OCP\Files\Folder|null
1336
-	 * @deprecated 20.0.0
1337
-	 */
1338
-	public function getUserFolder($userId = null) {
1339
-		if ($userId === null) {
1340
-			$user = $this->get(IUserSession::class)->getUser();
1341
-			if (!$user) {
1342
-				return null;
1343
-			}
1344
-			$userId = $user->getUID();
1345
-		}
1346
-		$root = $this->get(IRootFolder::class);
1347
-		return $root->getUserFolder($userId);
1348
-	}
1349
-
1350
-	/**
1351
-	 * @return \OC\User\Manager
1352
-	 * @deprecated 20.0.0
1353
-	 */
1354
-	public function getUserManager() {
1355
-		return $this->get(IUserManager::class);
1356
-	}
1357
-
1358
-	/**
1359
-	 * @return \OC\Group\Manager
1360
-	 * @deprecated 20.0.0
1361
-	 */
1362
-	public function getGroupManager() {
1363
-		return $this->get(IGroupManager::class);
1364
-	}
1365
-
1366
-	/**
1367
-	 * @return \OC\User\Session
1368
-	 * @deprecated 20.0.0
1369
-	 */
1370
-	public function getUserSession() {
1371
-		return $this->get(IUserSession::class);
1372
-	}
1373
-
1374
-	/**
1375
-	 * @return \OCP\ISession
1376
-	 * @deprecated 20.0.0
1377
-	 */
1378
-	public function getSession() {
1379
-		return $this->get(Session::class)->getSession();
1380
-	}
1381
-
1382
-	/**
1383
-	 * @param \OCP\ISession $session
1384
-	 * @return void
1385
-	 */
1386
-	public function setSession(\OCP\ISession $session) {
1387
-		$this->get(SessionStorage::class)->setSession($session);
1388
-		$this->get(Session::class)->setSession($session);
1389
-		$this->get(Store::class)->setSession($session);
1390
-	}
1391
-
1392
-	/**
1393
-	 * @return \OCP\IConfig
1394
-	 * @deprecated 20.0.0
1395
-	 */
1396
-	public function getConfig() {
1397
-		return $this->get(AllConfig::class);
1398
-	}
1399
-
1400
-	/**
1401
-	 * @return \OC\SystemConfig
1402
-	 * @deprecated 20.0.0
1403
-	 */
1404
-	public function getSystemConfig() {
1405
-		return $this->get(SystemConfig::class);
1406
-	}
1407
-
1408
-	/**
1409
-	 * @return IFactory
1410
-	 * @deprecated 20.0.0
1411
-	 */
1412
-	public function getL10NFactory() {
1413
-		return $this->get(IFactory::class);
1414
-	}
1415
-
1416
-	/**
1417
-	 * get an L10N instance
1418
-	 *
1419
-	 * @param string $app appid
1420
-	 * @param string $lang
1421
-	 * @return IL10N
1422
-	 * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1423
-	 */
1424
-	public function getL10N($app, $lang = null) {
1425
-		return $this->get(IFactory::class)->get($app, $lang);
1426
-	}
1427
-
1428
-	/**
1429
-	 * @return IURLGenerator
1430
-	 * @deprecated 20.0.0
1431
-	 */
1432
-	public function getURLGenerator() {
1433
-		return $this->get(IURLGenerator::class);
1434
-	}
1435
-
1436
-	/**
1437
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1438
-	 * getMemCacheFactory() instead.
1439
-	 *
1440
-	 * @return ICache
1441
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1442
-	 */
1443
-	public function getCache() {
1444
-		return $this->get(ICache::class);
1445
-	}
1446
-
1447
-	/**
1448
-	 * Returns an \OCP\CacheFactory instance
1449
-	 *
1450
-	 * @return \OCP\ICacheFactory
1451
-	 * @deprecated 20.0.0
1452
-	 */
1453
-	public function getMemCacheFactory() {
1454
-		return $this->get(ICacheFactory::class);
1455
-	}
1456
-
1457
-	/**
1458
-	 * Returns the current session
1459
-	 *
1460
-	 * @return \OCP\IDBConnection
1461
-	 * @deprecated 20.0.0
1462
-	 */
1463
-	public function getDatabaseConnection() {
1464
-		return $this->get(IDBConnection::class);
1465
-	}
1466
-
1467
-	/**
1468
-	 * Returns the activity manager
1469
-	 *
1470
-	 * @return \OCP\Activity\IManager
1471
-	 * @deprecated 20.0.0
1472
-	 */
1473
-	public function getActivityManager() {
1474
-		return $this->get(\OCP\Activity\IManager::class);
1475
-	}
1476
-
1477
-	/**
1478
-	 * Returns an job list for controlling background jobs
1479
-	 *
1480
-	 * @return IJobList
1481
-	 * @deprecated 20.0.0
1482
-	 */
1483
-	public function getJobList() {
1484
-		return $this->get(IJobList::class);
1485
-	}
1486
-
1487
-	/**
1488
-	 * Returns a SecureRandom instance
1489
-	 *
1490
-	 * @return \OCP\Security\ISecureRandom
1491
-	 * @deprecated 20.0.0
1492
-	 */
1493
-	public function getSecureRandom() {
1494
-		return $this->get(ISecureRandom::class);
1495
-	}
1496
-
1497
-	/**
1498
-	 * Returns a Crypto instance
1499
-	 *
1500
-	 * @return ICrypto
1501
-	 * @deprecated 20.0.0
1502
-	 */
1503
-	public function getCrypto() {
1504
-		return $this->get(ICrypto::class);
1505
-	}
1506
-
1507
-	/**
1508
-	 * Returns a Hasher instance
1509
-	 *
1510
-	 * @return IHasher
1511
-	 * @deprecated 20.0.0
1512
-	 */
1513
-	public function getHasher() {
1514
-		return $this->get(IHasher::class);
1515
-	}
1516
-
1517
-	/**
1518
-	 * Get the certificate manager
1519
-	 *
1520
-	 * @return \OCP\ICertificateManager
1521
-	 */
1522
-	public function getCertificateManager() {
1523
-		return $this->get(ICertificateManager::class);
1524
-	}
1525
-
1526
-	/**
1527
-	 * Get the manager for temporary files and folders
1528
-	 *
1529
-	 * @return \OCP\ITempManager
1530
-	 * @deprecated 20.0.0
1531
-	 */
1532
-	public function getTempManager() {
1533
-		return $this->get(ITempManager::class);
1534
-	}
1535
-
1536
-	/**
1537
-	 * Get the app manager
1538
-	 *
1539
-	 * @return \OCP\App\IAppManager
1540
-	 * @deprecated 20.0.0
1541
-	 */
1542
-	public function getAppManager() {
1543
-		return $this->get(IAppManager::class);
1544
-	}
1545
-
1546
-	/**
1547
-	 * Creates a new mailer
1548
-	 *
1549
-	 * @return IMailer
1550
-	 * @deprecated 20.0.0
1551
-	 */
1552
-	public function getMailer() {
1553
-		return $this->get(IMailer::class);
1554
-	}
1555
-
1556
-	/**
1557
-	 * Get the webroot
1558
-	 *
1559
-	 * @return string
1560
-	 * @deprecated 20.0.0
1561
-	 */
1562
-	public function getWebRoot() {
1563
-		return $this->webRoot;
1564
-	}
1565
-
1566
-	/**
1567
-	 * Get the locking provider
1568
-	 *
1569
-	 * @return ILockingProvider
1570
-	 * @since 8.1.0
1571
-	 * @deprecated 20.0.0
1572
-	 */
1573
-	public function getLockingProvider() {
1574
-		return $this->get(ILockingProvider::class);
1575
-	}
1576
-
1577
-	/**
1578
-	 * Get the MimeTypeDetector
1579
-	 *
1580
-	 * @return IMimeTypeDetector
1581
-	 * @deprecated 20.0.0
1582
-	 */
1583
-	public function getMimeTypeDetector() {
1584
-		return $this->get(IMimeTypeDetector::class);
1585
-	}
1586
-
1587
-	/**
1588
-	 * Get the MimeTypeLoader
1589
-	 *
1590
-	 * @return IMimeTypeLoader
1591
-	 * @deprecated 20.0.0
1592
-	 */
1593
-	public function getMimeTypeLoader() {
1594
-		return $this->get(IMimeTypeLoader::class);
1595
-	}
1596
-
1597
-	/**
1598
-	 * Get the Notification Manager
1599
-	 *
1600
-	 * @return \OCP\Notification\IManager
1601
-	 * @since 8.2.0
1602
-	 * @deprecated 20.0.0
1603
-	 */
1604
-	public function getNotificationManager() {
1605
-		return $this->get(\OCP\Notification\IManager::class);
1606
-	}
1607
-
1608
-	/**
1609
-	 * @return \OCA\Theming\ThemingDefaults
1610
-	 * @deprecated 20.0.0
1611
-	 */
1612
-	public function getThemingDefaults() {
1613
-		return $this->get('ThemingDefaults');
1614
-	}
1615
-
1616
-	/**
1617
-	 * @return \OC\IntegrityCheck\Checker
1618
-	 * @deprecated 20.0.0
1619
-	 */
1620
-	public function getIntegrityCodeChecker() {
1621
-		return $this->get('IntegrityCodeChecker');
1622
-	}
1623
-
1624
-	/**
1625
-	 * @return CsrfTokenManager
1626
-	 * @deprecated 20.0.0
1627
-	 */
1628
-	public function getCsrfTokenManager() {
1629
-		return $this->get(CsrfTokenManager::class);
1630
-	}
1631
-
1632
-	/**
1633
-	 * @return ContentSecurityPolicyNonceManager
1634
-	 * @deprecated 20.0.0
1635
-	 */
1636
-	public function getContentSecurityPolicyNonceManager() {
1637
-		return $this->get(ContentSecurityPolicyNonceManager::class);
1638
-	}
1639
-
1640
-	/**
1641
-	 * @return \OCP\Settings\IManager
1642
-	 * @deprecated 20.0.0
1643
-	 */
1644
-	public function getSettingsManager() {
1645
-		return $this->get(\OC\Settings\Manager::class);
1646
-	}
1647
-
1648
-	/**
1649
-	 * @return \OCP\Files\IAppData
1650
-	 * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1651
-	 */
1652
-	public function getAppDataDir($app) {
1653
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
1654
-		return $factory->get($app);
1655
-	}
1656
-
1657
-	/**
1658
-	 * @return \OCP\Federation\ICloudIdManager
1659
-	 * @deprecated 20.0.0
1660
-	 */
1661
-	public function getCloudIdManager() {
1662
-		return $this->get(ICloudIdManager::class);
1663
-	}
1255
+    public function boot() {
1256
+        /** @var HookConnector $hookConnector */
1257
+        $hookConnector = $this->get(HookConnector::class);
1258
+        $hookConnector->viewToNode();
1259
+    }
1260
+
1261
+    private function connectDispatcher(): void {
1262
+        /** @var IEventDispatcher $eventDispatcher */
1263
+        $eventDispatcher = $this->get(IEventDispatcher::class);
1264
+        $eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1265
+        $eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1266
+        $eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1267
+        $eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1268
+
1269
+        FilesMetadataManager::loadListeners($eventDispatcher);
1270
+        GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1271
+    }
1272
+
1273
+    /**
1274
+     * @return \OCP\Contacts\IManager
1275
+     * @deprecated 20.0.0
1276
+     */
1277
+    public function getContactsManager() {
1278
+        return $this->get(\OCP\Contacts\IManager::class);
1279
+    }
1280
+
1281
+    /**
1282
+     * @return \OC\Encryption\Manager
1283
+     * @deprecated 20.0.0
1284
+     */
1285
+    public function getEncryptionManager() {
1286
+        return $this->get(\OCP\Encryption\IManager::class);
1287
+    }
1288
+
1289
+    /**
1290
+     * @return \OC\Encryption\File
1291
+     * @deprecated 20.0.0
1292
+     */
1293
+    public function getEncryptionFilesHelper() {
1294
+        return $this->get(IFile::class);
1295
+    }
1296
+
1297
+    /**
1298
+     * The current request object holding all information about the request
1299
+     * currently being processed is returned from this method.
1300
+     * In case the current execution was not initiated by a web request null is returned
1301
+     *
1302
+     * @return \OCP\IRequest
1303
+     * @deprecated 20.0.0
1304
+     */
1305
+    public function getRequest() {
1306
+        return $this->get(IRequest::class);
1307
+    }
1308
+
1309
+    /**
1310
+     * Returns the root folder of ownCloud's data directory
1311
+     *
1312
+     * @return IRootFolder
1313
+     * @deprecated 20.0.0
1314
+     */
1315
+    public function getRootFolder() {
1316
+        return $this->get(IRootFolder::class);
1317
+    }
1318
+
1319
+    /**
1320
+     * Returns the root folder of ownCloud's data directory
1321
+     * This is the lazy variant so this gets only initialized once it
1322
+     * is actually used.
1323
+     *
1324
+     * @return IRootFolder
1325
+     * @deprecated 20.0.0
1326
+     */
1327
+    public function getLazyRootFolder() {
1328
+        return $this->get(IRootFolder::class);
1329
+    }
1330
+
1331
+    /**
1332
+     * Returns a view to ownCloud's files folder
1333
+     *
1334
+     * @param string $userId user ID
1335
+     * @return \OCP\Files\Folder|null
1336
+     * @deprecated 20.0.0
1337
+     */
1338
+    public function getUserFolder($userId = null) {
1339
+        if ($userId === null) {
1340
+            $user = $this->get(IUserSession::class)->getUser();
1341
+            if (!$user) {
1342
+                return null;
1343
+            }
1344
+            $userId = $user->getUID();
1345
+        }
1346
+        $root = $this->get(IRootFolder::class);
1347
+        return $root->getUserFolder($userId);
1348
+    }
1349
+
1350
+    /**
1351
+     * @return \OC\User\Manager
1352
+     * @deprecated 20.0.0
1353
+     */
1354
+    public function getUserManager() {
1355
+        return $this->get(IUserManager::class);
1356
+    }
1357
+
1358
+    /**
1359
+     * @return \OC\Group\Manager
1360
+     * @deprecated 20.0.0
1361
+     */
1362
+    public function getGroupManager() {
1363
+        return $this->get(IGroupManager::class);
1364
+    }
1365
+
1366
+    /**
1367
+     * @return \OC\User\Session
1368
+     * @deprecated 20.0.0
1369
+     */
1370
+    public function getUserSession() {
1371
+        return $this->get(IUserSession::class);
1372
+    }
1373
+
1374
+    /**
1375
+     * @return \OCP\ISession
1376
+     * @deprecated 20.0.0
1377
+     */
1378
+    public function getSession() {
1379
+        return $this->get(Session::class)->getSession();
1380
+    }
1381
+
1382
+    /**
1383
+     * @param \OCP\ISession $session
1384
+     * @return void
1385
+     */
1386
+    public function setSession(\OCP\ISession $session) {
1387
+        $this->get(SessionStorage::class)->setSession($session);
1388
+        $this->get(Session::class)->setSession($session);
1389
+        $this->get(Store::class)->setSession($session);
1390
+    }
1391
+
1392
+    /**
1393
+     * @return \OCP\IConfig
1394
+     * @deprecated 20.0.0
1395
+     */
1396
+    public function getConfig() {
1397
+        return $this->get(AllConfig::class);
1398
+    }
1399
+
1400
+    /**
1401
+     * @return \OC\SystemConfig
1402
+     * @deprecated 20.0.0
1403
+     */
1404
+    public function getSystemConfig() {
1405
+        return $this->get(SystemConfig::class);
1406
+    }
1407
+
1408
+    /**
1409
+     * @return IFactory
1410
+     * @deprecated 20.0.0
1411
+     */
1412
+    public function getL10NFactory() {
1413
+        return $this->get(IFactory::class);
1414
+    }
1415
+
1416
+    /**
1417
+     * get an L10N instance
1418
+     *
1419
+     * @param string $app appid
1420
+     * @param string $lang
1421
+     * @return IL10N
1422
+     * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1423
+     */
1424
+    public function getL10N($app, $lang = null) {
1425
+        return $this->get(IFactory::class)->get($app, $lang);
1426
+    }
1427
+
1428
+    /**
1429
+     * @return IURLGenerator
1430
+     * @deprecated 20.0.0
1431
+     */
1432
+    public function getURLGenerator() {
1433
+        return $this->get(IURLGenerator::class);
1434
+    }
1435
+
1436
+    /**
1437
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1438
+     * getMemCacheFactory() instead.
1439
+     *
1440
+     * @return ICache
1441
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1442
+     */
1443
+    public function getCache() {
1444
+        return $this->get(ICache::class);
1445
+    }
1446
+
1447
+    /**
1448
+     * Returns an \OCP\CacheFactory instance
1449
+     *
1450
+     * @return \OCP\ICacheFactory
1451
+     * @deprecated 20.0.0
1452
+     */
1453
+    public function getMemCacheFactory() {
1454
+        return $this->get(ICacheFactory::class);
1455
+    }
1456
+
1457
+    /**
1458
+     * Returns the current session
1459
+     *
1460
+     * @return \OCP\IDBConnection
1461
+     * @deprecated 20.0.0
1462
+     */
1463
+    public function getDatabaseConnection() {
1464
+        return $this->get(IDBConnection::class);
1465
+    }
1466
+
1467
+    /**
1468
+     * Returns the activity manager
1469
+     *
1470
+     * @return \OCP\Activity\IManager
1471
+     * @deprecated 20.0.0
1472
+     */
1473
+    public function getActivityManager() {
1474
+        return $this->get(\OCP\Activity\IManager::class);
1475
+    }
1476
+
1477
+    /**
1478
+     * Returns an job list for controlling background jobs
1479
+     *
1480
+     * @return IJobList
1481
+     * @deprecated 20.0.0
1482
+     */
1483
+    public function getJobList() {
1484
+        return $this->get(IJobList::class);
1485
+    }
1486
+
1487
+    /**
1488
+     * Returns a SecureRandom instance
1489
+     *
1490
+     * @return \OCP\Security\ISecureRandom
1491
+     * @deprecated 20.0.0
1492
+     */
1493
+    public function getSecureRandom() {
1494
+        return $this->get(ISecureRandom::class);
1495
+    }
1496
+
1497
+    /**
1498
+     * Returns a Crypto instance
1499
+     *
1500
+     * @return ICrypto
1501
+     * @deprecated 20.0.0
1502
+     */
1503
+    public function getCrypto() {
1504
+        return $this->get(ICrypto::class);
1505
+    }
1506
+
1507
+    /**
1508
+     * Returns a Hasher instance
1509
+     *
1510
+     * @return IHasher
1511
+     * @deprecated 20.0.0
1512
+     */
1513
+    public function getHasher() {
1514
+        return $this->get(IHasher::class);
1515
+    }
1516
+
1517
+    /**
1518
+     * Get the certificate manager
1519
+     *
1520
+     * @return \OCP\ICertificateManager
1521
+     */
1522
+    public function getCertificateManager() {
1523
+        return $this->get(ICertificateManager::class);
1524
+    }
1525
+
1526
+    /**
1527
+     * Get the manager for temporary files and folders
1528
+     *
1529
+     * @return \OCP\ITempManager
1530
+     * @deprecated 20.0.0
1531
+     */
1532
+    public function getTempManager() {
1533
+        return $this->get(ITempManager::class);
1534
+    }
1535
+
1536
+    /**
1537
+     * Get the app manager
1538
+     *
1539
+     * @return \OCP\App\IAppManager
1540
+     * @deprecated 20.0.0
1541
+     */
1542
+    public function getAppManager() {
1543
+        return $this->get(IAppManager::class);
1544
+    }
1545
+
1546
+    /**
1547
+     * Creates a new mailer
1548
+     *
1549
+     * @return IMailer
1550
+     * @deprecated 20.0.0
1551
+     */
1552
+    public function getMailer() {
1553
+        return $this->get(IMailer::class);
1554
+    }
1555
+
1556
+    /**
1557
+     * Get the webroot
1558
+     *
1559
+     * @return string
1560
+     * @deprecated 20.0.0
1561
+     */
1562
+    public function getWebRoot() {
1563
+        return $this->webRoot;
1564
+    }
1565
+
1566
+    /**
1567
+     * Get the locking provider
1568
+     *
1569
+     * @return ILockingProvider
1570
+     * @since 8.1.0
1571
+     * @deprecated 20.0.0
1572
+     */
1573
+    public function getLockingProvider() {
1574
+        return $this->get(ILockingProvider::class);
1575
+    }
1576
+
1577
+    /**
1578
+     * Get the MimeTypeDetector
1579
+     *
1580
+     * @return IMimeTypeDetector
1581
+     * @deprecated 20.0.0
1582
+     */
1583
+    public function getMimeTypeDetector() {
1584
+        return $this->get(IMimeTypeDetector::class);
1585
+    }
1586
+
1587
+    /**
1588
+     * Get the MimeTypeLoader
1589
+     *
1590
+     * @return IMimeTypeLoader
1591
+     * @deprecated 20.0.0
1592
+     */
1593
+    public function getMimeTypeLoader() {
1594
+        return $this->get(IMimeTypeLoader::class);
1595
+    }
1596
+
1597
+    /**
1598
+     * Get the Notification Manager
1599
+     *
1600
+     * @return \OCP\Notification\IManager
1601
+     * @since 8.2.0
1602
+     * @deprecated 20.0.0
1603
+     */
1604
+    public function getNotificationManager() {
1605
+        return $this->get(\OCP\Notification\IManager::class);
1606
+    }
1607
+
1608
+    /**
1609
+     * @return \OCA\Theming\ThemingDefaults
1610
+     * @deprecated 20.0.0
1611
+     */
1612
+    public function getThemingDefaults() {
1613
+        return $this->get('ThemingDefaults');
1614
+    }
1615
+
1616
+    /**
1617
+     * @return \OC\IntegrityCheck\Checker
1618
+     * @deprecated 20.0.0
1619
+     */
1620
+    public function getIntegrityCodeChecker() {
1621
+        return $this->get('IntegrityCodeChecker');
1622
+    }
1623
+
1624
+    /**
1625
+     * @return CsrfTokenManager
1626
+     * @deprecated 20.0.0
1627
+     */
1628
+    public function getCsrfTokenManager() {
1629
+        return $this->get(CsrfTokenManager::class);
1630
+    }
1631
+
1632
+    /**
1633
+     * @return ContentSecurityPolicyNonceManager
1634
+     * @deprecated 20.0.0
1635
+     */
1636
+    public function getContentSecurityPolicyNonceManager() {
1637
+        return $this->get(ContentSecurityPolicyNonceManager::class);
1638
+    }
1639
+
1640
+    /**
1641
+     * @return \OCP\Settings\IManager
1642
+     * @deprecated 20.0.0
1643
+     */
1644
+    public function getSettingsManager() {
1645
+        return $this->get(\OC\Settings\Manager::class);
1646
+    }
1647
+
1648
+    /**
1649
+     * @return \OCP\Files\IAppData
1650
+     * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1651
+     */
1652
+    public function getAppDataDir($app) {
1653
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
1654
+        return $factory->get($app);
1655
+    }
1656
+
1657
+    /**
1658
+     * @return \OCP\Federation\ICloudIdManager
1659
+     * @deprecated 20.0.0
1660
+     */
1661
+    public function getCloudIdManager() {
1662
+        return $this->get(ICloudIdManager::class);
1663
+    }
1664 1664
 }
Please login to merge, or discard this patch.
lib/private/TemplateLayout.php 2 patches
Indentation   +371 added lines, -371 removed lines patch added patch discarded remove patch
@@ -39,375 +39,375 @@
 block discarded – undo
39 39
 use OCP\Util;
40 40
 
41 41
 class TemplateLayout {
42
-	private static string $versionHash = '';
43
-	/** @var string[] */
44
-	private static array $cacheBusterCache = [];
45
-
46
-	public ?CSSResourceLocator $cssLocator = null;
47
-	public ?JSResourceLocator $jsLocator = null;
48
-
49
-	public function __construct(
50
-		private IConfig $config,
51
-		private readonly IAppConfig $appConfig,
52
-		private IAppManager $appManager,
53
-		private InitialStateService $initialState,
54
-		private INavigationManager $navigationManager,
55
-		private ITemplateManager $templateManager,
56
-		private ServerVersion $serverVersion,
57
-	) {
58
-	}
59
-
60
-	public function getPageTemplate(string $renderAs, string $appId): ITemplate {
61
-		// Add fallback theming variables if not rendered as user
62
-		if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
63
-			// TODO cache generated default theme if enabled for fallback if server is erroring ?
64
-			Util::addStyle('theming', 'default');
65
-		}
66
-
67
-		// Decide which page we show
68
-		switch ($renderAs) {
69
-			case TemplateResponse::RENDER_AS_USER:
70
-				$page = $this->templateManager->getTemplate('core', 'layout.user');
71
-				if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
72
-					$page->assign('bodyid', 'body-settings');
73
-				} else {
74
-					$page->assign('bodyid', 'body-user');
75
-				}
76
-
77
-				$this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
78
-				$this->initialState->provideInitialState('core', 'apps', array_values($this->navigationManager->getAll()));
79
-
80
-				$this->initialState->provideInitialState('unified-search', 'min-search-length', $this->appConfig->getValueInt(Application::APP_ID, ConfigLexicon::UNIFIED_SEARCH_MIN_SEARCH_LENGTH));
81
-				if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
82
-					$this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
83
-					$this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
84
-					Util::addScript('core', 'legacy-unified-search', 'core');
85
-				} else {
86
-					Util::addScript('core', 'unified-search', 'core');
87
-				}
88
-
89
-				// Set logo link target
90
-				$logoUrl = $this->config->getSystemValueString('logo_url', '');
91
-				$page->assign('logoUrl', $logoUrl);
92
-
93
-				// Set default entry name
94
-				$defaultEntryId = $this->navigationManager->getDefaultEntryIdForUser();
95
-				$defaultEntry = $this->navigationManager->get($defaultEntryId);
96
-				$page->assign('defaultAppName', $defaultEntry['name'] ?? '');
97
-
98
-				// Add navigation entry
99
-				$page->assign('application', '');
100
-				$page->assign('appid', $appId);
101
-
102
-				$navigation = $this->navigationManager->getAll();
103
-				$page->assign('navigation', $navigation);
104
-				$settingsNavigation = $this->navigationManager->getAll('settings');
105
-				$this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
106
-
107
-				foreach ($navigation as $entry) {
108
-					if ($entry['active']) {
109
-						$page->assign('application', $entry['name']);
110
-						break;
111
-					}
112
-				}
113
-
114
-				foreach ($settingsNavigation as $entry) {
115
-					if ($entry['active']) {
116
-						$page->assign('application', $entry['name']);
117
-						break;
118
-					}
119
-				}
120
-
121
-				$user = Server::get(IUserSession::class)->getUser();
122
-
123
-				if ($user === null) {
124
-					$page->assign('user_uid', false);
125
-					$page->assign('user_displayname', false);
126
-					$page->assign('userAvatarSet', false);
127
-					$page->assign('userStatus', false);
128
-				} else {
129
-					$page->assign('user_uid', $user->getUID());
130
-					$page->assign('user_displayname', $user->getDisplayName());
131
-					$page->assign('userAvatarSet', true);
132
-					$page->assign('userAvatarVersion', $this->config->getUserValue($user->getUID(), 'avatar', 'version', 0));
133
-				}
134
-				break;
135
-			case TemplateResponse::RENDER_AS_ERROR:
136
-				$page = $this->templateManager->getTemplate('core', 'layout.guest', '', false);
137
-				$page->assign('bodyid', 'body-login');
138
-				$page->assign('user_displayname', '');
139
-				$page->assign('user_uid', '');
140
-				break;
141
-			case TemplateResponse::RENDER_AS_GUEST:
142
-				$page = $this->templateManager->getTemplate('core', 'layout.guest');
143
-				Util::addStyle('guest');
144
-				$page->assign('bodyid', 'body-login');
145
-
146
-				$userDisplayName = false;
147
-				$user = Server::get(IUserSession::class)->getUser();
148
-				if ($user) {
149
-					$userDisplayName = $user->getDisplayName();
150
-				}
151
-
152
-				$page->assign('user_displayname', $userDisplayName);
153
-				$page->assign('user_uid', \OC_User::getUser());
154
-				break;
155
-			case TemplateResponse::RENDER_AS_PUBLIC:
156
-				$page = $this->templateManager->getTemplate('core', 'layout.public');
157
-				$page->assign('appid', $appId);
158
-				$page->assign('bodyid', 'body-public');
159
-
160
-				// Set logo link target
161
-				$logoUrl = $this->config->getSystemValueString('logo_url', '');
162
-				$page->assign('logoUrl', $logoUrl);
163
-
164
-				$subscription = Server::get(IRegistry::class);
165
-				$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
166
-				if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
167
-					$showSimpleSignup = false;
168
-				}
169
-
170
-				$defaultSignUpLink = 'https://nextcloud.com/signup/';
171
-				$signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
172
-				if ($signUpLink !== $defaultSignUpLink) {
173
-					$showSimpleSignup = true;
174
-				}
175
-
176
-				if ($this->appManager->isEnabledForUser('registration')) {
177
-					$urlGenerator = Server::get(IURLGenerator::class);
178
-					$signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
179
-				}
180
-
181
-				$page->assign('showSimpleSignUpLink', $showSimpleSignup);
182
-				$page->assign('signUpLink', $signUpLink);
183
-				break;
184
-			default:
185
-				$page = $this->templateManager->getTemplate('core', 'layout.base');
186
-				break;
187
-		}
188
-		// Send the language, locale, and direction to our layouts
189
-		$l10nFactory = Server::get(IFactory::class);
190
-		$lang = $l10nFactory->findLanguage();
191
-		$locale = $l10nFactory->findLocale($lang);
192
-		$direction = $l10nFactory->getLanguageDirection($lang);
193
-
194
-		$lang = str_replace('_', '-', $lang);
195
-		$page->assign('language', $lang);
196
-		$page->assign('locale', $locale);
197
-		$page->assign('direction', $direction);
198
-
199
-		// Set body data-theme
200
-		try {
201
-			$themesService = Server::get(\OCA\Theming\Service\ThemesService::class);
202
-		} catch (\Exception) {
203
-			$themesService = null;
204
-		}
205
-		$page->assign('enabledThemes', $themesService?->getEnabledThemes() ?? []);
206
-
207
-		if ($this->config->getSystemValueBool('installed', false)) {
208
-			if (empty(self::$versionHash)) {
209
-				$v = $this->appManager->getAppInstalledVersions(true);
210
-				$v['core'] = implode('.', $this->serverVersion->getVersion());
211
-				self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
212
-			}
213
-		} else {
214
-			self::$versionHash = md5('not installed');
215
-		}
216
-
217
-		// Add the js files
218
-		$jsFiles = $this->findJavascriptFiles(Util::getScripts());
219
-		$page->assign('jsfiles', []);
220
-		if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
221
-			// this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
222
-			// see https://github.com/nextcloud/server/pull/22636 for details
223
-			$jsConfigHelper = new JSConfigHelper(
224
-				$this->serverVersion,
225
-				\OCP\Util::getL10N('lib'),
226
-				\OCP\Server::get(Defaults::class),
227
-				$this->appManager,
228
-				\OC::$server->getSession(),
229
-				\OC::$server->getUserSession()->getUser(),
230
-				$this->config,
231
-				$this->appConfig,
232
-				\OC::$server->getGroupManager(),
233
-				\OC::$server->get(IniGetWrapper::class),
234
-				\OC::$server->getURLGenerator(),
235
-				\OC::$server->get(CapabilitiesManager::class),
236
-				\OCP\Server::get(IInitialStateService::class),
237
-				\OCP\Server::get(IProvider::class),
238
-				\OCP\Server::get(FilenameValidator::class),
239
-			);
240
-			$config = $jsConfigHelper->getConfig();
241
-			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
242
-				$page->assign('inline_ocjs', $config);
243
-			} else {
244
-				$page->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
245
-			}
246
-		}
247
-		foreach ($jsFiles as $info) {
248
-			$web = $info[1];
249
-			$file = $info[2];
250
-			$page->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix());
251
-		}
252
-
253
-		$request = \OCP\Server::get(IRequest::class);
254
-
255
-		try {
256
-			$pathInfo = $request->getPathInfo();
257
-		} catch (\Exception $e) {
258
-			$pathInfo = '';
259
-		}
260
-
261
-		// Do not initialise scss appdata until we have a fully installed instance
262
-		// Do not load scss for update, errors, installation or login page
263
-		if ($this->config->getSystemValueBool('installed', false)
264
-			&& !\OCP\Util::needUpgrade()
265
-			&& $pathInfo !== ''
266
-			&& !preg_match('/^\/login/', $pathInfo)
267
-			&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
268
-		) {
269
-			$cssFiles = $this->findStylesheetFiles(\OC_Util::$styles);
270
-		} else {
271
-			// If we ignore the scss compiler,
272
-			// we need to load the guest css fallback
273
-			Util::addStyle('guest');
274
-			$cssFiles = $this->findStylesheetFiles(\OC_Util::$styles);
275
-		}
276
-
277
-		$page->assign('cssfiles', []);
278
-		$page->assign('printcssfiles', []);
279
-		$this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
280
-		foreach ($cssFiles as $info) {
281
-			$web = $info[1];
282
-			$file = $info[2];
283
-
284
-			if (str_ends_with($file, 'print.css')) {
285
-				$page->append('printcssfiles', $web . '/' . $file . $this->getVersionHashSuffix());
286
-			} else {
287
-				$suffix = $this->getVersionHashSuffix($web, $file);
288
-
289
-				if (!str_contains($file, '?v=')) {
290
-					$page->append('cssfiles', $web . '/' . $file . $suffix);
291
-				} else {
292
-					$page->append('cssfiles', $web . '/' . $file . '-' . substr($suffix, 3));
293
-				}
294
-			}
295
-		}
296
-
297
-		if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
298
-			// Prevent auto zoom with iOS but still allow user zoom
299
-			// On chrome (and others) this does not work (will also disable user zoom)
300
-			$page->assign('viewport_maximum_scale', '1.0');
301
-		}
302
-
303
-		$page->assign('initialStates', $this->initialState->getInitialStates());
304
-
305
-		$page->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
306
-		$page->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
307
-
308
-		return $page;
309
-	}
310
-
311
-	protected function getVersionHashSuffix(string $path = '', string $file = ''): string {
312
-		if ($this->config->getSystemValueBool('debug', false)) {
313
-			// allows chrome workspace mapping in debug mode
314
-			return '';
315
-		}
316
-
317
-		if ($this->config->getSystemValueBool('installed', false) === false) {
318
-			// if not installed just return the version hash
319
-			return '?v=' . self::$versionHash;
320
-		}
321
-
322
-		$hash = false;
323
-		// Try the web-root first
324
-		if ($path !== '') {
325
-			$hash = $this->getVersionHashByPath($path);
326
-		}
327
-		// If not found try the file
328
-		if ($hash === false && $file !== '') {
329
-			$hash = $this->getVersionHashByPath($file);
330
-		}
331
-		// As a last resort we use the server version hash
332
-		if ($hash === false) {
333
-			$hash = self::$versionHash;
334
-		}
335
-
336
-		// The theming app is force-enabled thus the cache buster is always available
337
-		$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
338
-
339
-		return '?v=' . $hash . $themingSuffix;
340
-	}
341
-
342
-	private function getVersionHashByPath(string $path): string|false {
343
-		if (array_key_exists($path, self::$cacheBusterCache) === false) {
344
-			// Not yet cached, so lets find the cache buster string
345
-			$appId = $this->getAppNamefromPath($path);
346
-			if ($appId === false) {
347
-				// No app Id could be guessed
348
-				return false;
349
-			}
350
-
351
-			if ($appId === 'core') {
352
-				// core is not a real app but the server itself
353
-				$hash = self::$versionHash;
354
-			} else {
355
-				$appVersion = $this->appManager->getAppVersion($appId);
356
-				// For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
357
-				if ($this->appManager->isShipped($appId)) {
358
-					$appVersion .= '-' . self::$versionHash;
359
-				}
360
-
361
-				$hash = substr(md5($appVersion), 0, 8);
362
-			}
363
-			self::$cacheBusterCache[$path] = $hash;
364
-		}
365
-
366
-		return self::$cacheBusterCache[$path];
367
-	}
368
-
369
-	private function findStylesheetFiles(array $styles): array {
370
-		if ($this->cssLocator === null) {
371
-			$this->cssLocator = \OCP\Server::get(CSSResourceLocator::class);
372
-		}
373
-		$this->cssLocator->find($styles);
374
-		return $this->cssLocator->getResources();
375
-	}
376
-
377
-	public function getAppNamefromPath(string $path): string|false {
378
-		if ($path !== '') {
379
-			$pathParts = explode('/', $path);
380
-			if ($pathParts[0] === 'css') {
381
-				// This is a scss request
382
-				return $pathParts[1];
383
-			} elseif ($pathParts[0] === 'core') {
384
-				return 'core';
385
-			}
386
-			return end($pathParts);
387
-		}
388
-		return false;
389
-	}
390
-
391
-	private function findJavascriptFiles(array $scripts): array {
392
-		if ($this->jsLocator === null) {
393
-			$this->jsLocator = \OCP\Server::get(JSResourceLocator::class);
394
-		}
395
-		$this->jsLocator->find($scripts);
396
-		return $this->jsLocator->getResources();
397
-	}
398
-
399
-	/**
400
-	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
401
-	 * @param string $filePath Absolute path
402
-	 * @return string Relative path
403
-	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
404
-	 */
405
-	public static function convertToRelativePath(string $filePath) {
406
-		$relativePath = explode(\OC::$SERVERROOT, $filePath);
407
-		if (count($relativePath) !== 2) {
408
-			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
409
-		}
410
-
411
-		return $relativePath[1];
412
-	}
42
+    private static string $versionHash = '';
43
+    /** @var string[] */
44
+    private static array $cacheBusterCache = [];
45
+
46
+    public ?CSSResourceLocator $cssLocator = null;
47
+    public ?JSResourceLocator $jsLocator = null;
48
+
49
+    public function __construct(
50
+        private IConfig $config,
51
+        private readonly IAppConfig $appConfig,
52
+        private IAppManager $appManager,
53
+        private InitialStateService $initialState,
54
+        private INavigationManager $navigationManager,
55
+        private ITemplateManager $templateManager,
56
+        private ServerVersion $serverVersion,
57
+    ) {
58
+    }
59
+
60
+    public function getPageTemplate(string $renderAs, string $appId): ITemplate {
61
+        // Add fallback theming variables if not rendered as user
62
+        if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
63
+            // TODO cache generated default theme if enabled for fallback if server is erroring ?
64
+            Util::addStyle('theming', 'default');
65
+        }
66
+
67
+        // Decide which page we show
68
+        switch ($renderAs) {
69
+            case TemplateResponse::RENDER_AS_USER:
70
+                $page = $this->templateManager->getTemplate('core', 'layout.user');
71
+                if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
72
+                    $page->assign('bodyid', 'body-settings');
73
+                } else {
74
+                    $page->assign('bodyid', 'body-user');
75
+                }
76
+
77
+                $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
78
+                $this->initialState->provideInitialState('core', 'apps', array_values($this->navigationManager->getAll()));
79
+
80
+                $this->initialState->provideInitialState('unified-search', 'min-search-length', $this->appConfig->getValueInt(Application::APP_ID, ConfigLexicon::UNIFIED_SEARCH_MIN_SEARCH_LENGTH));
81
+                if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
82
+                    $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
83
+                    $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
84
+                    Util::addScript('core', 'legacy-unified-search', 'core');
85
+                } else {
86
+                    Util::addScript('core', 'unified-search', 'core');
87
+                }
88
+
89
+                // Set logo link target
90
+                $logoUrl = $this->config->getSystemValueString('logo_url', '');
91
+                $page->assign('logoUrl', $logoUrl);
92
+
93
+                // Set default entry name
94
+                $defaultEntryId = $this->navigationManager->getDefaultEntryIdForUser();
95
+                $defaultEntry = $this->navigationManager->get($defaultEntryId);
96
+                $page->assign('defaultAppName', $defaultEntry['name'] ?? '');
97
+
98
+                // Add navigation entry
99
+                $page->assign('application', '');
100
+                $page->assign('appid', $appId);
101
+
102
+                $navigation = $this->navigationManager->getAll();
103
+                $page->assign('navigation', $navigation);
104
+                $settingsNavigation = $this->navigationManager->getAll('settings');
105
+                $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
106
+
107
+                foreach ($navigation as $entry) {
108
+                    if ($entry['active']) {
109
+                        $page->assign('application', $entry['name']);
110
+                        break;
111
+                    }
112
+                }
113
+
114
+                foreach ($settingsNavigation as $entry) {
115
+                    if ($entry['active']) {
116
+                        $page->assign('application', $entry['name']);
117
+                        break;
118
+                    }
119
+                }
120
+
121
+                $user = Server::get(IUserSession::class)->getUser();
122
+
123
+                if ($user === null) {
124
+                    $page->assign('user_uid', false);
125
+                    $page->assign('user_displayname', false);
126
+                    $page->assign('userAvatarSet', false);
127
+                    $page->assign('userStatus', false);
128
+                } else {
129
+                    $page->assign('user_uid', $user->getUID());
130
+                    $page->assign('user_displayname', $user->getDisplayName());
131
+                    $page->assign('userAvatarSet', true);
132
+                    $page->assign('userAvatarVersion', $this->config->getUserValue($user->getUID(), 'avatar', 'version', 0));
133
+                }
134
+                break;
135
+            case TemplateResponse::RENDER_AS_ERROR:
136
+                $page = $this->templateManager->getTemplate('core', 'layout.guest', '', false);
137
+                $page->assign('bodyid', 'body-login');
138
+                $page->assign('user_displayname', '');
139
+                $page->assign('user_uid', '');
140
+                break;
141
+            case TemplateResponse::RENDER_AS_GUEST:
142
+                $page = $this->templateManager->getTemplate('core', 'layout.guest');
143
+                Util::addStyle('guest');
144
+                $page->assign('bodyid', 'body-login');
145
+
146
+                $userDisplayName = false;
147
+                $user = Server::get(IUserSession::class)->getUser();
148
+                if ($user) {
149
+                    $userDisplayName = $user->getDisplayName();
150
+                }
151
+
152
+                $page->assign('user_displayname', $userDisplayName);
153
+                $page->assign('user_uid', \OC_User::getUser());
154
+                break;
155
+            case TemplateResponse::RENDER_AS_PUBLIC:
156
+                $page = $this->templateManager->getTemplate('core', 'layout.public');
157
+                $page->assign('appid', $appId);
158
+                $page->assign('bodyid', 'body-public');
159
+
160
+                // Set logo link target
161
+                $logoUrl = $this->config->getSystemValueString('logo_url', '');
162
+                $page->assign('logoUrl', $logoUrl);
163
+
164
+                $subscription = Server::get(IRegistry::class);
165
+                $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
166
+                if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
167
+                    $showSimpleSignup = false;
168
+                }
169
+
170
+                $defaultSignUpLink = 'https://nextcloud.com/signup/';
171
+                $signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
172
+                if ($signUpLink !== $defaultSignUpLink) {
173
+                    $showSimpleSignup = true;
174
+                }
175
+
176
+                if ($this->appManager->isEnabledForUser('registration')) {
177
+                    $urlGenerator = Server::get(IURLGenerator::class);
178
+                    $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
179
+                }
180
+
181
+                $page->assign('showSimpleSignUpLink', $showSimpleSignup);
182
+                $page->assign('signUpLink', $signUpLink);
183
+                break;
184
+            default:
185
+                $page = $this->templateManager->getTemplate('core', 'layout.base');
186
+                break;
187
+        }
188
+        // Send the language, locale, and direction to our layouts
189
+        $l10nFactory = Server::get(IFactory::class);
190
+        $lang = $l10nFactory->findLanguage();
191
+        $locale = $l10nFactory->findLocale($lang);
192
+        $direction = $l10nFactory->getLanguageDirection($lang);
193
+
194
+        $lang = str_replace('_', '-', $lang);
195
+        $page->assign('language', $lang);
196
+        $page->assign('locale', $locale);
197
+        $page->assign('direction', $direction);
198
+
199
+        // Set body data-theme
200
+        try {
201
+            $themesService = Server::get(\OCA\Theming\Service\ThemesService::class);
202
+        } catch (\Exception) {
203
+            $themesService = null;
204
+        }
205
+        $page->assign('enabledThemes', $themesService?->getEnabledThemes() ?? []);
206
+
207
+        if ($this->config->getSystemValueBool('installed', false)) {
208
+            if (empty(self::$versionHash)) {
209
+                $v = $this->appManager->getAppInstalledVersions(true);
210
+                $v['core'] = implode('.', $this->serverVersion->getVersion());
211
+                self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
212
+            }
213
+        } else {
214
+            self::$versionHash = md5('not installed');
215
+        }
216
+
217
+        // Add the js files
218
+        $jsFiles = $this->findJavascriptFiles(Util::getScripts());
219
+        $page->assign('jsfiles', []);
220
+        if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
221
+            // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
222
+            // see https://github.com/nextcloud/server/pull/22636 for details
223
+            $jsConfigHelper = new JSConfigHelper(
224
+                $this->serverVersion,
225
+                \OCP\Util::getL10N('lib'),
226
+                \OCP\Server::get(Defaults::class),
227
+                $this->appManager,
228
+                \OC::$server->getSession(),
229
+                \OC::$server->getUserSession()->getUser(),
230
+                $this->config,
231
+                $this->appConfig,
232
+                \OC::$server->getGroupManager(),
233
+                \OC::$server->get(IniGetWrapper::class),
234
+                \OC::$server->getURLGenerator(),
235
+                \OC::$server->get(CapabilitiesManager::class),
236
+                \OCP\Server::get(IInitialStateService::class),
237
+                \OCP\Server::get(IProvider::class),
238
+                \OCP\Server::get(FilenameValidator::class),
239
+            );
240
+            $config = $jsConfigHelper->getConfig();
241
+            if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
242
+                $page->assign('inline_ocjs', $config);
243
+            } else {
244
+                $page->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
245
+            }
246
+        }
247
+        foreach ($jsFiles as $info) {
248
+            $web = $info[1];
249
+            $file = $info[2];
250
+            $page->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix());
251
+        }
252
+
253
+        $request = \OCP\Server::get(IRequest::class);
254
+
255
+        try {
256
+            $pathInfo = $request->getPathInfo();
257
+        } catch (\Exception $e) {
258
+            $pathInfo = '';
259
+        }
260
+
261
+        // Do not initialise scss appdata until we have a fully installed instance
262
+        // Do not load scss for update, errors, installation or login page
263
+        if ($this->config->getSystemValueBool('installed', false)
264
+            && !\OCP\Util::needUpgrade()
265
+            && $pathInfo !== ''
266
+            && !preg_match('/^\/login/', $pathInfo)
267
+            && $renderAs !== TemplateResponse::RENDER_AS_ERROR
268
+        ) {
269
+            $cssFiles = $this->findStylesheetFiles(\OC_Util::$styles);
270
+        } else {
271
+            // If we ignore the scss compiler,
272
+            // we need to load the guest css fallback
273
+            Util::addStyle('guest');
274
+            $cssFiles = $this->findStylesheetFiles(\OC_Util::$styles);
275
+        }
276
+
277
+        $page->assign('cssfiles', []);
278
+        $page->assign('printcssfiles', []);
279
+        $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
280
+        foreach ($cssFiles as $info) {
281
+            $web = $info[1];
282
+            $file = $info[2];
283
+
284
+            if (str_ends_with($file, 'print.css')) {
285
+                $page->append('printcssfiles', $web . '/' . $file . $this->getVersionHashSuffix());
286
+            } else {
287
+                $suffix = $this->getVersionHashSuffix($web, $file);
288
+
289
+                if (!str_contains($file, '?v=')) {
290
+                    $page->append('cssfiles', $web . '/' . $file . $suffix);
291
+                } else {
292
+                    $page->append('cssfiles', $web . '/' . $file . '-' . substr($suffix, 3));
293
+                }
294
+            }
295
+        }
296
+
297
+        if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
298
+            // Prevent auto zoom with iOS but still allow user zoom
299
+            // On chrome (and others) this does not work (will also disable user zoom)
300
+            $page->assign('viewport_maximum_scale', '1.0');
301
+        }
302
+
303
+        $page->assign('initialStates', $this->initialState->getInitialStates());
304
+
305
+        $page->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
306
+        $page->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
307
+
308
+        return $page;
309
+    }
310
+
311
+    protected function getVersionHashSuffix(string $path = '', string $file = ''): string {
312
+        if ($this->config->getSystemValueBool('debug', false)) {
313
+            // allows chrome workspace mapping in debug mode
314
+            return '';
315
+        }
316
+
317
+        if ($this->config->getSystemValueBool('installed', false) === false) {
318
+            // if not installed just return the version hash
319
+            return '?v=' . self::$versionHash;
320
+        }
321
+
322
+        $hash = false;
323
+        // Try the web-root first
324
+        if ($path !== '') {
325
+            $hash = $this->getVersionHashByPath($path);
326
+        }
327
+        // If not found try the file
328
+        if ($hash === false && $file !== '') {
329
+            $hash = $this->getVersionHashByPath($file);
330
+        }
331
+        // As a last resort we use the server version hash
332
+        if ($hash === false) {
333
+            $hash = self::$versionHash;
334
+        }
335
+
336
+        // The theming app is force-enabled thus the cache buster is always available
337
+        $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
338
+
339
+        return '?v=' . $hash . $themingSuffix;
340
+    }
341
+
342
+    private function getVersionHashByPath(string $path): string|false {
343
+        if (array_key_exists($path, self::$cacheBusterCache) === false) {
344
+            // Not yet cached, so lets find the cache buster string
345
+            $appId = $this->getAppNamefromPath($path);
346
+            if ($appId === false) {
347
+                // No app Id could be guessed
348
+                return false;
349
+            }
350
+
351
+            if ($appId === 'core') {
352
+                // core is not a real app but the server itself
353
+                $hash = self::$versionHash;
354
+            } else {
355
+                $appVersion = $this->appManager->getAppVersion($appId);
356
+                // For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
357
+                if ($this->appManager->isShipped($appId)) {
358
+                    $appVersion .= '-' . self::$versionHash;
359
+                }
360
+
361
+                $hash = substr(md5($appVersion), 0, 8);
362
+            }
363
+            self::$cacheBusterCache[$path] = $hash;
364
+        }
365
+
366
+        return self::$cacheBusterCache[$path];
367
+    }
368
+
369
+    private function findStylesheetFiles(array $styles): array {
370
+        if ($this->cssLocator === null) {
371
+            $this->cssLocator = \OCP\Server::get(CSSResourceLocator::class);
372
+        }
373
+        $this->cssLocator->find($styles);
374
+        return $this->cssLocator->getResources();
375
+    }
376
+
377
+    public function getAppNamefromPath(string $path): string|false {
378
+        if ($path !== '') {
379
+            $pathParts = explode('/', $path);
380
+            if ($pathParts[0] === 'css') {
381
+                // This is a scss request
382
+                return $pathParts[1];
383
+            } elseif ($pathParts[0] === 'core') {
384
+                return 'core';
385
+            }
386
+            return end($pathParts);
387
+        }
388
+        return false;
389
+    }
390
+
391
+    private function findJavascriptFiles(array $scripts): array {
392
+        if ($this->jsLocator === null) {
393
+            $this->jsLocator = \OCP\Server::get(JSResourceLocator::class);
394
+        }
395
+        $this->jsLocator->find($scripts);
396
+        return $this->jsLocator->getResources();
397
+    }
398
+
399
+    /**
400
+     * Converts the absolute file path to a relative path from \OC::$SERVERROOT
401
+     * @param string $filePath Absolute path
402
+     * @return string Relative path
403
+     * @throws \Exception If $filePath is not under \OC::$SERVERROOT
404
+     */
405
+    public static function convertToRelativePath(string $filePath) {
406
+        $relativePath = explode(\OC::$SERVERROOT, $filePath);
407
+        if (count($relativePath) !== 2) {
408
+            throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
409
+        }
410
+
411
+        return $relativePath[1];
412
+    }
413 413
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		switch ($renderAs) {
69 69
 			case TemplateResponse::RENDER_AS_USER:
70 70
 				$page = $this->templateManager->getTemplate('core', 'layout.user');
71
-				if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
71
+				if (in_array(\OC_App::getCurrentApp(), ['settings', 'admin', 'help']) !== false) {
72 72
 					$page->assign('bodyid', 'body-settings');
73 73
 				} else {
74 74
 					$page->assign('bodyid', 'body-user');
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 				$this->initialState->provideInitialState('unified-search', 'min-search-length', $this->appConfig->getValueInt(Application::APP_ID, ConfigLexicon::UNIFIED_SEARCH_MIN_SEARCH_LENGTH));
81 81
 				if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
82
-					$this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
82
+					$this->initialState->provideInitialState('unified-search', 'limit-default', (int) $this->config->getAppValue('core', 'unified-search.limit-default', (string) SearchQuery::LIMIT_DEFAULT));
83 83
 					$this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
84 84
 					Util::addScript('core', 'legacy-unified-search', 'core');
85 85
 				} else {
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 		foreach ($jsFiles as $info) {
248 248
 			$web = $info[1];
249 249
 			$file = $info[2];
250
-			$page->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix());
250
+			$page->append('jsfiles', $web.'/'.$file.$this->getVersionHashSuffix());
251 251
 		}
252 252
 
253 253
 		$request = \OCP\Server::get(IRequest::class);
@@ -282,14 +282,14 @@  discard block
 block discarded – undo
282 282
 			$file = $info[2];
283 283
 
284 284
 			if (str_ends_with($file, 'print.css')) {
285
-				$page->append('printcssfiles', $web . '/' . $file . $this->getVersionHashSuffix());
285
+				$page->append('printcssfiles', $web.'/'.$file.$this->getVersionHashSuffix());
286 286
 			} else {
287 287
 				$suffix = $this->getVersionHashSuffix($web, $file);
288 288
 
289 289
 				if (!str_contains($file, '?v=')) {
290
-					$page->append('cssfiles', $web . '/' . $file . $suffix);
290
+					$page->append('cssfiles', $web.'/'.$file.$suffix);
291 291
 				} else {
292
-					$page->append('cssfiles', $web . '/' . $file . '-' . substr($suffix, 3));
292
+					$page->append('cssfiles', $web.'/'.$file.'-'.substr($suffix, 3));
293 293
 				}
294 294
 			}
295 295
 		}
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 
317 317
 		if ($this->config->getSystemValueBool('installed', false) === false) {
318 318
 			// if not installed just return the version hash
319
-			return '?v=' . self::$versionHash;
319
+			return '?v='.self::$versionHash;
320 320
 		}
321 321
 
322 322
 		$hash = false;
@@ -334,12 +334,12 @@  discard block
 block discarded – undo
334 334
 		}
335 335
 
336 336
 		// The theming app is force-enabled thus the cache buster is always available
337
-		$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
337
+		$themingSuffix = '-'.$this->config->getAppValue('theming', 'cachebuster', '0');
338 338
 
339
-		return '?v=' . $hash . $themingSuffix;
339
+		return '?v='.$hash.$themingSuffix;
340 340
 	}
341 341
 
342
-	private function getVersionHashByPath(string $path): string|false {
342
+	private function getVersionHashByPath(string $path): string | false {
343 343
 		if (array_key_exists($path, self::$cacheBusterCache) === false) {
344 344
 			// Not yet cached, so lets find the cache buster string
345 345
 			$appId = $this->getAppNamefromPath($path);
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 				$appVersion = $this->appManager->getAppVersion($appId);
356 356
 				// For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
357 357
 				if ($this->appManager->isShipped($appId)) {
358
-					$appVersion .= '-' . self::$versionHash;
358
+					$appVersion .= '-'.self::$versionHash;
359 359
 				}
360 360
 
361 361
 				$hash = substr(md5($appVersion), 0, 8);
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 		return $this->cssLocator->getResources();
375 375
 	}
376 376
 
377
-	public function getAppNamefromPath(string $path): string|false {
377
+	public function getAppNamefromPath(string $path): string | false {
378 378
 		if ($path !== '') {
379 379
 			$pathParts = explode('/', $path);
380 380
 			if ($pathParts[0] === 'css') {
Please login to merge, or discard this patch.
lib/private/L10N/L10N.php 1 patch
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -15,211 +15,211 @@
 block discarded – undo
15 15
 use Symfony\Component\Translation\IdentityTranslator;
16 16
 
17 17
 class L10N implements IL10N {
18
-	/** @var IFactory */
19
-	protected $factory;
20
-
21
-	/** @var string App of this object */
22
-	protected $app;
23
-
24
-	/** @var string Language of this object */
25
-	protected $lang;
26
-
27
-	/** @var string Locale of this object */
28
-	protected $locale;
29
-
30
-	/** @var IdentityTranslator */
31
-	private $identityTranslator;
32
-
33
-	/** @var string[] */
34
-	private $translations = [];
35
-
36
-	/**
37
-	 * @param IFactory $factory
38
-	 * @param string $app
39
-	 * @param string $lang
40
-	 * @param string $locale
41
-	 * @param array $files
42
-	 */
43
-	public function __construct(IFactory $factory, $app, $lang, $locale, array $files) {
44
-		$this->factory = $factory;
45
-		$this->app = $app;
46
-		$this->lang = $lang;
47
-		$this->locale = $locale;
48
-
49
-		foreach ($files as $languageFile) {
50
-			$this->load($languageFile);
51
-		}
52
-	}
53
-
54
-	/**
55
-	 * The code (en, de, ...) of the language that is used for this instance
56
-	 *
57
-	 * @return string language
58
-	 */
59
-	public function getLanguageCode(): string {
60
-		return $this->lang;
61
-	}
62
-
63
-	/**
64
-	 * The code (en_US, fr_CA, ...) of the locale that is used for this instance
65
-	 *
66
-	 * @return string locale
67
-	 */
68
-	public function getLocaleCode(): string {
69
-		return $this->locale;
70
-	}
71
-
72
-	/**
73
-	 * Translating
74
-	 * @param string $text The text we need a translation for
75
-	 * @param array|string $parameters default:array() Parameters for sprintf
76
-	 * @return string Translation or the same text
77
-	 *
78
-	 * Returns the translation. If no translation is found, $text will be
79
-	 * returned.
80
-	 */
81
-	public function t(string $text, $parameters = []): string {
82
-		if (!\is_array($parameters)) {
83
-			$parameters = [$parameters];
84
-		}
85
-
86
-		return (string)new L10NString($this, $text, $parameters);
87
-	}
88
-
89
-	/**
90
-	 * Translating
91
-	 * @param string $text_singular the string to translate for exactly one object
92
-	 * @param string $text_plural the string to translate for n objects
93
-	 * @param integer $count Number of objects
94
-	 * @param array $parameters default:array() Parameters for sprintf
95
-	 * @return string Translation or the same text
96
-	 *
97
-	 * Returns the translation. If no translation is found, $text will be
98
-	 * returned. %n will be replaced with the number of objects.
99
-	 *
100
-	 * The correct plural is determined by the plural_forms-function
101
-	 * provided by the po file.
102
-	 *
103
-	 */
104
-	public function n(string $text_singular, string $text_plural, int $count, array $parameters = []): string {
105
-		$identifier = "_{$text_singular}_::_{$text_plural}_";
106
-		if (isset($this->translations[$identifier])) {
107
-			return (string)new L10NString($this, $identifier, $parameters, $count);
108
-		}
109
-
110
-		if ($count === 1) {
111
-			return (string)new L10NString($this, $text_singular, $parameters, $count);
112
-		}
113
-
114
-		return (string)new L10NString($this, $text_plural, $parameters, $count);
115
-	}
116
-
117
-	/**
118
-	 * Localization
119
-	 * @param string $type Type of localization
120
-	 * @param \DateTime|int|string|null $data parameters for this localization
121
-	 * @param array $options
122
-	 * @return string|int|false
123
-	 *
124
-	 * Returns the localized data.
125
-	 *
126
-	 * Implemented types:
127
-	 *  - date
128
-	 *    - Creates a date
129
-	 *    - params: timestamp (int/string)
130
-	 *  - datetime
131
-	 *    - Creates date and time
132
-	 *    - params: timestamp (int/string)
133
-	 *  - time
134
-	 *    - Creates a time
135
-	 *    - params: timestamp (int/string)
136
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
137
-	 *  - jsdate: Returns the short JS date format
138
-	 */
139
-	public function l(string $type, $data = null, array $options = []) {
140
-		if ($this->locale === null) {
141
-			// Use the language of the instance
142
-			$this->locale = $this->getLanguageCode();
143
-		}
144
-		if ($this->locale === 'sr@latin') {
145
-			$this->locale = 'sr_latn';
146
-		}
147
-
148
-		if ($type === 'firstday') {
149
-			return (int)Calendar::getFirstWeekday($this->locale);
150
-		}
151
-		if ($type === 'jsdate') {
152
-			return (string)Calendar::getDateFormat('short', $this->locale);
153
-		}
154
-
155
-		$value = new \DateTime();
156
-		if ($data instanceof \DateTime) {
157
-			$value = $data;
158
-		} elseif (\is_string($data) && !is_numeric($data)) {
159
-			$data = strtotime($data);
160
-			$value->setTimestamp($data);
161
-		} elseif ($data !== null) {
162
-			$data = (int)$data;
163
-			$value->setTimestamp($data);
164
-		}
165
-
166
-		$options = array_merge(['width' => 'long'], $options);
167
-		$width = $options['width'];
168
-		switch ($type) {
169
-			case 'date':
170
-				return (string)Calendar::formatDate($value, $width, $this->locale);
171
-			case 'datetime':
172
-				return (string)Calendar::formatDatetime($value, $width, $this->locale);
173
-			case 'time':
174
-				return (string)Calendar::formatTime($value, $width, $this->locale);
175
-			case 'weekdayName':
176
-				return (string)Calendar::getWeekdayName($value, $width, $this->locale);
177
-			default:
178
-				return false;
179
-		}
180
-	}
181
-
182
-	/**
183
-	 * Returns an associative array with all translations
184
-	 *
185
-	 * Called by \OC_L10N_String
186
-	 * @return array
187
-	 */
188
-	public function getTranslations(): array {
189
-		return $this->translations;
190
-	}
191
-
192
-	/**
193
-	 * @internal
194
-	 * @return IdentityTranslator
195
-	 */
196
-	public function getIdentityTranslator(): IdentityTranslator {
197
-		if (\is_null($this->identityTranslator)) {
198
-			$this->identityTranslator = new IdentityTranslator();
199
-			// We need to use the language code here instead of the locale,
200
-			// because Symfony does not distinguish between the two and would
201
-			// otherwise e.g. with locale "Czech" and language "German" try to
202
-			// pick a non-existing plural rule, because Czech has 4 plural forms
203
-			// and German only 2.
204
-			$this->identityTranslator->setLocale($this->getLanguageCode());
205
-		}
206
-
207
-		return $this->identityTranslator;
208
-	}
209
-
210
-	/**
211
-	 * @param string $translationFile
212
-	 * @return bool
213
-	 */
214
-	protected function load(string $translationFile): bool {
215
-		$json = json_decode(file_get_contents($translationFile), true);
216
-		if (!\is_array($json)) {
217
-			$jsonError = json_last_error();
218
-			\OCP\Server::get(LoggerInterface::class)->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
219
-			return false;
220
-		}
221
-
222
-		$this->translations = array_merge($this->translations, $json['translations']);
223
-		return true;
224
-	}
18
+    /** @var IFactory */
19
+    protected $factory;
20
+
21
+    /** @var string App of this object */
22
+    protected $app;
23
+
24
+    /** @var string Language of this object */
25
+    protected $lang;
26
+
27
+    /** @var string Locale of this object */
28
+    protected $locale;
29
+
30
+    /** @var IdentityTranslator */
31
+    private $identityTranslator;
32
+
33
+    /** @var string[] */
34
+    private $translations = [];
35
+
36
+    /**
37
+     * @param IFactory $factory
38
+     * @param string $app
39
+     * @param string $lang
40
+     * @param string $locale
41
+     * @param array $files
42
+     */
43
+    public function __construct(IFactory $factory, $app, $lang, $locale, array $files) {
44
+        $this->factory = $factory;
45
+        $this->app = $app;
46
+        $this->lang = $lang;
47
+        $this->locale = $locale;
48
+
49
+        foreach ($files as $languageFile) {
50
+            $this->load($languageFile);
51
+        }
52
+    }
53
+
54
+    /**
55
+     * The code (en, de, ...) of the language that is used for this instance
56
+     *
57
+     * @return string language
58
+     */
59
+    public function getLanguageCode(): string {
60
+        return $this->lang;
61
+    }
62
+
63
+    /**
64
+     * The code (en_US, fr_CA, ...) of the locale that is used for this instance
65
+     *
66
+     * @return string locale
67
+     */
68
+    public function getLocaleCode(): string {
69
+        return $this->locale;
70
+    }
71
+
72
+    /**
73
+     * Translating
74
+     * @param string $text The text we need a translation for
75
+     * @param array|string $parameters default:array() Parameters for sprintf
76
+     * @return string Translation or the same text
77
+     *
78
+     * Returns the translation. If no translation is found, $text will be
79
+     * returned.
80
+     */
81
+    public function t(string $text, $parameters = []): string {
82
+        if (!\is_array($parameters)) {
83
+            $parameters = [$parameters];
84
+        }
85
+
86
+        return (string)new L10NString($this, $text, $parameters);
87
+    }
88
+
89
+    /**
90
+     * Translating
91
+     * @param string $text_singular the string to translate for exactly one object
92
+     * @param string $text_plural the string to translate for n objects
93
+     * @param integer $count Number of objects
94
+     * @param array $parameters default:array() Parameters for sprintf
95
+     * @return string Translation or the same text
96
+     *
97
+     * Returns the translation. If no translation is found, $text will be
98
+     * returned. %n will be replaced with the number of objects.
99
+     *
100
+     * The correct plural is determined by the plural_forms-function
101
+     * provided by the po file.
102
+     *
103
+     */
104
+    public function n(string $text_singular, string $text_plural, int $count, array $parameters = []): string {
105
+        $identifier = "_{$text_singular}_::_{$text_plural}_";
106
+        if (isset($this->translations[$identifier])) {
107
+            return (string)new L10NString($this, $identifier, $parameters, $count);
108
+        }
109
+
110
+        if ($count === 1) {
111
+            return (string)new L10NString($this, $text_singular, $parameters, $count);
112
+        }
113
+
114
+        return (string)new L10NString($this, $text_plural, $parameters, $count);
115
+    }
116
+
117
+    /**
118
+     * Localization
119
+     * @param string $type Type of localization
120
+     * @param \DateTime|int|string|null $data parameters for this localization
121
+     * @param array $options
122
+     * @return string|int|false
123
+     *
124
+     * Returns the localized data.
125
+     *
126
+     * Implemented types:
127
+     *  - date
128
+     *    - Creates a date
129
+     *    - params: timestamp (int/string)
130
+     *  - datetime
131
+     *    - Creates date and time
132
+     *    - params: timestamp (int/string)
133
+     *  - time
134
+     *    - Creates a time
135
+     *    - params: timestamp (int/string)
136
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
137
+     *  - jsdate: Returns the short JS date format
138
+     */
139
+    public function l(string $type, $data = null, array $options = []) {
140
+        if ($this->locale === null) {
141
+            // Use the language of the instance
142
+            $this->locale = $this->getLanguageCode();
143
+        }
144
+        if ($this->locale === 'sr@latin') {
145
+            $this->locale = 'sr_latn';
146
+        }
147
+
148
+        if ($type === 'firstday') {
149
+            return (int)Calendar::getFirstWeekday($this->locale);
150
+        }
151
+        if ($type === 'jsdate') {
152
+            return (string)Calendar::getDateFormat('short', $this->locale);
153
+        }
154
+
155
+        $value = new \DateTime();
156
+        if ($data instanceof \DateTime) {
157
+            $value = $data;
158
+        } elseif (\is_string($data) && !is_numeric($data)) {
159
+            $data = strtotime($data);
160
+            $value->setTimestamp($data);
161
+        } elseif ($data !== null) {
162
+            $data = (int)$data;
163
+            $value->setTimestamp($data);
164
+        }
165
+
166
+        $options = array_merge(['width' => 'long'], $options);
167
+        $width = $options['width'];
168
+        switch ($type) {
169
+            case 'date':
170
+                return (string)Calendar::formatDate($value, $width, $this->locale);
171
+            case 'datetime':
172
+                return (string)Calendar::formatDatetime($value, $width, $this->locale);
173
+            case 'time':
174
+                return (string)Calendar::formatTime($value, $width, $this->locale);
175
+            case 'weekdayName':
176
+                return (string)Calendar::getWeekdayName($value, $width, $this->locale);
177
+            default:
178
+                return false;
179
+        }
180
+    }
181
+
182
+    /**
183
+     * Returns an associative array with all translations
184
+     *
185
+     * Called by \OC_L10N_String
186
+     * @return array
187
+     */
188
+    public function getTranslations(): array {
189
+        return $this->translations;
190
+    }
191
+
192
+    /**
193
+     * @internal
194
+     * @return IdentityTranslator
195
+     */
196
+    public function getIdentityTranslator(): IdentityTranslator {
197
+        if (\is_null($this->identityTranslator)) {
198
+            $this->identityTranslator = new IdentityTranslator();
199
+            // We need to use the language code here instead of the locale,
200
+            // because Symfony does not distinguish between the two and would
201
+            // otherwise e.g. with locale "Czech" and language "German" try to
202
+            // pick a non-existing plural rule, because Czech has 4 plural forms
203
+            // and German only 2.
204
+            $this->identityTranslator->setLocale($this->getLanguageCode());
205
+        }
206
+
207
+        return $this->identityTranslator;
208
+    }
209
+
210
+    /**
211
+     * @param string $translationFile
212
+     * @return bool
213
+     */
214
+    protected function load(string $translationFile): bool {
215
+        $json = json_decode(file_get_contents($translationFile), true);
216
+        if (!\is_array($json)) {
217
+            $jsonError = json_last_error();
218
+            \OCP\Server::get(LoggerInterface::class)->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
219
+            return false;
220
+        }
221
+
222
+        $this->translations = array_merge($this->translations, $json['translations']);
223
+        return true;
224
+    }
225 225
 }
Please login to merge, or discard this patch.
lib/private/Template/CSSResourceLocator.php 2 patches
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -16,76 +16,76 @@
 block discarded – undo
16 16
 use Psr\Log\LoggerInterface;
17 17
 
18 18
 class CSSResourceLocator extends ResourceLocator {
19
-	public function __construct(
20
-		LoggerInterface $logger,
21
-		IConfig $config,
22
-		protected IAppManager $appManager,
23
-	) {
24
-		parent::__construct($logger, $config);
25
-	}
19
+    public function __construct(
20
+        LoggerInterface $logger,
21
+        IConfig $config,
22
+        protected IAppManager $appManager,
23
+    ) {
24
+        parent::__construct($logger, $config);
25
+    }
26 26
 
27
-	public function doFind(string $resource): void {
28
-		$parts = explode('/', $resource, 2);
29
-		if (count($parts) < 2) {
30
-			return;
31
-		}
32
-		[$app,$subpath] = $parts;
33
-		if ($this->appendIfExist($this->serverroot, $resource . '.css')
34
-			|| $this->appendIfExist($this->serverroot, 'core/' . $resource . '.css')
35
-		) {
36
-			return;
37
-		}
38
-		try {
39
-			$app_path = $this->appManager->getAppPath($app);
40
-			$app_url = $this->appManager->getAppWebPath($app);
41
-		} catch (AppPathNotFoundException $e) {
42
-			$this->logger->error('Could not find resource {resource} to load', [
43
-				'resource' => $app . '/' . $subpath . '.css',
44
-				'app' => 'cssresourceloader',
45
-				'exception' => $e,
46
-			]);
47
-			return;
48
-		}
27
+    public function doFind(string $resource): void {
28
+        $parts = explode('/', $resource, 2);
29
+        if (count($parts) < 2) {
30
+            return;
31
+        }
32
+        [$app,$subpath] = $parts;
33
+        if ($this->appendIfExist($this->serverroot, $resource . '.css')
34
+            || $this->appendIfExist($this->serverroot, 'core/' . $resource . '.css')
35
+        ) {
36
+            return;
37
+        }
38
+        try {
39
+            $app_path = $this->appManager->getAppPath($app);
40
+            $app_url = $this->appManager->getAppWebPath($app);
41
+        } catch (AppPathNotFoundException $e) {
42
+            $this->logger->error('Could not find resource {resource} to load', [
43
+                'resource' => $app . '/' . $subpath . '.css',
44
+                'app' => 'cssresourceloader',
45
+                'exception' => $e,
46
+            ]);
47
+            return;
48
+        }
49 49
 
50
-		// Account for the possibility of having symlinks in app path. Doing
51
-		// this here instead of above as an empty argument to realpath gets
52
-		// turned into cwd.
53
-		$app_path = realpath($app_path);
50
+        // Account for the possibility of having symlinks in app path. Doing
51
+        // this here instead of above as an empty argument to realpath gets
52
+        // turned into cwd.
53
+        $app_path = realpath($app_path);
54 54
 
55
-		$this->append($app_path, $subpath . '.css', $app_url);
56
-	}
55
+        $this->append($app_path, $subpath . '.css', $app_url);
56
+    }
57 57
 
58
-	public function doFindTheme(string $resource): void {
59
-		$theme_dir = 'themes/' . $this->theme . '/';
60
-		$this->appendIfExist($this->serverroot, $theme_dir . 'apps/' . $resource . '.css')
61
-			|| $this->appendIfExist($this->serverroot, $theme_dir . $resource . '.css')
62
-			|| $this->appendIfExist($this->serverroot, $theme_dir . 'core/' . $resource . '.css');
63
-	}
58
+    public function doFindTheme(string $resource): void {
59
+        $theme_dir = 'themes/' . $this->theme . '/';
60
+        $this->appendIfExist($this->serverroot, $theme_dir . 'apps/' . $resource . '.css')
61
+            || $this->appendIfExist($this->serverroot, $theme_dir . $resource . '.css')
62
+            || $this->appendIfExist($this->serverroot, $theme_dir . 'core/' . $resource . '.css');
63
+    }
64 64
 
65
-	public function append(string $root, string $file, ?string $webRoot = null, bool $throw = true, bool $scss = false): void {
66
-		if (!$scss) {
67
-			parent::append($root, $file, $webRoot, $throw);
68
-		} else {
69
-			if ($webRoot === null || $webRoot === '') {
70
-				$webRoot = $this->findWebRoot($root);
65
+    public function append(string $root, string $file, ?string $webRoot = null, bool $throw = true, bool $scss = false): void {
66
+        if (!$scss) {
67
+            parent::append($root, $file, $webRoot, $throw);
68
+        } else {
69
+            if ($webRoot === null || $webRoot === '') {
70
+                $webRoot = $this->findWebRoot($root);
71 71
 
72
-				if ($webRoot === null) {
73
-					$webRoot = '';
74
-					$this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
75
-						'app' => 'lib',
76
-						'root' => $root,
77
-						'file' => $file,
78
-						'webRoot' => $webRoot,
79
-						'throw' => $throw ? 'true' : 'false'
80
-					]);
72
+                if ($webRoot === null) {
73
+                    $webRoot = '';
74
+                    $this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
75
+                        'app' => 'lib',
76
+                        'root' => $root,
77
+                        'file' => $file,
78
+                        'webRoot' => $webRoot,
79
+                        'throw' => $throw ? 'true' : 'false'
80
+                    ]);
81 81
 
82
-					if ($throw && $root === '/') {
83
-						throw new ResourceNotFoundException($file, $webRoot);
84
-					}
85
-				}
86
-			}
82
+                    if ($throw && $root === '/') {
83
+                        throw new ResourceNotFoundException($file, $webRoot);
84
+                    }
85
+                }
86
+            }
87 87
 
88
-			$this->resources[] = [$webRoot ?: \OC::$WEBROOT, $webRoot, $file];
89
-		}
90
-	}
88
+            $this->resources[] = [$webRoot ?: \OC::$WEBROOT, $webRoot, $file];
89
+        }
90
+    }
91 91
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -29,9 +29,9 @@  discard block
 block discarded – undo
29 29
 		if (count($parts) < 2) {
30 30
 			return;
31 31
 		}
32
-		[$app,$subpath] = $parts;
33
-		if ($this->appendIfExist($this->serverroot, $resource . '.css')
34
-			|| $this->appendIfExist($this->serverroot, 'core/' . $resource . '.css')
32
+		[$app, $subpath] = $parts;
33
+		if ($this->appendIfExist($this->serverroot, $resource.'.css')
34
+			|| $this->appendIfExist($this->serverroot, 'core/'.$resource.'.css')
35 35
 		) {
36 36
 			return;
37 37
 		}
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 			$app_url = $this->appManager->getAppWebPath($app);
41 41
 		} catch (AppPathNotFoundException $e) {
42 42
 			$this->logger->error('Could not find resource {resource} to load', [
43
-				'resource' => $app . '/' . $subpath . '.css',
43
+				'resource' => $app.'/'.$subpath.'.css',
44 44
 				'app' => 'cssresourceloader',
45 45
 				'exception' => $e,
46 46
 			]);
@@ -52,14 +52,14 @@  discard block
 block discarded – undo
52 52
 		// turned into cwd.
53 53
 		$app_path = realpath($app_path);
54 54
 
55
-		$this->append($app_path, $subpath . '.css', $app_url);
55
+		$this->append($app_path, $subpath.'.css', $app_url);
56 56
 	}
57 57
 
58 58
 	public function doFindTheme(string $resource): void {
59
-		$theme_dir = 'themes/' . $this->theme . '/';
60
-		$this->appendIfExist($this->serverroot, $theme_dir . 'apps/' . $resource . '.css')
61
-			|| $this->appendIfExist($this->serverroot, $theme_dir . $resource . '.css')
62
-			|| $this->appendIfExist($this->serverroot, $theme_dir . 'core/' . $resource . '.css');
59
+		$theme_dir = 'themes/'.$this->theme.'/';
60
+		$this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$resource.'.css')
61
+			|| $this->appendIfExist($this->serverroot, $theme_dir.$resource.'.css')
62
+			|| $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$resource.'.css');
63 63
 	}
64 64
 
65 65
 	public function append(string $root, string $file, ?string $webRoot = null, bool $throw = true, bool $scss = false): void {
Please login to merge, or discard this patch.