Passed
Push — master ( 3231b3...73e3d0 )
by John
12:14 queued 12s
created
apps/theming/lib/ImageManager.php 2 patches
Indentation   +242 added lines, -242 removed lines patch added patch discarded remove patch
@@ -46,271 +46,271 @@
 block discarded – undo
46 46
 
47 47
 class ImageManager {
48 48
 
49
-	/** @var IConfig */
50
-	private $config;
51
-	/** @var IAppData */
52
-	private $appData;
53
-	/** @var IURLGenerator */
54
-	private $urlGenerator;
55
-	/** @var array */
56
-	private $supportedImageKeys = ['background', 'logo', 'logoheader', 'favicon'];
57
-	/** @var ICacheFactory */
58
-	private $cacheFactory;
59
-	/** @var ILogger */
60
-	private $logger;
61
-	/** @var ITempManager */
62
-	private $tempManager;
49
+    /** @var IConfig */
50
+    private $config;
51
+    /** @var IAppData */
52
+    private $appData;
53
+    /** @var IURLGenerator */
54
+    private $urlGenerator;
55
+    /** @var array */
56
+    private $supportedImageKeys = ['background', 'logo', 'logoheader', 'favicon'];
57
+    /** @var ICacheFactory */
58
+    private $cacheFactory;
59
+    /** @var ILogger */
60
+    private $logger;
61
+    /** @var ITempManager */
62
+    private $tempManager;
63 63
 
64
-	public function __construct(IConfig $config,
65
-								IAppData $appData,
66
-								IURLGenerator $urlGenerator,
67
-								ICacheFactory $cacheFactory,
68
-								ILogger $logger,
69
-								ITempManager $tempManager
70
-	) {
71
-		$this->config = $config;
72
-		$this->appData = $appData;
73
-		$this->urlGenerator = $urlGenerator;
74
-		$this->cacheFactory = $cacheFactory;
75
-		$this->logger = $logger;
76
-		$this->tempManager = $tempManager;
77
-	}
64
+    public function __construct(IConfig $config,
65
+                                IAppData $appData,
66
+                                IURLGenerator $urlGenerator,
67
+                                ICacheFactory $cacheFactory,
68
+                                ILogger $logger,
69
+                                ITempManager $tempManager
70
+    ) {
71
+        $this->config = $config;
72
+        $this->appData = $appData;
73
+        $this->urlGenerator = $urlGenerator;
74
+        $this->cacheFactory = $cacheFactory;
75
+        $this->logger = $logger;
76
+        $this->tempManager = $tempManager;
77
+    }
78 78
 
79
-	public function getImageUrl(string $key, bool $useSvg = true): string {
80
-		$cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
81
-		try {
82
-			$image = $this->getImage($key, $useSvg);
83
-			return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
84
-		} catch (NotFoundException $e) {
85
-		}
79
+    public function getImageUrl(string $key, bool $useSvg = true): string {
80
+        $cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
81
+        try {
82
+            $image = $this->getImage($key, $useSvg);
83
+            return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
84
+        } catch (NotFoundException $e) {
85
+        }
86 86
 
87
-		switch ($key) {
88
-			case 'logo':
89
-			case 'logoheader':
90
-			case 'favicon':
91
-				return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
92
-			case 'background':
93
-				return $this->urlGenerator->imagePath('core', 'background.png') . '?v=' . $cacheBusterCounter;
94
-		}
95
-		return '';
96
-	}
87
+        switch ($key) {
88
+            case 'logo':
89
+            case 'logoheader':
90
+            case 'favicon':
91
+                return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
92
+            case 'background':
93
+                return $this->urlGenerator->imagePath('core', 'background.png') . '?v=' . $cacheBusterCounter;
94
+        }
95
+        return '';
96
+    }
97 97
 
98
-	public function getImageUrlAbsolute(string $key, bool $useSvg = true): string {
99
-		return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key, $useSvg));
100
-	}
98
+    public function getImageUrlAbsolute(string $key, bool $useSvg = true): string {
99
+        return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key, $useSvg));
100
+    }
101 101
 
102
-	/**
103
-	 * @param string $key
104
-	 * @param bool $useSvg
105
-	 * @return ISimpleFile
106
-	 * @throws NotFoundException
107
-	 * @throws NotPermittedException
108
-	 */
109
-	public function getImage(string $key, bool $useSvg = true): ISimpleFile {
110
-		$logo = $this->config->getAppValue('theming', $key . 'Mime', '');
111
-		$folder = $this->appData->getFolder('images');
112
-		if ($logo === '' || !$folder->fileExists($key)) {
113
-			throw new NotFoundException();
114
-		}
115
-		if (!$useSvg && $this->shouldReplaceIcons()) {
116
-			if (!$folder->fileExists($key . '.png')) {
117
-				try {
118
-					$finalIconFile = new \Imagick();
119
-					$finalIconFile->setBackgroundColor('none');
120
-					$finalIconFile->readImageBlob($folder->getFile($key)->getContent());
121
-					$finalIconFile->setImageFormat('png32');
122
-					$pngFile = $folder->newFile($key . '.png');
123
-					$pngFile->putContent($finalIconFile->getImageBlob());
124
-					return $pngFile;
125
-				} catch (\ImagickException $e) {
126
-					$this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
127
-				}
128
-			} else {
129
-				return $folder->getFile($key . '.png');
130
-			}
131
-		}
132
-		return $folder->getFile($key);
133
-	}
102
+    /**
103
+     * @param string $key
104
+     * @param bool $useSvg
105
+     * @return ISimpleFile
106
+     * @throws NotFoundException
107
+     * @throws NotPermittedException
108
+     */
109
+    public function getImage(string $key, bool $useSvg = true): ISimpleFile {
110
+        $logo = $this->config->getAppValue('theming', $key . 'Mime', '');
111
+        $folder = $this->appData->getFolder('images');
112
+        if ($logo === '' || !$folder->fileExists($key)) {
113
+            throw new NotFoundException();
114
+        }
115
+        if (!$useSvg && $this->shouldReplaceIcons()) {
116
+            if (!$folder->fileExists($key . '.png')) {
117
+                try {
118
+                    $finalIconFile = new \Imagick();
119
+                    $finalIconFile->setBackgroundColor('none');
120
+                    $finalIconFile->readImageBlob($folder->getFile($key)->getContent());
121
+                    $finalIconFile->setImageFormat('png32');
122
+                    $pngFile = $folder->newFile($key . '.png');
123
+                    $pngFile->putContent($finalIconFile->getImageBlob());
124
+                    return $pngFile;
125
+                } catch (\ImagickException $e) {
126
+                    $this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
127
+                }
128
+            } else {
129
+                return $folder->getFile($key . '.png');
130
+            }
131
+        }
132
+        return $folder->getFile($key);
133
+    }
134 134
 
135
-	/**
136
-	 * @return array<string, array{mime: string, url: string}>
137
-	 */
138
-	public function getCustomImages(): array {
139
-		$images = [];
140
-		foreach ($this->supportedImageKeys as $key) {
141
-			$images[$key] = [
142
-				'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
143
-				'url' => $this->getImageUrl($key),
144
-			];
145
-		}
146
-		return $images;
147
-	}
135
+    /**
136
+     * @return array<string, array{mime: string, url: string}>
137
+     */
138
+    public function getCustomImages(): array {
139
+        $images = [];
140
+        foreach ($this->supportedImageKeys as $key) {
141
+            $images[$key] = [
142
+                'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
143
+                'url' => $this->getImageUrl($key),
144
+            ];
145
+        }
146
+        return $images;
147
+    }
148 148
 
149
-	/**
150
-	 * Get folder for current theming files
151
-	 *
152
-	 * @return ISimpleFolder
153
-	 * @throws NotPermittedException
154
-	 */
155
-	public function getCacheFolder(): ISimpleFolder {
156
-		$cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
157
-		try {
158
-			$folder = $this->appData->getFolder($cacheBusterValue);
159
-		} catch (NotFoundException $e) {
160
-			$folder = $this->appData->newFolder($cacheBusterValue);
161
-			$this->cleanup();
162
-		}
163
-		return $folder;
164
-	}
149
+    /**
150
+     * Get folder for current theming files
151
+     *
152
+     * @return ISimpleFolder
153
+     * @throws NotPermittedException
154
+     */
155
+    public function getCacheFolder(): ISimpleFolder {
156
+        $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
157
+        try {
158
+            $folder = $this->appData->getFolder($cacheBusterValue);
159
+        } catch (NotFoundException $e) {
160
+            $folder = $this->appData->newFolder($cacheBusterValue);
161
+            $this->cleanup();
162
+        }
163
+        return $folder;
164
+    }
165 165
 
166
-	/**
167
-	 * Get a file from AppData
168
-	 *
169
-	 * @param string $filename
170
-	 * @throws NotFoundException
171
-	 * @return \OCP\Files\SimpleFS\ISimpleFile
172
-	 * @throws NotPermittedException
173
-	 */
174
-	public function getCachedImage(string $filename): ISimpleFile {
175
-		$currentFolder = $this->getCacheFolder();
176
-		return $currentFolder->getFile($filename);
177
-	}
166
+    /**
167
+     * Get a file from AppData
168
+     *
169
+     * @param string $filename
170
+     * @throws NotFoundException
171
+     * @return \OCP\Files\SimpleFS\ISimpleFile
172
+     * @throws NotPermittedException
173
+     */
174
+    public function getCachedImage(string $filename): ISimpleFile {
175
+        $currentFolder = $this->getCacheFolder();
176
+        return $currentFolder->getFile($filename);
177
+    }
178 178
 
179
-	/**
180
-	 * Store a file for theming in AppData
181
-	 *
182
-	 * @param string $filename
183
-	 * @param string $data
184
-	 * @return \OCP\Files\SimpleFS\ISimpleFile
185
-	 * @throws NotFoundException
186
-	 * @throws NotPermittedException
187
-	 */
188
-	public function setCachedImage(string $filename, string $data): ISimpleFile {
189
-		$currentFolder = $this->getCacheFolder();
190
-		if ($currentFolder->fileExists($filename)) {
191
-			$file = $currentFolder->getFile($filename);
192
-		} else {
193
-			$file = $currentFolder->newFile($filename);
194
-		}
195
-		$file->putContent($data);
196
-		return $file;
197
-	}
179
+    /**
180
+     * Store a file for theming in AppData
181
+     *
182
+     * @param string $filename
183
+     * @param string $data
184
+     * @return \OCP\Files\SimpleFS\ISimpleFile
185
+     * @throws NotFoundException
186
+     * @throws NotPermittedException
187
+     */
188
+    public function setCachedImage(string $filename, string $data): ISimpleFile {
189
+        $currentFolder = $this->getCacheFolder();
190
+        if ($currentFolder->fileExists($filename)) {
191
+            $file = $currentFolder->getFile($filename);
192
+        } else {
193
+            $file = $currentFolder->newFile($filename);
194
+        }
195
+        $file->putContent($data);
196
+        return $file;
197
+    }
198 198
 
199
-	public function delete(string $key): void {
200
-		/* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
201
-		try {
202
-			$file = $this->appData->getFolder('images')->getFile($key);
203
-			$file->delete();
204
-		} catch (NotFoundException $e) {
205
-		} catch (NotPermittedException $e) {
206
-		}
207
-		try {
208
-			$file = $this->appData->getFolder('images')->getFile($key . '.png');
209
-			$file->delete();
210
-		} catch (NotFoundException $e) {
211
-		} catch (NotPermittedException $e) {
212
-		}
213
-	}
199
+    public function delete(string $key): void {
200
+        /* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
201
+        try {
202
+            $file = $this->appData->getFolder('images')->getFile($key);
203
+            $file->delete();
204
+        } catch (NotFoundException $e) {
205
+        } catch (NotPermittedException $e) {
206
+        }
207
+        try {
208
+            $file = $this->appData->getFolder('images')->getFile($key . '.png');
209
+            $file->delete();
210
+        } catch (NotFoundException $e) {
211
+        } catch (NotPermittedException $e) {
212
+        }
213
+    }
214 214
 
215
-	public function updateImage(string $key, string $tmpFile): string {
216
-		$this->delete($key);
215
+    public function updateImage(string $key, string $tmpFile): string {
216
+        $this->delete($key);
217 217
 
218
-		try {
219
-			$folder = $this->appData->getFolder('images');
220
-		} catch (NotFoundException $e) {
221
-			$folder = $this->appData->newFolder('images');
222
-		}
218
+        try {
219
+            $folder = $this->appData->getFolder('images');
220
+        } catch (NotFoundException $e) {
221
+            $folder = $this->appData->newFolder('images');
222
+        }
223 223
 
224
-		$target = $folder->newFile($key);
225
-		$supportedFormats = $this->getSupportedUploadImageFormats($key);
226
-		$detectedMimeType = mime_content_type($tmpFile);
227
-		if (!in_array($detectedMimeType, $supportedFormats, true)) {
228
-			throw new \Exception('Unsupported image type');
229
-		}
224
+        $target = $folder->newFile($key);
225
+        $supportedFormats = $this->getSupportedUploadImageFormats($key);
226
+        $detectedMimeType = mime_content_type($tmpFile);
227
+        if (!in_array($detectedMimeType, $supportedFormats, true)) {
228
+            throw new \Exception('Unsupported image type');
229
+        }
230 230
 
231
-		if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
232
-			// Optimize the image since some people may upload images that will be
233
-			// either to big or are not progressive rendering.
234
-			$newImage = @imagecreatefromstring(file_get_contents($tmpFile));
231
+        if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
232
+            // Optimize the image since some people may upload images that will be
233
+            // either to big or are not progressive rendering.
234
+            $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
235 235
 
236
-			// Preserve transparency
237
-			imagesavealpha($newImage, true);
238
-			imagealphablending($newImage, true);
236
+            // Preserve transparency
237
+            imagesavealpha($newImage, true);
238
+            imagealphablending($newImage, true);
239 239
 
240
-			$tmpFile = $this->tempManager->getTemporaryFile();
241
-			$newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
242
-			$newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
243
-			$outputImage = imagescale($newImage, $newWidth, $newHeight);
240
+            $tmpFile = $this->tempManager->getTemporaryFile();
241
+            $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
242
+            $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
243
+            $outputImage = imagescale($newImage, $newWidth, $newHeight);
244 244
 
245
-			imageinterlace($outputImage, 1);
246
-			imagepng($outputImage, $tmpFile, 8);
247
-			imagedestroy($outputImage);
245
+            imageinterlace($outputImage, 1);
246
+            imagepng($outputImage, $tmpFile, 8);
247
+            imagedestroy($outputImage);
248 248
 
249
-			$target->putContent(file_get_contents($tmpFile));
250
-		} else {
251
-			$target->putContent(file_get_contents($tmpFile));
252
-		}
249
+            $target->putContent(file_get_contents($tmpFile));
250
+        } else {
251
+            $target->putContent(file_get_contents($tmpFile));
252
+        }
253 253
 
254
-		return $detectedMimeType;
255
-	}
254
+        return $detectedMimeType;
255
+    }
256 256
 
257
-	/**
258
-	 * Returns a list of supported mime types for image uploads.
259
-	 * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
260
-	 *
261
-	 * @param string $key The image key, e.g. "favicon"
262
-	 * @return string[]
263
-	 */
264
-	private function getSupportedUploadImageFormats(string $key): array {
265
-		$supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
257
+    /**
258
+     * Returns a list of supported mime types for image uploads.
259
+     * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
260
+     *
261
+     * @param string $key The image key, e.g. "favicon"
262
+     * @return string[]
263
+     */
264
+    private function getSupportedUploadImageFormats(string $key): array {
265
+        $supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
266 266
 
267
-		if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
268
-			$supportedFormats[] = 'image/svg+xml';
269
-			$supportedFormats[] = 'image/svg';
270
-		}
267
+        if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
268
+            $supportedFormats[] = 'image/svg+xml';
269
+            $supportedFormats[] = 'image/svg';
270
+        }
271 271
 
272
-		if ($key === 'favicon') {
273
-			$supportedFormats[] = 'image/x-icon';
274
-			$supportedFormats[] = 'image/vnd.microsoft.icon';
275
-		}
272
+        if ($key === 'favicon') {
273
+            $supportedFormats[] = 'image/x-icon';
274
+            $supportedFormats[] = 'image/vnd.microsoft.icon';
275
+        }
276 276
 
277
-		return $supportedFormats;
278
-	}
277
+        return $supportedFormats;
278
+    }
279 279
 
280
-	/**
281
-	 * remove cached files that are not required any longer
282
-	 *
283
-	 * @throws NotPermittedException
284
-	 * @throws NotFoundException
285
-	 */
286
-	public function cleanup() {
287
-		$currentFolder = $this->getCacheFolder();
288
-		$folders = $this->appData->getDirectoryListing();
289
-		foreach ($folders as $folder) {
290
-			if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
291
-				$folder->delete();
292
-			}
293
-		}
294
-	}
280
+    /**
281
+     * remove cached files that are not required any longer
282
+     *
283
+     * @throws NotPermittedException
284
+     * @throws NotFoundException
285
+     */
286
+    public function cleanup() {
287
+        $currentFolder = $this->getCacheFolder();
288
+        $folders = $this->appData->getDirectoryListing();
289
+        foreach ($folders as $folder) {
290
+            if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
291
+                $folder->delete();
292
+            }
293
+        }
294
+    }
295 295
 
296
-	/**
297
-	 * Check if Imagemagick is enabled and if SVG is supported
298
-	 * otherwise we can't render custom icons
299
-	 *
300
-	 * @return bool
301
-	 */
302
-	public function shouldReplaceIcons() {
303
-		$cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
304
-		if ($value = $cache->get('shouldReplaceIcons')) {
305
-			return (bool)$value;
306
-		}
307
-		$value = false;
308
-		if (extension_loaded('imagick')) {
309
-			if (count(\Imagick::queryFormats('SVG')) >= 1) {
310
-				$value = true;
311
-			}
312
-		}
313
-		$cache->set('shouldReplaceIcons', $value);
314
-		return $value;
315
-	}
296
+    /**
297
+     * Check if Imagemagick is enabled and if SVG is supported
298
+     * otherwise we can't render custom icons
299
+     *
300
+     * @return bool
301
+     */
302
+    public function shouldReplaceIcons() {
303
+        $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
304
+        if ($value = $cache->get('shouldReplaceIcons')) {
305
+            return (bool)$value;
306
+        }
307
+        $value = false;
308
+        if (extension_loaded('imagick')) {
309
+            if (count(\Imagick::queryFormats('SVG')) >= 1) {
310
+                $value = true;
311
+            }
312
+        }
313
+        $cache->set('shouldReplaceIcons', $value);
314
+        return $value;
315
+    }
316 316
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 		$cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
81 81
 		try {
82 82
 			$image = $this->getImage($key, $useSvg);
83
-			return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
83
+			return $this->urlGenerator->linkToRoute('theming.Theming.getImage', ['key' => $key]).'?v='.$cacheBusterCounter;
84 84
 		} catch (NotFoundException $e) {
85 85
 		}
86 86
 
@@ -88,9 +88,9 @@  discard block
 block discarded – undo
88 88
 			case 'logo':
89 89
 			case 'logoheader':
90 90
 			case 'favicon':
91
-				return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
91
+				return $this->urlGenerator->imagePath('core', 'logo/logo.png').'?v='.$cacheBusterCounter;
92 92
 			case 'background':
93
-				return $this->urlGenerator->imagePath('core', 'background.png') . '?v=' . $cacheBusterCounter;
93
+				return $this->urlGenerator->imagePath('core', 'background.png').'?v='.$cacheBusterCounter;
94 94
 		}
95 95
 		return '';
96 96
 	}
@@ -107,26 +107,26 @@  discard block
 block discarded – undo
107 107
 	 * @throws NotPermittedException
108 108
 	 */
109 109
 	public function getImage(string $key, bool $useSvg = true): ISimpleFile {
110
-		$logo = $this->config->getAppValue('theming', $key . 'Mime', '');
110
+		$logo = $this->config->getAppValue('theming', $key.'Mime', '');
111 111
 		$folder = $this->appData->getFolder('images');
112 112
 		if ($logo === '' || !$folder->fileExists($key)) {
113 113
 			throw new NotFoundException();
114 114
 		}
115 115
 		if (!$useSvg && $this->shouldReplaceIcons()) {
116
-			if (!$folder->fileExists($key . '.png')) {
116
+			if (!$folder->fileExists($key.'.png')) {
117 117
 				try {
118 118
 					$finalIconFile = new \Imagick();
119 119
 					$finalIconFile->setBackgroundColor('none');
120 120
 					$finalIconFile->readImageBlob($folder->getFile($key)->getContent());
121 121
 					$finalIconFile->setImageFormat('png32');
122
-					$pngFile = $folder->newFile($key . '.png');
122
+					$pngFile = $folder->newFile($key.'.png');
123 123
 					$pngFile->putContent($finalIconFile->getImageBlob());
124 124
 					return $pngFile;
125 125
 				} catch (\ImagickException $e) {
126
-					$this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
126
+					$this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: '.$e->getMessage());
127 127
 				}
128 128
 			} else {
129
-				return $folder->getFile($key . '.png');
129
+				return $folder->getFile($key.'.png');
130 130
 			}
131 131
 		}
132 132
 		return $folder->getFile($key);
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 		$images = [];
140 140
 		foreach ($this->supportedImageKeys as $key) {
141 141
 			$images[$key] = [
142
-				'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
142
+				'mime' => $this->config->getAppValue('theming', $key.'Mime', ''),
143 143
 				'url' => $this->getImageUrl($key),
144 144
 			];
145 145
 		}
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 		} catch (NotPermittedException $e) {
206 206
 		}
207 207
 		try {
208
-			$file = $this->appData->getFolder('images')->getFile($key . '.png');
208
+			$file = $this->appData->getFolder('images')->getFile($key.'.png');
209 209
 			$file->delete();
210 210
 		} catch (NotFoundException $e) {
211 211
 		} catch (NotPermittedException $e) {
@@ -238,8 +238,8 @@  discard block
 block discarded – undo
238 238
 			imagealphablending($newImage, true);
239 239
 
240 240
 			$tmpFile = $this->tempManager->getTemporaryFile();
241
-			$newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
242
-			$newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
241
+			$newWidth = (int) (imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
242
+			$newHeight = (int) (imagesy($newImage) / (imagesx($newImage) / $newWidth));
243 243
 			$outputImage = imagescale($newImage, $newWidth, $newHeight);
244 244
 
245 245
 			imageinterlace($outputImage, 1);
@@ -300,9 +300,9 @@  discard block
 block discarded – undo
300 300
 	 * @return bool
301 301
 	 */
302 302
 	public function shouldReplaceIcons() {
303
-		$cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
303
+		$cache = $this->cacheFactory->createDistributed('theming-'.$this->urlGenerator->getBaseUrl());
304 304
 		if ($value = $cache->get('shouldReplaceIcons')) {
305
-			return (bool)$value;
305
+			return (bool) $value;
306 306
 		}
307 307
 		$value = false;
308 308
 		if (extension_loaded('imagick')) {
Please login to merge, or discard this patch.
apps/theming/lib/Controller/IconController.php 2 patches
Indentation   +128 added lines, -128 removed lines patch added patch discarded remove patch
@@ -41,137 +41,137 @@
 block discarded – undo
41 41
 use OCP\IRequest;
42 42
 
43 43
 class IconController extends Controller {
44
-	/** @var ThemingDefaults */
45
-	private $themingDefaults;
46
-	/** @var IconBuilder */
47
-	private $iconBuilder;
48
-	/** @var ImageManager */
49
-	private $imageManager;
50
-	/** @var FileAccessHelper */
51
-	private $fileAccessHelper;
44
+    /** @var ThemingDefaults */
45
+    private $themingDefaults;
46
+    /** @var IconBuilder */
47
+    private $iconBuilder;
48
+    /** @var ImageManager */
49
+    private $imageManager;
50
+    /** @var FileAccessHelper */
51
+    private $fileAccessHelper;
52 52
 
53
-	/**
54
-	 * IconController constructor.
55
-	 *
56
-	 * @param string $appName
57
-	 * @param IRequest $request
58
-	 * @param ThemingDefaults $themingDefaults
59
-	 * @param IconBuilder $iconBuilder
60
-	 * @param ImageManager $imageManager
61
-	 * @param FileAccessHelper $fileAccessHelper
62
-	 */
63
-	public function __construct(
64
-		$appName,
65
-		IRequest $request,
66
-		ThemingDefaults $themingDefaults,
67
-		IconBuilder $iconBuilder,
68
-		ImageManager $imageManager,
69
-		FileAccessHelper $fileAccessHelper
70
-	) {
71
-		parent::__construct($appName, $request);
53
+    /**
54
+     * IconController constructor.
55
+     *
56
+     * @param string $appName
57
+     * @param IRequest $request
58
+     * @param ThemingDefaults $themingDefaults
59
+     * @param IconBuilder $iconBuilder
60
+     * @param ImageManager $imageManager
61
+     * @param FileAccessHelper $fileAccessHelper
62
+     */
63
+    public function __construct(
64
+        $appName,
65
+        IRequest $request,
66
+        ThemingDefaults $themingDefaults,
67
+        IconBuilder $iconBuilder,
68
+        ImageManager $imageManager,
69
+        FileAccessHelper $fileAccessHelper
70
+    ) {
71
+        parent::__construct($appName, $request);
72 72
 
73
-		$this->themingDefaults = $themingDefaults;
74
-		$this->iconBuilder = $iconBuilder;
75
-		$this->imageManager = $imageManager;
76
-		$this->fileAccessHelper = $fileAccessHelper;
77
-	}
73
+        $this->themingDefaults = $themingDefaults;
74
+        $this->iconBuilder = $iconBuilder;
75
+        $this->imageManager = $imageManager;
76
+        $this->fileAccessHelper = $fileAccessHelper;
77
+    }
78 78
 
79
-	/**
80
-	 * @PublicPage
81
-	 * @NoCSRFRequired
82
-	 *
83
-	 * @param $app string app name
84
-	 * @param $image string image file name (svg required)
85
-	 * @return FileDisplayResponse|NotFoundResponse
86
-	 * @throws \Exception
87
-	 */
88
-	public function getThemedIcon(string $app, string $image): Response {
89
-		try {
90
-			$iconFile = $this->imageManager->getCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image));
91
-		} catch (NotFoundException $exception) {
92
-			$icon = $this->iconBuilder->colorSvg($app, $image);
93
-			if ($icon === false || $icon === '') {
94
-				return new NotFoundResponse();
95
-			}
96
-			$iconFile = $this->imageManager->setCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image), $icon);
97
-		}
98
-		$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/svg+xml']);
99
-		$response->cacheFor(86400);
100
-		return $response;
101
-	}
79
+    /**
80
+     * @PublicPage
81
+     * @NoCSRFRequired
82
+     *
83
+     * @param $app string app name
84
+     * @param $image string image file name (svg required)
85
+     * @return FileDisplayResponse|NotFoundResponse
86
+     * @throws \Exception
87
+     */
88
+    public function getThemedIcon(string $app, string $image): Response {
89
+        try {
90
+            $iconFile = $this->imageManager->getCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image));
91
+        } catch (NotFoundException $exception) {
92
+            $icon = $this->iconBuilder->colorSvg($app, $image);
93
+            if ($icon === false || $icon === '') {
94
+                return new NotFoundResponse();
95
+            }
96
+            $iconFile = $this->imageManager->setCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image), $icon);
97
+        }
98
+        $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/svg+xml']);
99
+        $response->cacheFor(86400);
100
+        return $response;
101
+    }
102 102
 
103
-	/**
104
-	 * Return a 32x32 favicon as png
105
-	 *
106
-	 * @PublicPage
107
-	 * @NoCSRFRequired
108
-	 *
109
-	 * @param $app string app name
110
-	 * @return FileDisplayResponse|DataDisplayResponse|NotFoundResponse
111
-	 * @throws \Exception
112
-	 */
113
-	public function getFavicon(string $app = 'core'): Response {
114
-		$response = null;
115
-		$iconFile = null;
116
-		try {
117
-			$iconFile = $this->imageManager->getImage('favicon', false);
118
-			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
119
-		} catch (NotFoundException $e) {
120
-		}
121
-		if ($iconFile === null && $this->imageManager->shouldReplaceIcons()) {
122
-			try {
123
-				$iconFile = $this->imageManager->getCachedImage('favIcon-' . $app);
124
-			} catch (NotFoundException $exception) {
125
-				$icon = $this->iconBuilder->getFavicon($app);
126
-				if ($icon === false || $icon === '') {
127
-					return new NotFoundResponse();
128
-				}
129
-				$iconFile = $this->imageManager->setCachedImage('favIcon-' . $app, $icon);
130
-			}
131
-			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
132
-		}
133
-		if ($response === null) {
134
-			$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon.png';
135
-			$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
136
-		}
137
-		$response->cacheFor(86400);
138
-		return $response;
139
-	}
103
+    /**
104
+     * Return a 32x32 favicon as png
105
+     *
106
+     * @PublicPage
107
+     * @NoCSRFRequired
108
+     *
109
+     * @param $app string app name
110
+     * @return FileDisplayResponse|DataDisplayResponse|NotFoundResponse
111
+     * @throws \Exception
112
+     */
113
+    public function getFavicon(string $app = 'core'): Response {
114
+        $response = null;
115
+        $iconFile = null;
116
+        try {
117
+            $iconFile = $this->imageManager->getImage('favicon', false);
118
+            $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
119
+        } catch (NotFoundException $e) {
120
+        }
121
+        if ($iconFile === null && $this->imageManager->shouldReplaceIcons()) {
122
+            try {
123
+                $iconFile = $this->imageManager->getCachedImage('favIcon-' . $app);
124
+            } catch (NotFoundException $exception) {
125
+                $icon = $this->iconBuilder->getFavicon($app);
126
+                if ($icon === false || $icon === '') {
127
+                    return new NotFoundResponse();
128
+                }
129
+                $iconFile = $this->imageManager->setCachedImage('favIcon-' . $app, $icon);
130
+            }
131
+            $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
132
+        }
133
+        if ($response === null) {
134
+            $fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon.png';
135
+            $response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
136
+        }
137
+        $response->cacheFor(86400);
138
+        return $response;
139
+    }
140 140
 
141
-	/**
142
-	 * Return a 512x512 icon for touch devices
143
-	 *
144
-	 * @PublicPage
145
-	 * @NoCSRFRequired
146
-	 *
147
-	 * @param $app string app name
148
-	 * @return DataDisplayResponse|FileDisplayResponse|NotFoundResponse
149
-	 * @throws \Exception
150
-	 */
151
-	public function getTouchIcon(string $app = 'core'): Response {
152
-		$response = null;
153
-		try {
154
-			$iconFile = $this->imageManager->getImage('favicon');
155
-			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
156
-		} catch (NotFoundException $e) {
157
-		}
158
-		if ($this->imageManager->shouldReplaceIcons()) {
159
-			try {
160
-				$iconFile = $this->imageManager->getCachedImage('touchIcon-' . $app);
161
-			} catch (NotFoundException $exception) {
162
-				$icon = $this->iconBuilder->getTouchIcon($app);
163
-				if ($icon === false || $icon === '') {
164
-					return new NotFoundResponse();
165
-				}
166
-				$iconFile = $this->imageManager->setCachedImage('touchIcon-' . $app, $icon);
167
-			}
168
-			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/png']);
169
-		}
170
-		if ($response === null) {
171
-			$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon-touch.png';
172
-			$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/png']);
173
-		}
174
-		$response->cacheFor(86400);
175
-		return $response;
176
-	}
141
+    /**
142
+     * Return a 512x512 icon for touch devices
143
+     *
144
+     * @PublicPage
145
+     * @NoCSRFRequired
146
+     *
147
+     * @param $app string app name
148
+     * @return DataDisplayResponse|FileDisplayResponse|NotFoundResponse
149
+     * @throws \Exception
150
+     */
151
+    public function getTouchIcon(string $app = 'core'): Response {
152
+        $response = null;
153
+        try {
154
+            $iconFile = $this->imageManager->getImage('favicon');
155
+            $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
156
+        } catch (NotFoundException $e) {
157
+        }
158
+        if ($this->imageManager->shouldReplaceIcons()) {
159
+            try {
160
+                $iconFile = $this->imageManager->getCachedImage('touchIcon-' . $app);
161
+            } catch (NotFoundException $exception) {
162
+                $icon = $this->iconBuilder->getTouchIcon($app);
163
+                if ($icon === false || $icon === '') {
164
+                    return new NotFoundResponse();
165
+                }
166
+                $iconFile = $this->imageManager->setCachedImage('touchIcon-' . $app, $icon);
167
+            }
168
+            $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/png']);
169
+        }
170
+        if ($response === null) {
171
+            $fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon-touch.png';
172
+            $response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/png']);
173
+        }
174
+        $response->cacheFor(86400);
175
+        return $response;
176
+    }
177 177
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -87,13 +87,13 @@  discard block
 block discarded – undo
87 87
 	 */
88 88
 	public function getThemedIcon(string $app, string $image): Response {
89 89
 		try {
90
-			$iconFile = $this->imageManager->getCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image));
90
+			$iconFile = $this->imageManager->getCachedImage('icon-'.$app.'-'.str_replace('/', '_', $image));
91 91
 		} catch (NotFoundException $exception) {
92 92
 			$icon = $this->iconBuilder->colorSvg($app, $image);
93 93
 			if ($icon === false || $icon === '') {
94 94
 				return new NotFoundResponse();
95 95
 			}
96
-			$iconFile = $this->imageManager->setCachedImage('icon-' . $app . '-' . str_replace('/', '_',$image), $icon);
96
+			$iconFile = $this->imageManager->setCachedImage('icon-'.$app.'-'.str_replace('/', '_', $image), $icon);
97 97
 		}
98 98
 		$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/svg+xml']);
99 99
 		$response->cacheFor(86400);
@@ -120,18 +120,18 @@  discard block
 block discarded – undo
120 120
 		}
121 121
 		if ($iconFile === null && $this->imageManager->shouldReplaceIcons()) {
122 122
 			try {
123
-				$iconFile = $this->imageManager->getCachedImage('favIcon-' . $app);
123
+				$iconFile = $this->imageManager->getCachedImage('favIcon-'.$app);
124 124
 			} catch (NotFoundException $exception) {
125 125
 				$icon = $this->iconBuilder->getFavicon($app);
126 126
 				if ($icon === false || $icon === '') {
127 127
 					return new NotFoundResponse();
128 128
 				}
129
-				$iconFile = $this->imageManager->setCachedImage('favIcon-' . $app, $icon);
129
+				$iconFile = $this->imageManager->setCachedImage('favIcon-'.$app, $icon);
130 130
 			}
131 131
 			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
132 132
 		}
133 133
 		if ($response === null) {
134
-			$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon.png';
134
+			$fallbackLogo = \OC::$SERVERROOT.'/core/img/favicon.png';
135 135
 			$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
136 136
 		}
137 137
 		$response->cacheFor(86400);
@@ -157,18 +157,18 @@  discard block
 block discarded – undo
157 157
 		}
158 158
 		if ($this->imageManager->shouldReplaceIcons()) {
159 159
 			try {
160
-				$iconFile = $this->imageManager->getCachedImage('touchIcon-' . $app);
160
+				$iconFile = $this->imageManager->getCachedImage('touchIcon-'.$app);
161 161
 			} catch (NotFoundException $exception) {
162 162
 				$icon = $this->iconBuilder->getTouchIcon($app);
163 163
 				if ($icon === false || $icon === '') {
164 164
 					return new NotFoundResponse();
165 165
 				}
166
-				$iconFile = $this->imageManager->setCachedImage('touchIcon-' . $app, $icon);
166
+				$iconFile = $this->imageManager->setCachedImage('touchIcon-'.$app, $icon);
167 167
 			}
168 168
 			$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/png']);
169 169
 		}
170 170
 		if ($response === null) {
171
-			$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon-touch.png';
171
+			$fallbackLogo = \OC::$SERVERROOT.'/core/img/favicon-touch.png';
172 172
 			$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/png']);
173 173
 		}
174 174
 		$response->cacheFor(86400);
Please login to merge, or discard this patch.
apps/theming/lib/Util.php 2 patches
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -37,254 +37,254 @@
 block discarded – undo
37 37
 
38 38
 class Util {
39 39
 
40
-	/** @var IConfig */
41
-	private $config;
40
+    /** @var IConfig */
41
+    private $config;
42 42
 
43
-	/** @var IAppManager */
44
-	private $appManager;
43
+    /** @var IAppManager */
44
+    private $appManager;
45 45
 
46
-	/** @var IAppData */
47
-	private $appData;
46
+    /** @var IAppData */
47
+    private $appData;
48 48
 
49
-	/**
50
-	 * Util constructor.
51
-	 *
52
-	 * @param IConfig $config
53
-	 * @param IAppManager $appManager
54
-	 * @param IAppData $appData
55
-	 */
56
-	public function __construct(IConfig $config, IAppManager $appManager, IAppData $appData) {
57
-		$this->config = $config;
58
-		$this->appManager = $appManager;
59
-		$this->appData = $appData;
60
-	}
49
+    /**
50
+     * Util constructor.
51
+     *
52
+     * @param IConfig $config
53
+     * @param IAppManager $appManager
54
+     * @param IAppData $appData
55
+     */
56
+    public function __construct(IConfig $config, IAppManager $appManager, IAppData $appData) {
57
+        $this->config = $config;
58
+        $this->appManager = $appManager;
59
+        $this->appData = $appData;
60
+    }
61 61
 
62
-	/**
63
-	 * @param string $color rgb color value
64
-	 * @return bool
65
-	 */
66
-	public function invertTextColor($color) {
67
-		$l = $this->calculateLuma($color);
68
-		if ($l > 0.6) {
69
-			return true;
70
-		} else {
71
-			return false;
72
-		}
73
-	}
62
+    /**
63
+     * @param string $color rgb color value
64
+     * @return bool
65
+     */
66
+    public function invertTextColor($color) {
67
+        $l = $this->calculateLuma($color);
68
+        if ($l > 0.6) {
69
+            return true;
70
+        } else {
71
+            return false;
72
+        }
73
+    }
74 74
 
75
-	/**
76
-	 * get color for on-page elements:
77
-	 * theme color by default, grey if theme color is to bright
78
-	 * @param string $color
79
-	 * @param bool $brightBackground
80
-	 * @return string
81
-	 */
82
-	public function elementColor($color, bool $brightBackground = true) {
83
-		$luminance = $this->calculateLuminance($color);
75
+    /**
76
+     * get color for on-page elements:
77
+     * theme color by default, grey if theme color is to bright
78
+     * @param string $color
79
+     * @param bool $brightBackground
80
+     * @return string
81
+     */
82
+    public function elementColor($color, bool $brightBackground = true) {
83
+        $luminance = $this->calculateLuminance($color);
84 84
 
85
-		if ($brightBackground && $luminance > 0.8) {
86
-			// If the color is too bright in bright mode, we fall back to a darker gray
87
-			return '#aaaaaa';
88
-		}
85
+        if ($brightBackground && $luminance > 0.8) {
86
+            // If the color is too bright in bright mode, we fall back to a darker gray
87
+            return '#aaaaaa';
88
+        }
89 89
 
90
-		if (!$brightBackground && $luminance < 0.2) {
91
-			// If the color is too dark in dark mode, we fall back to a brighter gray
92
-			return '#555555';
93
-		}
90
+        if (!$brightBackground && $luminance < 0.2) {
91
+            // If the color is too dark in dark mode, we fall back to a brighter gray
92
+            return '#555555';
93
+        }
94 94
 
95
-		return $color;
96
-	}
95
+        return $color;
96
+    }
97 97
 
98
-	/**
99
-	 * Convert RGB to HSL
100
-	 *
101
-	 * Copied from cssphp, copyright Leaf Corcoran, licensed under MIT
102
-	 *
103
-	 * @param integer $red
104
-	 * @param integer $green
105
-	 * @param integer $blue
106
-	 *
107
-	 * @return array
108
-	 */
109
-	public function toHSL($red, $green, $blue) {
110
-		$min = min($red, $green, $blue);
111
-		$max = max($red, $green, $blue);
112
-		$l = $min + $max;
113
-		$d = $max - $min;
98
+    /**
99
+     * Convert RGB to HSL
100
+     *
101
+     * Copied from cssphp, copyright Leaf Corcoran, licensed under MIT
102
+     *
103
+     * @param integer $red
104
+     * @param integer $green
105
+     * @param integer $blue
106
+     *
107
+     * @return array
108
+     */
109
+    public function toHSL($red, $green, $blue) {
110
+        $min = min($red, $green, $blue);
111
+        $max = max($red, $green, $blue);
112
+        $l = $min + $max;
113
+        $d = $max - $min;
114 114
 
115
-		if ((int) $d === 0) {
116
-			$h = $s = 0;
117
-		} else {
118
-			if ($l < 255) {
119
-				$s = $d / $l;
120
-			} else {
121
-				$s = $d / (510 - $l);
122
-			}
115
+        if ((int) $d === 0) {
116
+            $h = $s = 0;
117
+        } else {
118
+            if ($l < 255) {
119
+                $s = $d / $l;
120
+            } else {
121
+                $s = $d / (510 - $l);
122
+            }
123 123
 
124
-			if ($red == $max) {
125
-				$h = 60 * ($green - $blue) / $d;
126
-			} elseif ($green == $max) {
127
-				$h = 60 * ($blue - $red) / $d + 120;
128
-			} else {
129
-				$h = 60 * ($red - $green) / $d + 240;
130
-			}
131
-		}
124
+            if ($red == $max) {
125
+                $h = 60 * ($green - $blue) / $d;
126
+            } elseif ($green == $max) {
127
+                $h = 60 * ($blue - $red) / $d + 120;
128
+            } else {
129
+                $h = 60 * ($red - $green) / $d + 240;
130
+            }
131
+        }
132 132
 
133
-		return [fmod($h, 360), $s * 100, $l / 5.1];
134
-	}
133
+        return [fmod($h, 360), $s * 100, $l / 5.1];
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $color rgb color value
138
-	 * @return float
139
-	 */
140
-	public function calculateLuminance($color) {
141
-		[$red, $green, $blue] = $this->hexToRGB($color);
142
-		$hsl = $this->toHSL($red, $green, $blue);
143
-		return $hsl[2] / 100;
144
-	}
136
+    /**
137
+     * @param string $color rgb color value
138
+     * @return float
139
+     */
140
+    public function calculateLuminance($color) {
141
+        [$red, $green, $blue] = $this->hexToRGB($color);
142
+        $hsl = $this->toHSL($red, $green, $blue);
143
+        return $hsl[2] / 100;
144
+    }
145 145
 
146
-	/**
147
-	 * @param string $color rgb color value
148
-	 * @return float
149
-	 */
150
-	public function calculateLuma($color) {
151
-		[$red, $green, $blue] = $this->hexToRGB($color);
152
-		return (0.2126 * $red + 0.7152 * $green + 0.0722 * $blue) / 255;
153
-	}
146
+    /**
147
+     * @param string $color rgb color value
148
+     * @return float
149
+     */
150
+    public function calculateLuma($color) {
151
+        [$red, $green, $blue] = $this->hexToRGB($color);
152
+        return (0.2126 * $red + 0.7152 * $green + 0.0722 * $blue) / 255;
153
+    }
154 154
 
155
-	/**
156
-	 * @param string $color rgb color value
157
-	 * @return int[]
158
-	 * @psalm-return array{0: int, 1: int, 2: int}
159
-	 */
160
-	public function hexToRGB($color) {
161
-		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
162
-		if (strlen($hex) === 3) {
163
-			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
164
-		}
165
-		if (strlen($hex) !== 6) {
166
-			return [0, 0, 0];
167
-		}
168
-		return [
169
-			hexdec(substr($hex, 0, 2)),
170
-			hexdec(substr($hex, 2, 2)),
171
-			hexdec(substr($hex, 4, 2))
172
-		];
173
-	}
155
+    /**
156
+     * @param string $color rgb color value
157
+     * @return int[]
158
+     * @psalm-return array{0: int, 1: int, 2: int}
159
+     */
160
+    public function hexToRGB($color) {
161
+        $hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
162
+        if (strlen($hex) === 3) {
163
+            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
164
+        }
165
+        if (strlen($hex) !== 6) {
166
+            return [0, 0, 0];
167
+        }
168
+        return [
169
+            hexdec(substr($hex, 0, 2)),
170
+            hexdec(substr($hex, 2, 2)),
171
+            hexdec(substr($hex, 4, 2))
172
+        ];
173
+    }
174 174
 
175
-	/**
176
-	 * @param $color
177
-	 * @return string base64 encoded radio button svg
178
-	 */
179
-	public function generateRadioButton($color) {
180
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
181
-			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
182
-		return base64_encode($radioButtonIcon);
183
-	}
175
+    /**
176
+     * @param $color
177
+     * @return string base64 encoded radio button svg
178
+     */
179
+    public function generateRadioButton($color) {
180
+        $radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
181
+            '<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
182
+        return base64_encode($radioButtonIcon);
183
+    }
184 184
 
185 185
 
186
-	/**
187
-	 * @param $app string app name
188
-	 * @return string|ISimpleFile path to app icon / file of logo
189
-	 */
190
-	public function getAppIcon($app) {
191
-		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
192
-		try {
193
-			$appPath = $this->appManager->getAppPath($app);
194
-			$icon = $appPath . '/img/' . $app . '.svg';
195
-			if (file_exists($icon)) {
196
-				return $icon;
197
-			}
198
-			$icon = $appPath . '/img/app.svg';
199
-			if (file_exists($icon)) {
200
-				return $icon;
201
-			}
202
-		} catch (AppPathNotFoundException $e) {
203
-		}
186
+    /**
187
+     * @param $app string app name
188
+     * @return string|ISimpleFile path to app icon / file of logo
189
+     */
190
+    public function getAppIcon($app) {
191
+        $app = str_replace(['\0', '/', '\\', '..'], '', $app);
192
+        try {
193
+            $appPath = $this->appManager->getAppPath($app);
194
+            $icon = $appPath . '/img/' . $app . '.svg';
195
+            if (file_exists($icon)) {
196
+                return $icon;
197
+            }
198
+            $icon = $appPath . '/img/app.svg';
199
+            if (file_exists($icon)) {
200
+                return $icon;
201
+            }
202
+        } catch (AppPathNotFoundException $e) {
203
+        }
204 204
 
205
-		if ($this->config->getAppValue('theming', 'logoMime', '') !== '') {
206
-			$logoFile = null;
207
-			try {
208
-				$folder = $this->appData->getFolder('images');
209
-				return $folder->getFile('logo');
210
-			} catch (NotFoundException $e) {
211
-			}
212
-		}
213
-		return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
214
-	}
205
+        if ($this->config->getAppValue('theming', 'logoMime', '') !== '') {
206
+            $logoFile = null;
207
+            try {
208
+                $folder = $this->appData->getFolder('images');
209
+                return $folder->getFile('logo');
210
+            } catch (NotFoundException $e) {
211
+            }
212
+        }
213
+        return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
214
+    }
215 215
 
216
-	/**
217
-	 * @param $app string app name
218
-	 * @param $image string relative path to image in app folder
219
-	 * @return string|false absolute path to image
220
-	 */
221
-	public function getAppImage($app, $image) {
222
-		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
223
-		$image = str_replace(['\0', '\\', '..'], '', $image);
224
-		if ($app === "core") {
225
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
226
-			if (file_exists($icon)) {
227
-				return $icon;
228
-			}
229
-		}
216
+    /**
217
+     * @param $app string app name
218
+     * @param $image string relative path to image in app folder
219
+     * @return string|false absolute path to image
220
+     */
221
+    public function getAppImage($app, $image) {
222
+        $app = str_replace(['\0', '/', '\\', '..'], '', $app);
223
+        $image = str_replace(['\0', '\\', '..'], '', $image);
224
+        if ($app === "core") {
225
+            $icon = \OC::$SERVERROOT . '/core/img/' . $image;
226
+            if (file_exists($icon)) {
227
+                return $icon;
228
+            }
229
+        }
230 230
 
231
-		try {
232
-			$appPath = $this->appManager->getAppPath($app);
233
-		} catch (AppPathNotFoundException $e) {
234
-			return false;
235
-		}
231
+        try {
232
+            $appPath = $this->appManager->getAppPath($app);
233
+        } catch (AppPathNotFoundException $e) {
234
+            return false;
235
+        }
236 236
 
237
-		$icon = $appPath . '/img/' . $image;
238
-		if (file_exists($icon)) {
239
-			return $icon;
240
-		}
241
-		$icon = $appPath . '/img/' . $image . '.svg';
242
-		if (file_exists($icon)) {
243
-			return $icon;
244
-		}
245
-		$icon = $appPath . '/img/' . $image . '.png';
246
-		if (file_exists($icon)) {
247
-			return $icon;
248
-		}
249
-		$icon = $appPath . '/img/' . $image . '.gif';
250
-		if (file_exists($icon)) {
251
-			return $icon;
252
-		}
253
-		$icon = $appPath . '/img/' . $image . '.jpg';
254
-		if (file_exists($icon)) {
255
-			return $icon;
256
-		}
237
+        $icon = $appPath . '/img/' . $image;
238
+        if (file_exists($icon)) {
239
+            return $icon;
240
+        }
241
+        $icon = $appPath . '/img/' . $image . '.svg';
242
+        if (file_exists($icon)) {
243
+            return $icon;
244
+        }
245
+        $icon = $appPath . '/img/' . $image . '.png';
246
+        if (file_exists($icon)) {
247
+            return $icon;
248
+        }
249
+        $icon = $appPath . '/img/' . $image . '.gif';
250
+        if (file_exists($icon)) {
251
+            return $icon;
252
+        }
253
+        $icon = $appPath . '/img/' . $image . '.jpg';
254
+        if (file_exists($icon)) {
255
+            return $icon;
256
+        }
257 257
 
258
-		return false;
259
-	}
258
+        return false;
259
+    }
260 260
 
261
-	/**
262
-	 * replace default color with a custom one
263
-	 *
264
-	 * @param $svg string content of a svg file
265
-	 * @param $color string color to match
266
-	 * @return string
267
-	 */
268
-	public function colorizeSvg($svg, $color) {
269
-		$svg = preg_replace('/#0082c9/i', $color, $svg);
270
-		return $svg;
271
-	}
261
+    /**
262
+     * replace default color with a custom one
263
+     *
264
+     * @param $svg string content of a svg file
265
+     * @param $color string color to match
266
+     * @return string
267
+     */
268
+    public function colorizeSvg($svg, $color) {
269
+        $svg = preg_replace('/#0082c9/i', $color, $svg);
270
+        return $svg;
271
+    }
272 272
 
273
-	/**
274
-	 * Check if a custom theme is set in the server configuration
275
-	 *
276
-	 * @return bool
277
-	 */
278
-	public function isAlreadyThemed() {
279
-		$theme = $this->config->getSystemValue('theme', '');
280
-		if ($theme !== '') {
281
-			return true;
282
-		}
283
-		return false;
284
-	}
273
+    /**
274
+     * Check if a custom theme is set in the server configuration
275
+     *
276
+     * @return bool
277
+     */
278
+    public function isAlreadyThemed() {
279
+        $theme = $this->config->getSystemValue('theme', '');
280
+        if ($theme !== '') {
281
+            return true;
282
+        }
283
+        return false;
284
+    }
285 285
 
286
-	public function isBackgroundThemed() {
287
-		$backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime', '');
288
-		return $backgroundLogo !== '' && $backgroundLogo !== 'backgroundColor';
289
-	}
286
+    public function isBackgroundThemed() {
287
+        $backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime', '');
288
+        return $backgroundLogo !== '' && $backgroundLogo !== 'backgroundColor';
289
+    }
290 290
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	public function hexToRGB($color) {
161 161
 		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
162 162
 		if (strlen($hex) === 3) {
163
-			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
163
+			$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
164 164
 		}
165 165
 		if (strlen($hex) !== 6) {
166 166
 			return [0, 0, 0];
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	 * @return string base64 encoded radio button svg
178 178
 	 */
179 179
 	public function generateRadioButton($color) {
180
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
180
+		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">'.
181 181
 			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
182 182
 		return base64_encode($radioButtonIcon);
183 183
 	}
@@ -191,11 +191,11 @@  discard block
 block discarded – undo
191 191
 		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
192 192
 		try {
193 193
 			$appPath = $this->appManager->getAppPath($app);
194
-			$icon = $appPath . '/img/' . $app . '.svg';
194
+			$icon = $appPath.'/img/'.$app.'.svg';
195 195
 			if (file_exists($icon)) {
196 196
 				return $icon;
197 197
 			}
198
-			$icon = $appPath . '/img/app.svg';
198
+			$icon = $appPath.'/img/app.svg';
199 199
 			if (file_exists($icon)) {
200 200
 				return $icon;
201 201
 			}
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 			} catch (NotFoundException $e) {
211 211
 			}
212 212
 		}
213
-		return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
213
+		return \OC::$SERVERROOT.'/core/img/logo/logo.svg';
214 214
 	}
215 215
 
216 216
 	/**
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
223 223
 		$image = str_replace(['\0', '\\', '..'], '', $image);
224 224
 		if ($app === "core") {
225
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
225
+			$icon = \OC::$SERVERROOT.'/core/img/'.$image;
226 226
 			if (file_exists($icon)) {
227 227
 				return $icon;
228 228
 			}
@@ -234,23 +234,23 @@  discard block
 block discarded – undo
234 234
 			return false;
235 235
 		}
236 236
 
237
-		$icon = $appPath . '/img/' . $image;
237
+		$icon = $appPath.'/img/'.$image;
238 238
 		if (file_exists($icon)) {
239 239
 			return $icon;
240 240
 		}
241
-		$icon = $appPath . '/img/' . $image . '.svg';
241
+		$icon = $appPath.'/img/'.$image.'.svg';
242 242
 		if (file_exists($icon)) {
243 243
 			return $icon;
244 244
 		}
245
-		$icon = $appPath . '/img/' . $image . '.png';
245
+		$icon = $appPath.'/img/'.$image.'.png';
246 246
 		if (file_exists($icon)) {
247 247
 			return $icon;
248 248
 		}
249
-		$icon = $appPath . '/img/' . $image . '.gif';
249
+		$icon = $appPath.'/img/'.$image.'.gif';
250 250
 		if (file_exists($icon)) {
251 251
 			return $icon;
252 252
 		}
253
-		$icon = $appPath . '/img/' . $image . '.jpg';
253
+		$icon = $appPath.'/img/'.$image.'.jpg';
254 254
 		if (file_exists($icon)) {
255 255
 			return $icon;
256 256
 		}
Please login to merge, or discard this patch.
apps/theming/lib/ThemingDefaults.php 2 patches
Indentation   +417 added lines, -417 removed lines patch added patch discarded remove patch
@@ -52,421 +52,421 @@
 block discarded – undo
52 52
 
53 53
 class ThemingDefaults extends \OC_Defaults {
54 54
 
55
-	/** @var IConfig */
56
-	private $config;
57
-	/** @var IL10N */
58
-	private $l;
59
-	/** @var ImageManager */
60
-	private $imageManager;
61
-	/** @var IURLGenerator */
62
-	private $urlGenerator;
63
-	/** @var ICacheFactory */
64
-	private $cacheFactory;
65
-	/** @var Util */
66
-	private $util;
67
-	/** @var IAppManager */
68
-	private $appManager;
69
-	/** @var INavigationManager */
70
-	private $navigationManager;
71
-
72
-	/** @var string */
73
-	private $name;
74
-	/** @var string */
75
-	private $title;
76
-	/** @var string */
77
-	private $entity;
78
-	/** @var string */
79
-	private $productName;
80
-	/** @var string */
81
-	private $url;
82
-	/** @var string */
83
-	private $color;
84
-
85
-	/** @var string */
86
-	private $iTunesAppId;
87
-	/** @var string */
88
-	private $iOSClientUrl;
89
-	/** @var string */
90
-	private $AndroidClientUrl;
91
-	/** @var string */
92
-	private $FDroidClientUrl;
93
-
94
-	/**
95
-	 * ThemingDefaults constructor.
96
-	 *
97
-	 * @param IConfig $config
98
-	 * @param IL10N $l
99
-	 * @param ImageManager $imageManager
100
-	 * @param IURLGenerator $urlGenerator
101
-	 * @param ICacheFactory $cacheFactory
102
-	 * @param Util $util
103
-	 * @param IAppManager $appManager
104
-	 */
105
-	public function __construct(IConfig $config,
106
-								IL10N $l,
107
-								IURLGenerator $urlGenerator,
108
-								ICacheFactory $cacheFactory,
109
-								Util $util,
110
-								ImageManager $imageManager,
111
-								IAppManager $appManager,
112
-								INavigationManager $navigationManager
113
-	) {
114
-		parent::__construct();
115
-		$this->config = $config;
116
-		$this->l = $l;
117
-		$this->imageManager = $imageManager;
118
-		$this->urlGenerator = $urlGenerator;
119
-		$this->cacheFactory = $cacheFactory;
120
-		$this->util = $util;
121
-		$this->appManager = $appManager;
122
-		$this->navigationManager = $navigationManager;
123
-
124
-		$this->name = parent::getName();
125
-		$this->title = parent::getTitle();
126
-		$this->entity = parent::getEntity();
127
-		$this->productName = parent::getProductName();
128
-		$this->url = parent::getBaseUrl();
129
-		$this->color = parent::getColorPrimary();
130
-		$this->iTunesAppId = parent::getiTunesAppId();
131
-		$this->iOSClientUrl = parent::getiOSClientUrl();
132
-		$this->AndroidClientUrl = parent::getAndroidClientUrl();
133
-		$this->FDroidClientUrl = parent::getFDroidClientUrl();
134
-	}
135
-
136
-	public function getName() {
137
-		return strip_tags($this->config->getAppValue('theming', 'name', $this->name));
138
-	}
139
-
140
-	public function getHTMLName() {
141
-		return $this->config->getAppValue('theming', 'name', $this->name);
142
-	}
143
-
144
-	public function getTitle() {
145
-		return strip_tags($this->config->getAppValue('theming', 'name', $this->title));
146
-	}
147
-
148
-	public function getEntity() {
149
-		return strip_tags($this->config->getAppValue('theming', 'name', $this->entity));
150
-	}
151
-
152
-	public function getProductName() {
153
-		return strip_tags($this->config->getAppValue('theming', 'productName', $this->productName));
154
-	}
155
-
156
-	public function getBaseUrl() {
157
-		return $this->config->getAppValue('theming', 'url', $this->url);
158
-	}
159
-
160
-	/**
161
-	 * We pass a string and sanitizeHTML will return a string too in that case
162
-	 * @psalm-suppress InvalidReturnStatement
163
-	 * @psalm-suppress InvalidReturnType
164
-	 */
165
-	public function getSlogan(?string $lang = null) {
166
-		return \OCP\Util::sanitizeHTML($this->config->getAppValue('theming', 'slogan', parent::getSlogan($lang)));
167
-	}
168
-
169
-	public function getImprintUrl() {
170
-		return (string)$this->config->getAppValue('theming', 'imprintUrl', '');
171
-	}
172
-
173
-	public function getPrivacyUrl() {
174
-		return (string)$this->config->getAppValue('theming', 'privacyUrl', '');
175
-	}
176
-
177
-	public function getShortFooter() {
178
-		$slogan = $this->getSlogan();
179
-		$baseUrl = $this->getBaseUrl();
180
-		if ($baseUrl !== '') {
181
-			$footer = '<a href="' . $baseUrl . '" target="_blank"' .
182
-				' rel="noreferrer noopener" class="entity-name">' . $this->getEntity() . '</a>';
183
-		} else {
184
-			$footer = '<span class="entity-name">' .$this->getEntity() . '</span>';
185
-		}
186
-		$footer .= ($slogan !== '' ? ' – ' . $slogan : '');
187
-
188
-		$links = [
189
-			[
190
-				'text' => $this->l->t('Legal notice'),
191
-				'url' => (string)$this->getImprintUrl()
192
-			],
193
-			[
194
-				'text' => $this->l->t('Privacy policy'),
195
-				'url' => (string)$this->getPrivacyUrl()
196
-			],
197
-		];
198
-
199
-		$navigation = $this->navigationManager->getAll(INavigationManager::TYPE_GUEST);
200
-		$guestNavigation = array_map(function ($nav) {
201
-			return [
202
-				'text' => $nav['name'],
203
-				'url' => $nav['href']
204
-			];
205
-		}, $navigation);
206
-		$links = array_merge($links, $guestNavigation);
207
-
208
-		$legalLinks = '';
209
-		$divider = '';
210
-		foreach ($links as $link) {
211
-			if ($link['url'] !== ''
212
-				&& filter_var($link['url'], FILTER_VALIDATE_URL)
213
-			) {
214
-				$legalLinks .= $divider . '<a href="' . $link['url'] . '" class="legal" target="_blank"' .
215
-					' rel="noreferrer noopener">' . $link['text'] . '</a>';
216
-				$divider = ' · ';
217
-			}
218
-		}
219
-		if ($legalLinks !== '') {
220
-			$footer .= '<br/>' . $legalLinks;
221
-		}
222
-
223
-		return $footer;
224
-	}
225
-
226
-	/**
227
-	 * Color that is used for the header as well as for mail headers
228
-	 *
229
-	 * @return string
230
-	 */
231
-	public function getColorPrimary() {
232
-		$color = $this->config->getAppValue('theming', 'color', $this->color);
233
-		if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $color)) {
234
-			$color = '#0082c9';
235
-		}
236
-		return $color;
237
-	}
238
-
239
-	/**
240
-	 * Themed logo url
241
-	 *
242
-	 * @param bool $useSvg Whether to point to the SVG image or a fallback
243
-	 * @return string
244
-	 */
245
-	public function getLogo($useSvg = true): string {
246
-		$logo = $this->config->getAppValue('theming', 'logoMime', '');
247
-
248
-		// short cut to avoid setting up the filesystem just to check if the logo is there
249
-		//
250
-		// explanation: if an SVG is requested and the app config value for logoMime is set then the logo is there.
251
-		// otherwise we need to check it and maybe also generate a PNG from the SVG (that's done in getImage() which
252
-		// needs to be called then)
253
-		if ($useSvg === true && $logo !== false) {
254
-			$logoExists = true;
255
-		} else {
256
-			try {
257
-				$this->imageManager->getImage('logo', $useSvg);
258
-				$logoExists = true;
259
-			} catch (\Exception $e) {
260
-				$logoExists = false;
261
-			}
262
-		}
263
-
264
-		$cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
265
-
266
-		if (!$logo || !$logoExists) {
267
-			if ($useSvg) {
268
-				$logo = $this->urlGenerator->imagePath('core', 'logo/logo.svg');
269
-			} else {
270
-				$logo = $this->urlGenerator->imagePath('core', 'logo/logo.png');
271
-			}
272
-			return $logo . '?v=' . $cacheBusterCounter;
273
-		}
274
-
275
-		return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => 'logo', 'useSvg' => $useSvg, 'v' => $cacheBusterCounter ]);
276
-	}
277
-
278
-	/**
279
-	 * Themed background image url
280
-	 *
281
-	 * @return string
282
-	 */
283
-	public function getBackground(): string {
284
-		return $this->imageManager->getImageUrl('background');
285
-	}
286
-
287
-	/**
288
-	 * @return string
289
-	 */
290
-	public function getiTunesAppId() {
291
-		return $this->config->getAppValue('theming', 'iTunesAppId', $this->iTunesAppId);
292
-	}
293
-
294
-	/**
295
-	 * @return string
296
-	 */
297
-	public function getiOSClientUrl() {
298
-		return $this->config->getAppValue('theming', 'iOSClientUrl', $this->iOSClientUrl);
299
-	}
300
-
301
-	/**
302
-	 * @return string
303
-	 */
304
-	public function getAndroidClientUrl() {
305
-		return $this->config->getAppValue('theming', 'AndroidClientUrl', $this->AndroidClientUrl);
306
-	}
307
-
308
-	/**
309
-	 * @return string
310
-	 */
311
-	public function getFDroidClientUrl() {
312
-		return $this->config->getAppValue('theming', 'FDroidClientUrl', $this->FDroidClientUrl);
313
-	}
314
-
315
-	/**
316
-	 * @return array scss variables to overwrite
317
-	 */
318
-	public function getScssVariables() {
319
-		$cacheBuster = $this->config->getAppValue('theming', 'cachebuster', '0');
320
-		$cache = $this->cacheFactory->createDistributed('theming-' . $cacheBuster . '-' . $this->urlGenerator->getBaseUrl());
321
-		if ($value = $cache->get('getScssVariables')) {
322
-			return $value;
323
-		}
324
-
325
-		$variables = [
326
-			'theming-cachebuster' => "'" . $cacheBuster . "'",
327
-			'theming-logo-mime' => "'" . $this->config->getAppValue('theming', 'logoMime') . "'",
328
-			'theming-background-mime' => "'" . $this->config->getAppValue('theming', 'backgroundMime') . "'",
329
-			'theming-logoheader-mime' => "'" . $this->config->getAppValue('theming', 'logoheaderMime') . "'",
330
-			'theming-favicon-mime' => "'" . $this->config->getAppValue('theming', 'faviconMime') . "'"
331
-		];
332
-
333
-		$variables['image-logo'] = "url('".$this->imageManager->getImageUrl('logo')."')";
334
-		$variables['image-logoheader'] = "url('".$this->imageManager->getImageUrl('logoheader')."')";
335
-		$variables['image-favicon'] = "url('".$this->imageManager->getImageUrl('favicon')."')";
336
-		$variables['image-login-background'] = "url('".$this->imageManager->getImageUrl('background')."')";
337
-		$variables['image-login-plain'] = 'false';
338
-
339
-		if ($this->config->getAppValue('theming', 'color', '') !== '') {
340
-			$variables['color-primary'] = $this->getColorPrimary();
341
-			$variables['color-primary-text'] = $this->getTextColorPrimary();
342
-			$variables['color-primary-element'] = $this->util->elementColor($this->getColorPrimary());
343
-		}
344
-
345
-		if ($this->config->getAppValue('theming', 'backgroundMime', '') === 'backgroundColor') {
346
-			$variables['image-login-plain'] = 'true';
347
-		}
348
-
349
-		$variables['has-legal-links'] = 'false';
350
-		if ($this->getImprintUrl() !== '' || $this->getPrivacyUrl() !== '') {
351
-			$variables['has-legal-links'] = 'true';
352
-		}
353
-
354
-		$cache->set('getScssVariables', $variables);
355
-		return $variables;
356
-	}
357
-
358
-	/**
359
-	 * Check if the image should be replaced by the theming app
360
-	 * and return the new image location then
361
-	 *
362
-	 * @param string $app name of the app
363
-	 * @param string $image filename of the image
364
-	 * @return bool|string false if image should not replaced, otherwise the location of the image
365
-	 */
366
-	public function replaceImagePath($app, $image) {
367
-		if ($app === '' || $app === 'files_sharing') {
368
-			$app = 'core';
369
-		}
370
-		$cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
371
-
372
-		$route = false;
373
-		if ($image === 'favicon.ico' && ($this->imageManager->shouldReplaceIcons() || $this->getCustomFavicon() !== null)) {
374
-			$route = $this->urlGenerator->linkToRoute('theming.Icon.getFavicon', ['app' => $app]);
375
-		}
376
-		if (($image === 'favicon-touch.png' || $image === 'favicon-fb.png') && ($this->imageManager->shouldReplaceIcons() || $this->getCustomFavicon() !== null)) {
377
-			$route = $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon', ['app' => $app]);
378
-		}
379
-		if ($image === 'manifest.json') {
380
-			try {
381
-				$appPath = $this->appManager->getAppPath($app);
382
-				if (file_exists($appPath . '/img/manifest.json')) {
383
-					return false;
384
-				}
385
-			} catch (AppPathNotFoundException $e) {
386
-			}
387
-			$route = $this->urlGenerator->linkToRoute('theming.Theming.getManifest', ['app' => $app ]);
388
-		}
389
-		if (strpos($image, 'filetypes/') === 0 && file_exists(\OC::$SERVERROOT . '/core/img/' . $image)) {
390
-			$route = $this->urlGenerator->linkToRoute('theming.Icon.getThemedIcon', ['app' => $app, 'image' => $image]);
391
-		}
392
-
393
-		if ($route) {
394
-			return $route . '?v=' . $cacheBusterValue;
395
-		}
396
-
397
-		return false;
398
-	}
399
-
400
-	protected function getCustomFavicon(): ?ISimpleFile {
401
-		try {
402
-			return $this->imageManager->getImage('favicon');
403
-		} catch (NotFoundException $e) {
404
-			return null;
405
-		}
406
-	}
407
-
408
-	/**
409
-	 * Increases the cache buster key
410
-	 */
411
-	private function increaseCacheBuster(): void {
412
-		$cacheBusterKey = (int)$this->config->getAppValue('theming', 'cachebuster', '0');
413
-		$this->config->setAppValue('theming', 'cachebuster', (string)($cacheBusterKey + 1));
414
-		$this->cacheFactory->createDistributed('theming-')->clear();
415
-		$this->cacheFactory->createDistributed('imagePath')->clear();
416
-	}
417
-
418
-	/**
419
-	 * Update setting in the database
420
-	 *
421
-	 * @param string $setting
422
-	 * @param string $value
423
-	 */
424
-	public function set($setting, $value) {
425
-		$this->config->setAppValue('theming', $setting, $value);
426
-		$this->increaseCacheBuster();
427
-	}
428
-
429
-	/**
430
-	 * Revert settings to the default value
431
-	 *
432
-	 * @param string $setting setting which should be reverted
433
-	 * @return string default value
434
-	 */
435
-	public function undo($setting) {
436
-		$this->config->deleteAppValue('theming', $setting);
437
-		$this->increaseCacheBuster();
438
-
439
-		$returnValue = '';
440
-		switch ($setting) {
441
-			case 'name':
442
-				$returnValue = $this->getEntity();
443
-				break;
444
-			case 'url':
445
-				$returnValue = $this->getBaseUrl();
446
-				break;
447
-			case 'slogan':
448
-				$returnValue = $this->getSlogan();
449
-				break;
450
-			case 'color':
451
-				$returnValue = $this->getColorPrimary();
452
-				break;
453
-			case 'logo':
454
-			case 'logoheader':
455
-			case 'background':
456
-			case 'favicon':
457
-				$this->imageManager->delete($setting);
458
-				break;
459
-		}
460
-
461
-		return $returnValue;
462
-	}
463
-
464
-	/**
465
-	 * Color of text in the header and primary buttons
466
-	 *
467
-	 * @return string
468
-	 */
469
-	public function getTextColorPrimary() {
470
-		return $this->util->invertTextColor($this->getColorPrimary()) ? '#000000' : '#ffffff';
471
-	}
55
+    /** @var IConfig */
56
+    private $config;
57
+    /** @var IL10N */
58
+    private $l;
59
+    /** @var ImageManager */
60
+    private $imageManager;
61
+    /** @var IURLGenerator */
62
+    private $urlGenerator;
63
+    /** @var ICacheFactory */
64
+    private $cacheFactory;
65
+    /** @var Util */
66
+    private $util;
67
+    /** @var IAppManager */
68
+    private $appManager;
69
+    /** @var INavigationManager */
70
+    private $navigationManager;
71
+
72
+    /** @var string */
73
+    private $name;
74
+    /** @var string */
75
+    private $title;
76
+    /** @var string */
77
+    private $entity;
78
+    /** @var string */
79
+    private $productName;
80
+    /** @var string */
81
+    private $url;
82
+    /** @var string */
83
+    private $color;
84
+
85
+    /** @var string */
86
+    private $iTunesAppId;
87
+    /** @var string */
88
+    private $iOSClientUrl;
89
+    /** @var string */
90
+    private $AndroidClientUrl;
91
+    /** @var string */
92
+    private $FDroidClientUrl;
93
+
94
+    /**
95
+     * ThemingDefaults constructor.
96
+     *
97
+     * @param IConfig $config
98
+     * @param IL10N $l
99
+     * @param ImageManager $imageManager
100
+     * @param IURLGenerator $urlGenerator
101
+     * @param ICacheFactory $cacheFactory
102
+     * @param Util $util
103
+     * @param IAppManager $appManager
104
+     */
105
+    public function __construct(IConfig $config,
106
+                                IL10N $l,
107
+                                IURLGenerator $urlGenerator,
108
+                                ICacheFactory $cacheFactory,
109
+                                Util $util,
110
+                                ImageManager $imageManager,
111
+                                IAppManager $appManager,
112
+                                INavigationManager $navigationManager
113
+    ) {
114
+        parent::__construct();
115
+        $this->config = $config;
116
+        $this->l = $l;
117
+        $this->imageManager = $imageManager;
118
+        $this->urlGenerator = $urlGenerator;
119
+        $this->cacheFactory = $cacheFactory;
120
+        $this->util = $util;
121
+        $this->appManager = $appManager;
122
+        $this->navigationManager = $navigationManager;
123
+
124
+        $this->name = parent::getName();
125
+        $this->title = parent::getTitle();
126
+        $this->entity = parent::getEntity();
127
+        $this->productName = parent::getProductName();
128
+        $this->url = parent::getBaseUrl();
129
+        $this->color = parent::getColorPrimary();
130
+        $this->iTunesAppId = parent::getiTunesAppId();
131
+        $this->iOSClientUrl = parent::getiOSClientUrl();
132
+        $this->AndroidClientUrl = parent::getAndroidClientUrl();
133
+        $this->FDroidClientUrl = parent::getFDroidClientUrl();
134
+    }
135
+
136
+    public function getName() {
137
+        return strip_tags($this->config->getAppValue('theming', 'name', $this->name));
138
+    }
139
+
140
+    public function getHTMLName() {
141
+        return $this->config->getAppValue('theming', 'name', $this->name);
142
+    }
143
+
144
+    public function getTitle() {
145
+        return strip_tags($this->config->getAppValue('theming', 'name', $this->title));
146
+    }
147
+
148
+    public function getEntity() {
149
+        return strip_tags($this->config->getAppValue('theming', 'name', $this->entity));
150
+    }
151
+
152
+    public function getProductName() {
153
+        return strip_tags($this->config->getAppValue('theming', 'productName', $this->productName));
154
+    }
155
+
156
+    public function getBaseUrl() {
157
+        return $this->config->getAppValue('theming', 'url', $this->url);
158
+    }
159
+
160
+    /**
161
+     * We pass a string and sanitizeHTML will return a string too in that case
162
+     * @psalm-suppress InvalidReturnStatement
163
+     * @psalm-suppress InvalidReturnType
164
+     */
165
+    public function getSlogan(?string $lang = null) {
166
+        return \OCP\Util::sanitizeHTML($this->config->getAppValue('theming', 'slogan', parent::getSlogan($lang)));
167
+    }
168
+
169
+    public function getImprintUrl() {
170
+        return (string)$this->config->getAppValue('theming', 'imprintUrl', '');
171
+    }
172
+
173
+    public function getPrivacyUrl() {
174
+        return (string)$this->config->getAppValue('theming', 'privacyUrl', '');
175
+    }
176
+
177
+    public function getShortFooter() {
178
+        $slogan = $this->getSlogan();
179
+        $baseUrl = $this->getBaseUrl();
180
+        if ($baseUrl !== '') {
181
+            $footer = '<a href="' . $baseUrl . '" target="_blank"' .
182
+                ' rel="noreferrer noopener" class="entity-name">' . $this->getEntity() . '</a>';
183
+        } else {
184
+            $footer = '<span class="entity-name">' .$this->getEntity() . '</span>';
185
+        }
186
+        $footer .= ($slogan !== '' ? ' – ' . $slogan : '');
187
+
188
+        $links = [
189
+            [
190
+                'text' => $this->l->t('Legal notice'),
191
+                'url' => (string)$this->getImprintUrl()
192
+            ],
193
+            [
194
+                'text' => $this->l->t('Privacy policy'),
195
+                'url' => (string)$this->getPrivacyUrl()
196
+            ],
197
+        ];
198
+
199
+        $navigation = $this->navigationManager->getAll(INavigationManager::TYPE_GUEST);
200
+        $guestNavigation = array_map(function ($nav) {
201
+            return [
202
+                'text' => $nav['name'],
203
+                'url' => $nav['href']
204
+            ];
205
+        }, $navigation);
206
+        $links = array_merge($links, $guestNavigation);
207
+
208
+        $legalLinks = '';
209
+        $divider = '';
210
+        foreach ($links as $link) {
211
+            if ($link['url'] !== ''
212
+                && filter_var($link['url'], FILTER_VALIDATE_URL)
213
+            ) {
214
+                $legalLinks .= $divider . '<a href="' . $link['url'] . '" class="legal" target="_blank"' .
215
+                    ' rel="noreferrer noopener">' . $link['text'] . '</a>';
216
+                $divider = ' · ';
217
+            }
218
+        }
219
+        if ($legalLinks !== '') {
220
+            $footer .= '<br/>' . $legalLinks;
221
+        }
222
+
223
+        return $footer;
224
+    }
225
+
226
+    /**
227
+     * Color that is used for the header as well as for mail headers
228
+     *
229
+     * @return string
230
+     */
231
+    public function getColorPrimary() {
232
+        $color = $this->config->getAppValue('theming', 'color', $this->color);
233
+        if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $color)) {
234
+            $color = '#0082c9';
235
+        }
236
+        return $color;
237
+    }
238
+
239
+    /**
240
+     * Themed logo url
241
+     *
242
+     * @param bool $useSvg Whether to point to the SVG image or a fallback
243
+     * @return string
244
+     */
245
+    public function getLogo($useSvg = true): string {
246
+        $logo = $this->config->getAppValue('theming', 'logoMime', '');
247
+
248
+        // short cut to avoid setting up the filesystem just to check if the logo is there
249
+        //
250
+        // explanation: if an SVG is requested and the app config value for logoMime is set then the logo is there.
251
+        // otherwise we need to check it and maybe also generate a PNG from the SVG (that's done in getImage() which
252
+        // needs to be called then)
253
+        if ($useSvg === true && $logo !== false) {
254
+            $logoExists = true;
255
+        } else {
256
+            try {
257
+                $this->imageManager->getImage('logo', $useSvg);
258
+                $logoExists = true;
259
+            } catch (\Exception $e) {
260
+                $logoExists = false;
261
+            }
262
+        }
263
+
264
+        $cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
265
+
266
+        if (!$logo || !$logoExists) {
267
+            if ($useSvg) {
268
+                $logo = $this->urlGenerator->imagePath('core', 'logo/logo.svg');
269
+            } else {
270
+                $logo = $this->urlGenerator->imagePath('core', 'logo/logo.png');
271
+            }
272
+            return $logo . '?v=' . $cacheBusterCounter;
273
+        }
274
+
275
+        return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => 'logo', 'useSvg' => $useSvg, 'v' => $cacheBusterCounter ]);
276
+    }
277
+
278
+    /**
279
+     * Themed background image url
280
+     *
281
+     * @return string
282
+     */
283
+    public function getBackground(): string {
284
+        return $this->imageManager->getImageUrl('background');
285
+    }
286
+
287
+    /**
288
+     * @return string
289
+     */
290
+    public function getiTunesAppId() {
291
+        return $this->config->getAppValue('theming', 'iTunesAppId', $this->iTunesAppId);
292
+    }
293
+
294
+    /**
295
+     * @return string
296
+     */
297
+    public function getiOSClientUrl() {
298
+        return $this->config->getAppValue('theming', 'iOSClientUrl', $this->iOSClientUrl);
299
+    }
300
+
301
+    /**
302
+     * @return string
303
+     */
304
+    public function getAndroidClientUrl() {
305
+        return $this->config->getAppValue('theming', 'AndroidClientUrl', $this->AndroidClientUrl);
306
+    }
307
+
308
+    /**
309
+     * @return string
310
+     */
311
+    public function getFDroidClientUrl() {
312
+        return $this->config->getAppValue('theming', 'FDroidClientUrl', $this->FDroidClientUrl);
313
+    }
314
+
315
+    /**
316
+     * @return array scss variables to overwrite
317
+     */
318
+    public function getScssVariables() {
319
+        $cacheBuster = $this->config->getAppValue('theming', 'cachebuster', '0');
320
+        $cache = $this->cacheFactory->createDistributed('theming-' . $cacheBuster . '-' . $this->urlGenerator->getBaseUrl());
321
+        if ($value = $cache->get('getScssVariables')) {
322
+            return $value;
323
+        }
324
+
325
+        $variables = [
326
+            'theming-cachebuster' => "'" . $cacheBuster . "'",
327
+            'theming-logo-mime' => "'" . $this->config->getAppValue('theming', 'logoMime') . "'",
328
+            'theming-background-mime' => "'" . $this->config->getAppValue('theming', 'backgroundMime') . "'",
329
+            'theming-logoheader-mime' => "'" . $this->config->getAppValue('theming', 'logoheaderMime') . "'",
330
+            'theming-favicon-mime' => "'" . $this->config->getAppValue('theming', 'faviconMime') . "'"
331
+        ];
332
+
333
+        $variables['image-logo'] = "url('".$this->imageManager->getImageUrl('logo')."')";
334
+        $variables['image-logoheader'] = "url('".$this->imageManager->getImageUrl('logoheader')."')";
335
+        $variables['image-favicon'] = "url('".$this->imageManager->getImageUrl('favicon')."')";
336
+        $variables['image-login-background'] = "url('".$this->imageManager->getImageUrl('background')."')";
337
+        $variables['image-login-plain'] = 'false';
338
+
339
+        if ($this->config->getAppValue('theming', 'color', '') !== '') {
340
+            $variables['color-primary'] = $this->getColorPrimary();
341
+            $variables['color-primary-text'] = $this->getTextColorPrimary();
342
+            $variables['color-primary-element'] = $this->util->elementColor($this->getColorPrimary());
343
+        }
344
+
345
+        if ($this->config->getAppValue('theming', 'backgroundMime', '') === 'backgroundColor') {
346
+            $variables['image-login-plain'] = 'true';
347
+        }
348
+
349
+        $variables['has-legal-links'] = 'false';
350
+        if ($this->getImprintUrl() !== '' || $this->getPrivacyUrl() !== '') {
351
+            $variables['has-legal-links'] = 'true';
352
+        }
353
+
354
+        $cache->set('getScssVariables', $variables);
355
+        return $variables;
356
+    }
357
+
358
+    /**
359
+     * Check if the image should be replaced by the theming app
360
+     * and return the new image location then
361
+     *
362
+     * @param string $app name of the app
363
+     * @param string $image filename of the image
364
+     * @return bool|string false if image should not replaced, otherwise the location of the image
365
+     */
366
+    public function replaceImagePath($app, $image) {
367
+        if ($app === '' || $app === 'files_sharing') {
368
+            $app = 'core';
369
+        }
370
+        $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
371
+
372
+        $route = false;
373
+        if ($image === 'favicon.ico' && ($this->imageManager->shouldReplaceIcons() || $this->getCustomFavicon() !== null)) {
374
+            $route = $this->urlGenerator->linkToRoute('theming.Icon.getFavicon', ['app' => $app]);
375
+        }
376
+        if (($image === 'favicon-touch.png' || $image === 'favicon-fb.png') && ($this->imageManager->shouldReplaceIcons() || $this->getCustomFavicon() !== null)) {
377
+            $route = $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon', ['app' => $app]);
378
+        }
379
+        if ($image === 'manifest.json') {
380
+            try {
381
+                $appPath = $this->appManager->getAppPath($app);
382
+                if (file_exists($appPath . '/img/manifest.json')) {
383
+                    return false;
384
+                }
385
+            } catch (AppPathNotFoundException $e) {
386
+            }
387
+            $route = $this->urlGenerator->linkToRoute('theming.Theming.getManifest', ['app' => $app ]);
388
+        }
389
+        if (strpos($image, 'filetypes/') === 0 && file_exists(\OC::$SERVERROOT . '/core/img/' . $image)) {
390
+            $route = $this->urlGenerator->linkToRoute('theming.Icon.getThemedIcon', ['app' => $app, 'image' => $image]);
391
+        }
392
+
393
+        if ($route) {
394
+            return $route . '?v=' . $cacheBusterValue;
395
+        }
396
+
397
+        return false;
398
+    }
399
+
400
+    protected function getCustomFavicon(): ?ISimpleFile {
401
+        try {
402
+            return $this->imageManager->getImage('favicon');
403
+        } catch (NotFoundException $e) {
404
+            return null;
405
+        }
406
+    }
407
+
408
+    /**
409
+     * Increases the cache buster key
410
+     */
411
+    private function increaseCacheBuster(): void {
412
+        $cacheBusterKey = (int)$this->config->getAppValue('theming', 'cachebuster', '0');
413
+        $this->config->setAppValue('theming', 'cachebuster', (string)($cacheBusterKey + 1));
414
+        $this->cacheFactory->createDistributed('theming-')->clear();
415
+        $this->cacheFactory->createDistributed('imagePath')->clear();
416
+    }
417
+
418
+    /**
419
+     * Update setting in the database
420
+     *
421
+     * @param string $setting
422
+     * @param string $value
423
+     */
424
+    public function set($setting, $value) {
425
+        $this->config->setAppValue('theming', $setting, $value);
426
+        $this->increaseCacheBuster();
427
+    }
428
+
429
+    /**
430
+     * Revert settings to the default value
431
+     *
432
+     * @param string $setting setting which should be reverted
433
+     * @return string default value
434
+     */
435
+    public function undo($setting) {
436
+        $this->config->deleteAppValue('theming', $setting);
437
+        $this->increaseCacheBuster();
438
+
439
+        $returnValue = '';
440
+        switch ($setting) {
441
+            case 'name':
442
+                $returnValue = $this->getEntity();
443
+                break;
444
+            case 'url':
445
+                $returnValue = $this->getBaseUrl();
446
+                break;
447
+            case 'slogan':
448
+                $returnValue = $this->getSlogan();
449
+                break;
450
+            case 'color':
451
+                $returnValue = $this->getColorPrimary();
452
+                break;
453
+            case 'logo':
454
+            case 'logoheader':
455
+            case 'background':
456
+            case 'favicon':
457
+                $this->imageManager->delete($setting);
458
+                break;
459
+        }
460
+
461
+        return $returnValue;
462
+    }
463
+
464
+    /**
465
+     * Color of text in the header and primary buttons
466
+     *
467
+     * @return string
468
+     */
469
+    public function getTextColorPrimary() {
470
+        return $this->util->invertTextColor($this->getColorPrimary()) ? '#000000' : '#ffffff';
471
+    }
472 472
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -167,37 +167,37 @@  discard block
 block discarded – undo
167 167
 	}
168 168
 
169 169
 	public function getImprintUrl() {
170
-		return (string)$this->config->getAppValue('theming', 'imprintUrl', '');
170
+		return (string) $this->config->getAppValue('theming', 'imprintUrl', '');
171 171
 	}
172 172
 
173 173
 	public function getPrivacyUrl() {
174
-		return (string)$this->config->getAppValue('theming', 'privacyUrl', '');
174
+		return (string) $this->config->getAppValue('theming', 'privacyUrl', '');
175 175
 	}
176 176
 
177 177
 	public function getShortFooter() {
178 178
 		$slogan = $this->getSlogan();
179 179
 		$baseUrl = $this->getBaseUrl();
180 180
 		if ($baseUrl !== '') {
181
-			$footer = '<a href="' . $baseUrl . '" target="_blank"' .
182
-				' rel="noreferrer noopener" class="entity-name">' . $this->getEntity() . '</a>';
181
+			$footer = '<a href="'.$baseUrl.'" target="_blank"'.
182
+				' rel="noreferrer noopener" class="entity-name">'.$this->getEntity().'</a>';
183 183
 		} else {
184
-			$footer = '<span class="entity-name">' .$this->getEntity() . '</span>';
184
+			$footer = '<span class="entity-name">'.$this->getEntity().'</span>';
185 185
 		}
186
-		$footer .= ($slogan !== '' ? ' – ' . $slogan : '');
186
+		$footer .= ($slogan !== '' ? ' – '.$slogan : '');
187 187
 
188 188
 		$links = [
189 189
 			[
190 190
 				'text' => $this->l->t('Legal notice'),
191
-				'url' => (string)$this->getImprintUrl()
191
+				'url' => (string) $this->getImprintUrl()
192 192
 			],
193 193
 			[
194 194
 				'text' => $this->l->t('Privacy policy'),
195
-				'url' => (string)$this->getPrivacyUrl()
195
+				'url' => (string) $this->getPrivacyUrl()
196 196
 			],
197 197
 		];
198 198
 
199 199
 		$navigation = $this->navigationManager->getAll(INavigationManager::TYPE_GUEST);
200
-		$guestNavigation = array_map(function ($nav) {
200
+		$guestNavigation = array_map(function($nav) {
201 201
 			return [
202 202
 				'text' => $nav['name'],
203 203
 				'url' => $nav['href']
@@ -211,13 +211,13 @@  discard block
 block discarded – undo
211 211
 			if ($link['url'] !== ''
212 212
 				&& filter_var($link['url'], FILTER_VALIDATE_URL)
213 213
 			) {
214
-				$legalLinks .= $divider . '<a href="' . $link['url'] . '" class="legal" target="_blank"' .
215
-					' rel="noreferrer noopener">' . $link['text'] . '</a>';
214
+				$legalLinks .= $divider.'<a href="'.$link['url'].'" class="legal" target="_blank"'.
215
+					' rel="noreferrer noopener">'.$link['text'].'</a>';
216 216
 				$divider = ' · ';
217 217
 			}
218 218
 		}
219 219
 		if ($legalLinks !== '') {
220
-			$footer .= '<br/>' . $legalLinks;
220
+			$footer .= '<br/>'.$legalLinks;
221 221
 		}
222 222
 
223 223
 		return $footer;
@@ -269,10 +269,10 @@  discard block
 block discarded – undo
269 269
 			} else {
270 270
 				$logo = $this->urlGenerator->imagePath('core', 'logo/logo.png');
271 271
 			}
272
-			return $logo . '?v=' . $cacheBusterCounter;
272
+			return $logo.'?v='.$cacheBusterCounter;
273 273
 		}
274 274
 
275
-		return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => 'logo', 'useSvg' => $useSvg, 'v' => $cacheBusterCounter ]);
275
+		return $this->urlGenerator->linkToRoute('theming.Theming.getImage', ['key' => 'logo', 'useSvg' => $useSvg, 'v' => $cacheBusterCounter]);
276 276
 	}
277 277
 
278 278
 	/**
@@ -317,17 +317,17 @@  discard block
 block discarded – undo
317 317
 	 */
318 318
 	public function getScssVariables() {
319 319
 		$cacheBuster = $this->config->getAppValue('theming', 'cachebuster', '0');
320
-		$cache = $this->cacheFactory->createDistributed('theming-' . $cacheBuster . '-' . $this->urlGenerator->getBaseUrl());
320
+		$cache = $this->cacheFactory->createDistributed('theming-'.$cacheBuster.'-'.$this->urlGenerator->getBaseUrl());
321 321
 		if ($value = $cache->get('getScssVariables')) {
322 322
 			return $value;
323 323
 		}
324 324
 
325 325
 		$variables = [
326
-			'theming-cachebuster' => "'" . $cacheBuster . "'",
327
-			'theming-logo-mime' => "'" . $this->config->getAppValue('theming', 'logoMime') . "'",
328
-			'theming-background-mime' => "'" . $this->config->getAppValue('theming', 'backgroundMime') . "'",
329
-			'theming-logoheader-mime' => "'" . $this->config->getAppValue('theming', 'logoheaderMime') . "'",
330
-			'theming-favicon-mime' => "'" . $this->config->getAppValue('theming', 'faviconMime') . "'"
326
+			'theming-cachebuster' => "'".$cacheBuster."'",
327
+			'theming-logo-mime' => "'".$this->config->getAppValue('theming', 'logoMime')."'",
328
+			'theming-background-mime' => "'".$this->config->getAppValue('theming', 'backgroundMime')."'",
329
+			'theming-logoheader-mime' => "'".$this->config->getAppValue('theming', 'logoheaderMime')."'",
330
+			'theming-favicon-mime' => "'".$this->config->getAppValue('theming', 'faviconMime')."'"
331 331
 		];
332 332
 
333 333
 		$variables['image-logo'] = "url('".$this->imageManager->getImageUrl('logo')."')";
@@ -379,19 +379,19 @@  discard block
 block discarded – undo
379 379
 		if ($image === 'manifest.json') {
380 380
 			try {
381 381
 				$appPath = $this->appManager->getAppPath($app);
382
-				if (file_exists($appPath . '/img/manifest.json')) {
382
+				if (file_exists($appPath.'/img/manifest.json')) {
383 383
 					return false;
384 384
 				}
385 385
 			} catch (AppPathNotFoundException $e) {
386 386
 			}
387
-			$route = $this->urlGenerator->linkToRoute('theming.Theming.getManifest', ['app' => $app ]);
387
+			$route = $this->urlGenerator->linkToRoute('theming.Theming.getManifest', ['app' => $app]);
388 388
 		}
389
-		if (strpos($image, 'filetypes/') === 0 && file_exists(\OC::$SERVERROOT . '/core/img/' . $image)) {
389
+		if (strpos($image, 'filetypes/') === 0 && file_exists(\OC::$SERVERROOT.'/core/img/'.$image)) {
390 390
 			$route = $this->urlGenerator->linkToRoute('theming.Icon.getThemedIcon', ['app' => $app, 'image' => $image]);
391 391
 		}
392 392
 
393 393
 		if ($route) {
394
-			return $route . '?v=' . $cacheBusterValue;
394
+			return $route.'?v='.$cacheBusterValue;
395 395
 		}
396 396
 
397 397
 		return false;
@@ -409,8 +409,8 @@  discard block
 block discarded – undo
409 409
 	 * Increases the cache buster key
410 410
 	 */
411 411
 	private function increaseCacheBuster(): void {
412
-		$cacheBusterKey = (int)$this->config->getAppValue('theming', 'cachebuster', '0');
413
-		$this->config->setAppValue('theming', 'cachebuster', (string)($cacheBusterKey + 1));
412
+		$cacheBusterKey = (int) $this->config->getAppValue('theming', 'cachebuster', '0');
413
+		$this->config->setAppValue('theming', 'cachebuster', (string) ($cacheBusterKey + 1));
414 414
 		$this->cacheFactory->createDistributed('theming-')->clear();
415 415
 		$this->cacheFactory->createDistributed('imagePath')->clear();
416 416
 	}
Please login to merge, or discard this patch.
apps/theming/lib/Command/UpdateConfig.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -32,110 +32,110 @@
 block discarded – undo
32 32
 use Symfony\Component\Console\Output\OutputInterface;
33 33
 
34 34
 class UpdateConfig extends Command {
35
-	public const SUPPORTED_KEYS = [
36
-		'name', 'url', 'imprintUrl', 'privacyUrl', 'slogan', 'color'
37
-	];
38
-
39
-	public const SUPPORTED_IMAGE_KEYS = [
40
-		'background', 'logo', 'favicon', 'logoheader'
41
-	];
42
-
43
-	private $themingDefaults;
44
-	private $imageManager;
45
-	private $config;
46
-
47
-	public function __construct(ThemingDefaults $themingDefaults, ImageManager $imageManager, IConfig $config) {
48
-		parent::__construct();
49
-
50
-		$this->themingDefaults = $themingDefaults;
51
-		$this->imageManager = $imageManager;
52
-		$this->config = $config;
53
-	}
54
-
55
-	protected function configure() {
56
-		$this
57
-			->setName('theming:config')
58
-			->setDescription('Set theming app config values')
59
-			->addArgument(
60
-				'key',
61
-				InputArgument::OPTIONAL,
62
-				'Key to update the theming app configuration (leave empty to get a list of all configured values)' . PHP_EOL .
63
-				'One of: ' . implode(', ', self::SUPPORTED_KEYS)
64
-			)
65
-			->addArgument(
66
-				'value',
67
-				InputArgument::OPTIONAL,
68
-				'Value to set (leave empty to obtain the current value)'
69
-			)
70
-			->addOption(
71
-				'reset',
72
-				'r',
73
-				InputOption::VALUE_NONE,
74
-				'Reset the given config key to default'
75
-			);
76
-	}
77
-
78
-
79
-	protected function execute(InputInterface $input, OutputInterface $output): int {
80
-		$key = $input->getArgument('key');
81
-		$value = $input->getArgument('value');
82
-		assert(is_string($value) || $value === null, 'At most one value should be provided.');
83
-
84
-		if ($key === null) {
85
-			$output->writeln('Current theming config:');
86
-			foreach (self::SUPPORTED_KEYS as $key) {
87
-				$value = $this->config->getAppValue('theming', $key, '');
88
-				$output->writeln('- ' . $key . ': ' . $value . '');
89
-			}
90
-			foreach (self::SUPPORTED_IMAGE_KEYS as $key) {
91
-				$value = $this->config->getAppValue('theming', $key . 'Mime', '');
92
-				$output->writeln('- ' . $key . ': ' . $value . '');
93
-			}
94
-			return 0;
95
-		}
96
-
97
-		if (!in_array($key, self::SUPPORTED_KEYS, true) && !in_array($key, self::SUPPORTED_IMAGE_KEYS, true)) {
98
-			$output->writeln('<error>Invalid config key provided</error>');
99
-			return 1;
100
-		}
101
-
102
-		if ($input->getOption('reset')) {
103
-			$defaultValue = $this->themingDefaults->undo($key);
104
-			$output->writeln('<info>Reset ' . $key . ' to ' . $defaultValue . '</info>');
105
-			return 0;
106
-		}
107
-
108
-		if ($value === null) {
109
-			$value = $this->config->getAppValue('theming', $key, '');
110
-			if ($value !== '') {
111
-				$output->writeln('<info>' . $key . ' is currently set to ' . $value . '</info>');
112
-			} else {
113
-				$output->writeln('<info>' . $key . ' is currently not set</info>');
114
-			}
115
-			return 0;
116
-		}
117
-
118
-		if (in_array($key, self::SUPPORTED_IMAGE_KEYS, true)) {
119
-			if (strpos($value, '/') !== 0) {
120
-				$output->writeln('<error>The image file needs to be provided as an absolute path: ' . $value . '.</error>');
121
-				return 1;
122
-			}
123
-			if (!file_exists($value)) {
124
-				$output->writeln('<error>File could not be found: ' . $value . '.</error>');
125
-				return 1;
126
-			}
127
-			$value = $this->imageManager->updateImage($key, $value);
128
-			$key = $key . 'Mime';
129
-		}
130
-
131
-		if ($key === 'color' && !preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
132
-			$output->writeln('<error>The given color is invalid: ' . $value . '</error>');
133
-			return 1;
134
-		}
135
-
136
-		$this->themingDefaults->set($key, $value);
137
-		$output->writeln('<info>Updated ' . $key . ' to ' . $value . '</info>');
138
-
139
-		return 0;
140
-	}
35
+    public const SUPPORTED_KEYS = [
36
+        'name', 'url', 'imprintUrl', 'privacyUrl', 'slogan', 'color'
37
+    ];
38
+
39
+    public const SUPPORTED_IMAGE_KEYS = [
40
+        'background', 'logo', 'favicon', 'logoheader'
41
+    ];
42
+
43
+    private $themingDefaults;
44
+    private $imageManager;
45
+    private $config;
46
+
47
+    public function __construct(ThemingDefaults $themingDefaults, ImageManager $imageManager, IConfig $config) {
48
+        parent::__construct();
49
+
50
+        $this->themingDefaults = $themingDefaults;
51
+        $this->imageManager = $imageManager;
52
+        $this->config = $config;
53
+    }
54
+
55
+    protected function configure() {
56
+        $this
57
+            ->setName('theming:config')
58
+            ->setDescription('Set theming app config values')
59
+            ->addArgument(
60
+                'key',
61
+                InputArgument::OPTIONAL,
62
+                'Key to update the theming app configuration (leave empty to get a list of all configured values)' . PHP_EOL .
63
+                'One of: ' . implode(', ', self::SUPPORTED_KEYS)
64
+            )
65
+            ->addArgument(
66
+                'value',
67
+                InputArgument::OPTIONAL,
68
+                'Value to set (leave empty to obtain the current value)'
69
+            )
70
+            ->addOption(
71
+                'reset',
72
+                'r',
73
+                InputOption::VALUE_NONE,
74
+                'Reset the given config key to default'
75
+            );
76
+    }
77
+
78
+
79
+    protected function execute(InputInterface $input, OutputInterface $output): int {
80
+        $key = $input->getArgument('key');
81
+        $value = $input->getArgument('value');
82
+        assert(is_string($value) || $value === null, 'At most one value should be provided.');
83
+
84
+        if ($key === null) {
85
+            $output->writeln('Current theming config:');
86
+            foreach (self::SUPPORTED_KEYS as $key) {
87
+                $value = $this->config->getAppValue('theming', $key, '');
88
+                $output->writeln('- ' . $key . ': ' . $value . '');
89
+            }
90
+            foreach (self::SUPPORTED_IMAGE_KEYS as $key) {
91
+                $value = $this->config->getAppValue('theming', $key . 'Mime', '');
92
+                $output->writeln('- ' . $key . ': ' . $value . '');
93
+            }
94
+            return 0;
95
+        }
96
+
97
+        if (!in_array($key, self::SUPPORTED_KEYS, true) && !in_array($key, self::SUPPORTED_IMAGE_KEYS, true)) {
98
+            $output->writeln('<error>Invalid config key provided</error>');
99
+            return 1;
100
+        }
101
+
102
+        if ($input->getOption('reset')) {
103
+            $defaultValue = $this->themingDefaults->undo($key);
104
+            $output->writeln('<info>Reset ' . $key . ' to ' . $defaultValue . '</info>');
105
+            return 0;
106
+        }
107
+
108
+        if ($value === null) {
109
+            $value = $this->config->getAppValue('theming', $key, '');
110
+            if ($value !== '') {
111
+                $output->writeln('<info>' . $key . ' is currently set to ' . $value . '</info>');
112
+            } else {
113
+                $output->writeln('<info>' . $key . ' is currently not set</info>');
114
+            }
115
+            return 0;
116
+        }
117
+
118
+        if (in_array($key, self::SUPPORTED_IMAGE_KEYS, true)) {
119
+            if (strpos($value, '/') !== 0) {
120
+                $output->writeln('<error>The image file needs to be provided as an absolute path: ' . $value . '.</error>');
121
+                return 1;
122
+            }
123
+            if (!file_exists($value)) {
124
+                $output->writeln('<error>File could not be found: ' . $value . '.</error>');
125
+                return 1;
126
+            }
127
+            $value = $this->imageManager->updateImage($key, $value);
128
+            $key = $key . 'Mime';
129
+        }
130
+
131
+        if ($key === 'color' && !preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
132
+            $output->writeln('<error>The given color is invalid: ' . $value . '</error>');
133
+            return 1;
134
+        }
135
+
136
+        $this->themingDefaults->set($key, $value);
137
+        $output->writeln('<info>Updated ' . $key . ' to ' . $value . '</info>');
138
+
139
+        return 0;
140
+    }
141 141
 }
Please login to merge, or discard this patch.
apps/testing/lib/Controller/LockingController.php 2 patches
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -39,183 +39,183 @@
 block discarded – undo
39 39
 
40 40
 class LockingController extends OCSController {
41 41
 
42
-	/** @var ILockingProvider */
43
-	protected $lockingProvider;
44
-
45
-	/** @var FakeDBLockingProvider */
46
-	protected $fakeDBLockingProvider;
47
-
48
-	/** @var IDBConnection */
49
-	protected $connection;
50
-
51
-	/** @var IConfig */
52
-	protected $config;
53
-
54
-	/** @var IRootFolder */
55
-	protected $rootFolder;
56
-
57
-	/**
58
-	 * @param string $appName
59
-	 * @param IRequest $request
60
-	 * @param ILockingProvider $lockingProvider
61
-	 * @param FakeDBLockingProvider $fakeDBLockingProvider
62
-	 * @param IDBConnection $connection
63
-	 * @param IConfig $config
64
-	 * @param IRootFolder $rootFolder
65
-	 */
66
-	public function __construct($appName,
67
-								IRequest $request,
68
-								ILockingProvider $lockingProvider,
69
-								FakeDBLockingProvider $fakeDBLockingProvider,
70
-								IDBConnection $connection,
71
-								IConfig $config,
72
-								IRootFolder $rootFolder) {
73
-		parent::__construct($appName, $request);
74
-
75
-		$this->lockingProvider = $lockingProvider;
76
-		$this->fakeDBLockingProvider = $fakeDBLockingProvider;
77
-		$this->connection = $connection;
78
-		$this->config = $config;
79
-		$this->rootFolder = $rootFolder;
80
-	}
81
-
82
-	/**
83
-	 * @throws \RuntimeException
84
-	 */
85
-	protected function getLockingProvider(): ILockingProvider {
86
-		if ($this->lockingProvider instanceof DBLockingProvider) {
87
-			return $this->fakeDBLockingProvider;
88
-		}
89
-		throw new \RuntimeException('Lock provisioning is only possible using the DBLockingProvider');
90
-	}
91
-
92
-	/**
93
-	 * @throws NotFoundException
94
-	 */
95
-	protected function getPath(string $user, string $path): string {
96
-		$node = $this->rootFolder->getUserFolder($user)->get($path);
97
-		return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
98
-	}
99
-
100
-	/**
101
-	 * @throws OCSException
102
-	 */
103
-	public function isLockingEnabled(): DataResponse {
104
-		try {
105
-			$this->getLockingProvider();
106
-			return new DataResponse();
107
-		} catch (\RuntimeException $e) {
108
-			throw new OCSException($e->getMessage(), Http::STATUS_NOT_IMPLEMENTED, $e);
109
-		}
110
-	}
111
-
112
-	/**
113
-	 * @throws OCSException
114
-	 */
115
-	public function acquireLock(int $type, string $user, string $path): DataResponse {
116
-		try {
117
-			$path = $this->getPath($user, $path);
118
-		} catch (NoUserException $e) {
119
-			throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
120
-		} catch (NotFoundException $e) {
121
-			throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
122
-		}
123
-
124
-		$lockingProvider = $this->getLockingProvider();
125
-
126
-		try {
127
-			$lockingProvider->acquireLock($path, $type);
128
-			$this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
129
-			return new DataResponse();
130
-		} catch (LockedException $e) {
131
-			throw new OCSException('', Http::STATUS_LOCKED, $e);
132
-		}
133
-	}
134
-
135
-	/**
136
-	 * @throws OCSException
137
-	 */
138
-	public function changeLock(int $type, string $user, string $path): DataResponse {
139
-		try {
140
-			$path = $this->getPath($user, $path);
141
-		} catch (NoUserException $e) {
142
-			throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
143
-		} catch (NotFoundException $e) {
144
-			throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
145
-		}
146
-
147
-		$lockingProvider = $this->getLockingProvider();
148
-
149
-		try {
150
-			$lockingProvider->changeLock($path, $type);
151
-			$this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
152
-			return new DataResponse();
153
-		} catch (LockedException $e) {
154
-			throw new OCSException('', Http::STATUS_LOCKED, $e);
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * @throws OCSException
160
-	 */
161
-	public function releaseLock(int $type, string $user, string $path): DataResponse {
162
-		try {
163
-			$path = $this->getPath($user, $path);
164
-		} catch (NoUserException $e) {
165
-			throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
166
-		} catch (NotFoundException $e) {
167
-			throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
168
-		}
169
-
170
-		$lockingProvider = $this->getLockingProvider();
171
-
172
-		try {
173
-			$lockingProvider->releaseLock($path, $type);
174
-			$this->config->deleteAppValue('testing', 'locking_' . $path);
175
-			return new DataResponse();
176
-		} catch (LockedException $e) {
177
-			throw new OCSException('', Http::STATUS_LOCKED, $e);
178
-		}
179
-	}
180
-
181
-	/**
182
-	 * @throws OCSException
183
-	 */
184
-	public function isLocked(int $type, string $user, string $path): DataResponse {
185
-		try {
186
-			$path = $this->getPath($user, $path);
187
-		} catch (NoUserException $e) {
188
-			throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
189
-		} catch (NotFoundException $e) {
190
-			throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
191
-		}
192
-
193
-		$lockingProvider = $this->getLockingProvider();
194
-
195
-		if ($lockingProvider->isLocked($path, $type)) {
196
-			return new DataResponse();
197
-		}
198
-
199
-		throw new OCSException('', Http::STATUS_LOCKED);
200
-	}
201
-
202
-	public function releaseAll(int $type = null): DataResponse {
203
-		$lockingProvider = $this->getLockingProvider();
204
-
205
-		foreach ($this->config->getAppKeys('testing') as $lock) {
206
-			if (strpos($lock, 'locking_') === 0) {
207
-				$path = substr($lock, strlen('locking_'));
208
-
209
-				if ($type === ILockingProvider::LOCK_EXCLUSIVE && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_EXCLUSIVE) {
210
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
211
-				} elseif ($type === ILockingProvider::LOCK_SHARED && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_SHARED) {
212
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
213
-				} else {
214
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
215
-				}
216
-			}
217
-		}
218
-
219
-		return new DataResponse();
220
-	}
42
+    /** @var ILockingProvider */
43
+    protected $lockingProvider;
44
+
45
+    /** @var FakeDBLockingProvider */
46
+    protected $fakeDBLockingProvider;
47
+
48
+    /** @var IDBConnection */
49
+    protected $connection;
50
+
51
+    /** @var IConfig */
52
+    protected $config;
53
+
54
+    /** @var IRootFolder */
55
+    protected $rootFolder;
56
+
57
+    /**
58
+     * @param string $appName
59
+     * @param IRequest $request
60
+     * @param ILockingProvider $lockingProvider
61
+     * @param FakeDBLockingProvider $fakeDBLockingProvider
62
+     * @param IDBConnection $connection
63
+     * @param IConfig $config
64
+     * @param IRootFolder $rootFolder
65
+     */
66
+    public function __construct($appName,
67
+                                IRequest $request,
68
+                                ILockingProvider $lockingProvider,
69
+                                FakeDBLockingProvider $fakeDBLockingProvider,
70
+                                IDBConnection $connection,
71
+                                IConfig $config,
72
+                                IRootFolder $rootFolder) {
73
+        parent::__construct($appName, $request);
74
+
75
+        $this->lockingProvider = $lockingProvider;
76
+        $this->fakeDBLockingProvider = $fakeDBLockingProvider;
77
+        $this->connection = $connection;
78
+        $this->config = $config;
79
+        $this->rootFolder = $rootFolder;
80
+    }
81
+
82
+    /**
83
+     * @throws \RuntimeException
84
+     */
85
+    protected function getLockingProvider(): ILockingProvider {
86
+        if ($this->lockingProvider instanceof DBLockingProvider) {
87
+            return $this->fakeDBLockingProvider;
88
+        }
89
+        throw new \RuntimeException('Lock provisioning is only possible using the DBLockingProvider');
90
+    }
91
+
92
+    /**
93
+     * @throws NotFoundException
94
+     */
95
+    protected function getPath(string $user, string $path): string {
96
+        $node = $this->rootFolder->getUserFolder($user)->get($path);
97
+        return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
98
+    }
99
+
100
+    /**
101
+     * @throws OCSException
102
+     */
103
+    public function isLockingEnabled(): DataResponse {
104
+        try {
105
+            $this->getLockingProvider();
106
+            return new DataResponse();
107
+        } catch (\RuntimeException $e) {
108
+            throw new OCSException($e->getMessage(), Http::STATUS_NOT_IMPLEMENTED, $e);
109
+        }
110
+    }
111
+
112
+    /**
113
+     * @throws OCSException
114
+     */
115
+    public function acquireLock(int $type, string $user, string $path): DataResponse {
116
+        try {
117
+            $path = $this->getPath($user, $path);
118
+        } catch (NoUserException $e) {
119
+            throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
120
+        } catch (NotFoundException $e) {
121
+            throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
122
+        }
123
+
124
+        $lockingProvider = $this->getLockingProvider();
125
+
126
+        try {
127
+            $lockingProvider->acquireLock($path, $type);
128
+            $this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
129
+            return new DataResponse();
130
+        } catch (LockedException $e) {
131
+            throw new OCSException('', Http::STATUS_LOCKED, $e);
132
+        }
133
+    }
134
+
135
+    /**
136
+     * @throws OCSException
137
+     */
138
+    public function changeLock(int $type, string $user, string $path): DataResponse {
139
+        try {
140
+            $path = $this->getPath($user, $path);
141
+        } catch (NoUserException $e) {
142
+            throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
143
+        } catch (NotFoundException $e) {
144
+            throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
145
+        }
146
+
147
+        $lockingProvider = $this->getLockingProvider();
148
+
149
+        try {
150
+            $lockingProvider->changeLock($path, $type);
151
+            $this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
152
+            return new DataResponse();
153
+        } catch (LockedException $e) {
154
+            throw new OCSException('', Http::STATUS_LOCKED, $e);
155
+        }
156
+    }
157
+
158
+    /**
159
+     * @throws OCSException
160
+     */
161
+    public function releaseLock(int $type, string $user, string $path): DataResponse {
162
+        try {
163
+            $path = $this->getPath($user, $path);
164
+        } catch (NoUserException $e) {
165
+            throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
166
+        } catch (NotFoundException $e) {
167
+            throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
168
+        }
169
+
170
+        $lockingProvider = $this->getLockingProvider();
171
+
172
+        try {
173
+            $lockingProvider->releaseLock($path, $type);
174
+            $this->config->deleteAppValue('testing', 'locking_' . $path);
175
+            return new DataResponse();
176
+        } catch (LockedException $e) {
177
+            throw new OCSException('', Http::STATUS_LOCKED, $e);
178
+        }
179
+    }
180
+
181
+    /**
182
+     * @throws OCSException
183
+     */
184
+    public function isLocked(int $type, string $user, string $path): DataResponse {
185
+        try {
186
+            $path = $this->getPath($user, $path);
187
+        } catch (NoUserException $e) {
188
+            throw new OCSException('User not found', Http::STATUS_NOT_FOUND, $e);
189
+        } catch (NotFoundException $e) {
190
+            throw new OCSException('Path not found', Http::STATUS_NOT_FOUND, $e);
191
+        }
192
+
193
+        $lockingProvider = $this->getLockingProvider();
194
+
195
+        if ($lockingProvider->isLocked($path, $type)) {
196
+            return new DataResponse();
197
+        }
198
+
199
+        throw new OCSException('', Http::STATUS_LOCKED);
200
+    }
201
+
202
+    public function releaseAll(int $type = null): DataResponse {
203
+        $lockingProvider = $this->getLockingProvider();
204
+
205
+        foreach ($this->config->getAppKeys('testing') as $lock) {
206
+            if (strpos($lock, 'locking_') === 0) {
207
+                $path = substr($lock, strlen('locking_'));
208
+
209
+                if ($type === ILockingProvider::LOCK_EXCLUSIVE && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_EXCLUSIVE) {
210
+                    $lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
211
+                } elseif ($type === ILockingProvider::LOCK_SHARED && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_SHARED) {
212
+                    $lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
213
+                } else {
214
+                    $lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
215
+                }
216
+            }
217
+        }
218
+
219
+        return new DataResponse();
220
+    }
221 221
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	protected function getPath(string $user, string $path): string {
96 96
 		$node = $this->rootFolder->getUserFolder($user)->get($path);
97
-		return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
97
+		return 'files/'.md5($node->getStorage()->getId().'::'.trim($node->getInternalPath(), '/'));
98 98
 	}
99 99
 
100 100
 	/**
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 
126 126
 		try {
127 127
 			$lockingProvider->acquireLock($path, $type);
128
-			$this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
128
+			$this->config->setAppValue('testing', 'locking_'.$path, (string) $type);
129 129
 			return new DataResponse();
130 130
 		} catch (LockedException $e) {
131 131
 			throw new OCSException('', Http::STATUS_LOCKED, $e);
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 
149 149
 		try {
150 150
 			$lockingProvider->changeLock($path, $type);
151
-			$this->config->setAppValue('testing', 'locking_' . $path, (string)$type);
151
+			$this->config->setAppValue('testing', 'locking_'.$path, (string) $type);
152 152
 			return new DataResponse();
153 153
 		} catch (LockedException $e) {
154 154
 			throw new OCSException('', Http::STATUS_LOCKED, $e);
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 
172 172
 		try {
173 173
 			$lockingProvider->releaseLock($path, $type);
174
-			$this->config->deleteAppValue('testing', 'locking_' . $path);
174
+			$this->config->deleteAppValue('testing', 'locking_'.$path);
175 175
 			return new DataResponse();
176 176
 		} catch (LockedException $e) {
177 177
 			throw new OCSException('', Http::STATUS_LOCKED, $e);
@@ -206,12 +206,12 @@  discard block
 block discarded – undo
206 206
 			if (strpos($lock, 'locking_') === 0) {
207 207
 				$path = substr($lock, strlen('locking_'));
208 208
 
209
-				if ($type === ILockingProvider::LOCK_EXCLUSIVE && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_EXCLUSIVE) {
210
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
211
-				} elseif ($type === ILockingProvider::LOCK_SHARED && (int)$this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_SHARED) {
212
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
209
+				if ($type === ILockingProvider::LOCK_EXCLUSIVE && (int) $this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_EXCLUSIVE) {
210
+					$lockingProvider->releaseLock($path, (int) $this->config->getAppValue('testing', $lock));
211
+				} elseif ($type === ILockingProvider::LOCK_SHARED && (int) $this->config->getAppValue('testing', $lock) === ILockingProvider::LOCK_SHARED) {
212
+					$lockingProvider->releaseLock($path, (int) $this->config->getAppValue('testing', $lock));
213 213
 				} else {
214
-					$lockingProvider->releaseLock($path, (int)$this->config->getAppValue('testing', $lock));
214
+					$lockingProvider->releaseLock($path, (int) $this->config->getAppValue('testing', $lock));
215 215
 				}
216 216
 			}
217 217
 		}
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 2 patches
Indentation   +1366 added lines, -1366 removed lines patch added patch discarded remove patch
@@ -77,1375 +77,1375 @@
 block discarded – undo
77 77
 use Psr\Log\LoggerInterface;
78 78
 
79 79
 class OC_Util {
80
-	public static $scripts = [];
81
-	public static $styles = [];
82
-	public static $headers = [];
83
-	private static $rootMounted = false;
84
-	private static $fsSetup = false;
85
-
86
-	/** @var array Local cache of version.php */
87
-	private static $versionCache = null;
88
-
89
-	protected static function getAppManager() {
90
-		return \OC::$server->getAppManager();
91
-	}
92
-
93
-	private static function initLocalStorageRootFS() {
94
-		// mount local file backend as root
95
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
96
-		//first set up the local "root" storage
97
-		\OC\Files\Filesystem::initMountManager();
98
-		if (!self::$rootMounted) {
99
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
100
-			self::$rootMounted = true;
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * mounting an object storage as the root fs will in essence remove the
106
-	 * necessity of a data folder being present.
107
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
108
-	 *
109
-	 * @param array $config containing 'class' and optional 'arguments'
110
-	 * @suppress PhanDeprecatedFunction
111
-	 */
112
-	private static function initObjectStoreRootFS($config) {
113
-		// check misconfiguration
114
-		if (empty($config['class'])) {
115
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
116
-		}
117
-		if (!isset($config['arguments'])) {
118
-			$config['arguments'] = [];
119
-		}
120
-
121
-		// instantiate object store implementation
122
-		$name = $config['class'];
123
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
124
-			$segments = explode('\\', $name);
125
-			OC_App::loadApp(strtolower($segments[1]));
126
-		}
127
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
128
-		// mount with plain / root object store implementation
129
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
130
-
131
-		// mount object storage as root
132
-		\OC\Files\Filesystem::initMountManager();
133
-		if (!self::$rootMounted) {
134
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
135
-			self::$rootMounted = true;
136
-		}
137
-	}
138
-
139
-	/**
140
-	 * mounting an object storage as the root fs will in essence remove the
141
-	 * necessity of a data folder being present.
142
-	 *
143
-	 * @param array $config containing 'class' and optional 'arguments'
144
-	 * @suppress PhanDeprecatedFunction
145
-	 */
146
-	private static function initObjectStoreMultibucketRootFS($config) {
147
-		// check misconfiguration
148
-		if (empty($config['class'])) {
149
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
150
-		}
151
-		if (!isset($config['arguments'])) {
152
-			$config['arguments'] = [];
153
-		}
154
-
155
-		// instantiate object store implementation
156
-		$name = $config['class'];
157
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
158
-			$segments = explode('\\', $name);
159
-			OC_App::loadApp(strtolower($segments[1]));
160
-		}
161
-
162
-		if (!isset($config['arguments']['bucket'])) {
163
-			$config['arguments']['bucket'] = '';
164
-		}
165
-		// put the root FS always in first bucket for multibucket configuration
166
-		$config['arguments']['bucket'] .= '0';
167
-
168
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
169
-		// mount with plain / root object store implementation
170
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
171
-
172
-		// mount object storage as root
173
-		\OC\Files\Filesystem::initMountManager();
174
-		if (!self::$rootMounted) {
175
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
176
-			self::$rootMounted = true;
177
-		}
178
-	}
179
-
180
-	/**
181
-	 * Can be set up
182
-	 *
183
-	 * @param string $user
184
-	 * @return boolean
185
-	 * @description configure the initial filesystem based on the configuration
186
-	 * @suppress PhanDeprecatedFunction
187
-	 * @suppress PhanAccessMethodInternal
188
-	 */
189
-	public static function setupFS($user = '') {
190
-		//setting up the filesystem twice can only lead to trouble
191
-		if (self::$fsSetup) {
192
-			return false;
193
-		}
194
-
195
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
196
-
197
-		// If we are not forced to load a specific user we load the one that is logged in
198
-		if ($user === null) {
199
-			$user = '';
200
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
201
-			$user = OC_User::getUser();
202
-		}
203
-
204
-		// load all filesystem apps before, so no setup-hook gets lost
205
-		OC_App::loadApps(['filesystem']);
206
-
207
-		// the filesystem will finish when $user is not empty,
208
-		// mark fs setup here to avoid doing the setup from loading
209
-		// OC_Filesystem
210
-		if ($user != '') {
211
-			self::$fsSetup = true;
212
-		}
213
-
214
-		\OC\Files\Filesystem::initMountManager();
215
-
216
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
217
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
219
-				/** @var \OC\Files\Storage\Common $storage */
220
-				$storage->setMountOptions($mount->getOptions());
221
-			}
222
-			return $storage;
223
-		});
224
-
225
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
226
-			if (!$mount->getOption('enable_sharing', true)) {
227
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
228
-					'storage' => $storage,
229
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
230
-				]);
231
-			}
232
-			return $storage;
233
-		});
234
-
235
-		// install storage availability wrapper, before most other wrappers
236
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
237
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
238
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
239
-			}
240
-			return $storage;
241
-		});
242
-
243
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
244
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
245
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
246
-			}
247
-			return $storage;
248
-		});
249
-
250
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
251
-			// set up quota for home storages, even for other users
252
-			// which can happen when using sharing
253
-
254
-			/**
255
-			 * @var \OC\Files\Storage\Storage $storage
256
-			 */
257
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
258
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
259
-			) {
260
-				/** @var \OC\Files\Storage\Home $storage */
261
-				if (is_object($storage->getUser())) {
262
-					$quota = OC_Util::getUserQuota($storage->getUser());
263
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
264
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
265
-					}
266
-				}
267
-			}
268
-
269
-			return $storage;
270
-		});
271
-
272
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
273
-			/*
80
+    public static $scripts = [];
81
+    public static $styles = [];
82
+    public static $headers = [];
83
+    private static $rootMounted = false;
84
+    private static $fsSetup = false;
85
+
86
+    /** @var array Local cache of version.php */
87
+    private static $versionCache = null;
88
+
89
+    protected static function getAppManager() {
90
+        return \OC::$server->getAppManager();
91
+    }
92
+
93
+    private static function initLocalStorageRootFS() {
94
+        // mount local file backend as root
95
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
96
+        //first set up the local "root" storage
97
+        \OC\Files\Filesystem::initMountManager();
98
+        if (!self::$rootMounted) {
99
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
100
+            self::$rootMounted = true;
101
+        }
102
+    }
103
+
104
+    /**
105
+     * mounting an object storage as the root fs will in essence remove the
106
+     * necessity of a data folder being present.
107
+     * TODO make home storage aware of this and use the object storage instead of local disk access
108
+     *
109
+     * @param array $config containing 'class' and optional 'arguments'
110
+     * @suppress PhanDeprecatedFunction
111
+     */
112
+    private static function initObjectStoreRootFS($config) {
113
+        // check misconfiguration
114
+        if (empty($config['class'])) {
115
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
116
+        }
117
+        if (!isset($config['arguments'])) {
118
+            $config['arguments'] = [];
119
+        }
120
+
121
+        // instantiate object store implementation
122
+        $name = $config['class'];
123
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
124
+            $segments = explode('\\', $name);
125
+            OC_App::loadApp(strtolower($segments[1]));
126
+        }
127
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
128
+        // mount with plain / root object store implementation
129
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
130
+
131
+        // mount object storage as root
132
+        \OC\Files\Filesystem::initMountManager();
133
+        if (!self::$rootMounted) {
134
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
135
+            self::$rootMounted = true;
136
+        }
137
+    }
138
+
139
+    /**
140
+     * mounting an object storage as the root fs will in essence remove the
141
+     * necessity of a data folder being present.
142
+     *
143
+     * @param array $config containing 'class' and optional 'arguments'
144
+     * @suppress PhanDeprecatedFunction
145
+     */
146
+    private static function initObjectStoreMultibucketRootFS($config) {
147
+        // check misconfiguration
148
+        if (empty($config['class'])) {
149
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
150
+        }
151
+        if (!isset($config['arguments'])) {
152
+            $config['arguments'] = [];
153
+        }
154
+
155
+        // instantiate object store implementation
156
+        $name = $config['class'];
157
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
158
+            $segments = explode('\\', $name);
159
+            OC_App::loadApp(strtolower($segments[1]));
160
+        }
161
+
162
+        if (!isset($config['arguments']['bucket'])) {
163
+            $config['arguments']['bucket'] = '';
164
+        }
165
+        // put the root FS always in first bucket for multibucket configuration
166
+        $config['arguments']['bucket'] .= '0';
167
+
168
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
169
+        // mount with plain / root object store implementation
170
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
171
+
172
+        // mount object storage as root
173
+        \OC\Files\Filesystem::initMountManager();
174
+        if (!self::$rootMounted) {
175
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
176
+            self::$rootMounted = true;
177
+        }
178
+    }
179
+
180
+    /**
181
+     * Can be set up
182
+     *
183
+     * @param string $user
184
+     * @return boolean
185
+     * @description configure the initial filesystem based on the configuration
186
+     * @suppress PhanDeprecatedFunction
187
+     * @suppress PhanAccessMethodInternal
188
+     */
189
+    public static function setupFS($user = '') {
190
+        //setting up the filesystem twice can only lead to trouble
191
+        if (self::$fsSetup) {
192
+            return false;
193
+        }
194
+
195
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
196
+
197
+        // If we are not forced to load a specific user we load the one that is logged in
198
+        if ($user === null) {
199
+            $user = '';
200
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
201
+            $user = OC_User::getUser();
202
+        }
203
+
204
+        // load all filesystem apps before, so no setup-hook gets lost
205
+        OC_App::loadApps(['filesystem']);
206
+
207
+        // the filesystem will finish when $user is not empty,
208
+        // mark fs setup here to avoid doing the setup from loading
209
+        // OC_Filesystem
210
+        if ($user != '') {
211
+            self::$fsSetup = true;
212
+        }
213
+
214
+        \OC\Files\Filesystem::initMountManager();
215
+
216
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
217
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
219
+                /** @var \OC\Files\Storage\Common $storage */
220
+                $storage->setMountOptions($mount->getOptions());
221
+            }
222
+            return $storage;
223
+        });
224
+
225
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
226
+            if (!$mount->getOption('enable_sharing', true)) {
227
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
228
+                    'storage' => $storage,
229
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
230
+                ]);
231
+            }
232
+            return $storage;
233
+        });
234
+
235
+        // install storage availability wrapper, before most other wrappers
236
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
237
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
238
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
239
+            }
240
+            return $storage;
241
+        });
242
+
243
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
244
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
245
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
246
+            }
247
+            return $storage;
248
+        });
249
+
250
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
251
+            // set up quota for home storages, even for other users
252
+            // which can happen when using sharing
253
+
254
+            /**
255
+             * @var \OC\Files\Storage\Storage $storage
256
+             */
257
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
258
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
259
+            ) {
260
+                /** @var \OC\Files\Storage\Home $storage */
261
+                if (is_object($storage->getUser())) {
262
+                    $quota = OC_Util::getUserQuota($storage->getUser());
263
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
264
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
265
+                    }
266
+                }
267
+            }
268
+
269
+            return $storage;
270
+        });
271
+
272
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
273
+            /*
274 274
 			 * Do not allow any operations that modify the storage
275 275
 			 */
276
-			if ($mount->getOption('readonly', false)) {
277
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
278
-					'storage' => $storage,
279
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
280
-						\OCP\Constants::PERMISSION_UPDATE |
281
-						\OCP\Constants::PERMISSION_CREATE |
282
-						\OCP\Constants::PERMISSION_DELETE
283
-					),
284
-				]);
285
-			}
286
-			return $storage;
287
-		});
288
-
289
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
290
-
291
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
292
-
293
-		//check if we are using an object storage
294
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
295
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
296
-
297
-		// use the same order as in ObjectHomeMountProvider
298
-		if (isset($objectStoreMultibucket)) {
299
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
300
-		} elseif (isset($objectStore)) {
301
-			self::initObjectStoreRootFS($objectStore);
302
-		} else {
303
-			self::initLocalStorageRootFS();
304
-		}
305
-
306
-		/** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
307
-		$mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
308
-		$rootMountProviders = $mountProviderCollection->getRootMounts();
309
-
310
-		/** @var \OC\Files\Mount\Manager $mountManager */
311
-		$mountManager = \OC\Files\Filesystem::getMountManager();
312
-		foreach ($rootMountProviders as $rootMountProvider) {
313
-			$mountManager->addMount($rootMountProvider);
314
-		}
315
-
316
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
317
-			\OC::$server->getEventLogger()->end('setup_fs');
318
-			return false;
319
-		}
320
-
321
-		//if we aren't logged in, there is no use to set up the filesystem
322
-		if ($user != "") {
323
-			$userDir = '/' . $user . '/files';
324
-
325
-			//jail the user into his "home" directory
326
-			\OC\Files\Filesystem::init($user, $userDir);
327
-
328
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
329
-		}
330
-		\OC::$server->getEventLogger()->end('setup_fs');
331
-		return true;
332
-	}
333
-
334
-	/**
335
-	 * check if a password is required for each public link
336
-	 *
337
-	 * @return boolean
338
-	 * @suppress PhanDeprecatedFunction
339
-	 */
340
-	public static function isPublicLinkPasswordRequired() {
341
-		/** @var IManager $shareManager */
342
-		$shareManager = \OC::$server->get(IManager::class);
343
-		return $shareManager->shareApiLinkEnforcePassword();
344
-	}
345
-
346
-	/**
347
-	 * check if sharing is disabled for the current user
348
-	 * @param IConfig $config
349
-	 * @param IGroupManager $groupManager
350
-	 * @param IUser|null $user
351
-	 * @return bool
352
-	 */
353
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
354
-		/** @var IManager $shareManager */
355
-		$shareManager = \OC::$server->get(IManager::class);
356
-		$userId = $user ? $user->getUID() : null;
357
-		return $shareManager->sharingDisabledForUser($userId);
358
-	}
359
-
360
-	/**
361
-	 * check if share API enforces a default expire date
362
-	 *
363
-	 * @return boolean
364
-	 * @suppress PhanDeprecatedFunction
365
-	 */
366
-	public static function isDefaultExpireDateEnforced() {
367
-		/** @var IManager $shareManager */
368
-		$shareManager = \OC::$server->get(IManager::class);
369
-		return $shareManager->shareApiLinkDefaultExpireDateEnforced();
370
-	}
371
-
372
-	/**
373
-	 * Get the quota of a user
374
-	 *
375
-	 * @param IUser|null $user
376
-	 * @return float Quota bytes
377
-	 */
378
-	public static function getUserQuota(?IUser $user) {
379
-		if (is_null($user)) {
380
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
381
-		}
382
-		$userQuota = $user->getQuota();
383
-		if ($userQuota === 'none') {
384
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
-		}
386
-		return OC_Helper::computerFileSize($userQuota);
387
-	}
388
-
389
-	/**
390
-	 * copies the skeleton to the users /files
391
-	 *
392
-	 * @param string $userId
393
-	 * @param \OCP\Files\Folder $userDirectory
394
-	 * @throws \OCP\Files\NotFoundException
395
-	 * @throws \OCP\Files\NotPermittedException
396
-	 * @suppress PhanDeprecatedFunction
397
-	 */
398
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
399
-		/** @var LoggerInterface $logger */
400
-		$logger = \OC::$server->get(LoggerInterface::class);
401
-
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
-
406
-		if (!file_exists($skeletonDirectory)) {
407
-			$dialectStart = strpos($userLang, '_');
408
-			if ($dialectStart !== false) {
409
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
-			}
411
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
-			}
414
-			if (!file_exists($skeletonDirectory)) {
415
-				$skeletonDirectory = '';
416
-			}
417
-		}
418
-
419
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
-
421
-		if ($instanceId === null) {
422
-			throw new \RuntimeException('no instance id!');
423
-		}
424
-		$appdata = 'appdata_' . $instanceId;
425
-		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
427
-		}
428
-
429
-		if (!empty($skeletonDirectory)) {
430
-			$logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
431
-			self::copyr($skeletonDirectory, $userDirectory);
432
-			// update the file cache
433
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
434
-
435
-			/** @var ITemplateManager $templateManager */
436
-			$templateManager = \OC::$server->get(ITemplateManager::class);
437
-			$templateManager->initializeTemplateDirectory(null, $userId);
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * copies a directory recursively by using streams
443
-	 *
444
-	 * @param string $source
445
-	 * @param \OCP\Files\Folder $target
446
-	 * @return void
447
-	 */
448
-	public static function copyr($source, \OCP\Files\Folder $target) {
449
-		$logger = \OC::$server->getLogger();
450
-
451
-		// Verify if folder exists
452
-		$dir = opendir($source);
453
-		if ($dir === false) {
454
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
-			return;
456
-		}
457
-
458
-		// Copy the files
459
-		while (false !== ($file = readdir($dir))) {
460
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
462
-					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
464
-				} else {
465
-					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if ($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
-						closedir($dir);
470
-						return;
471
-					}
472
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
-				}
474
-			}
475
-		}
476
-		closedir($dir);
477
-	}
478
-
479
-	/**
480
-	 * @return void
481
-	 * @suppress PhanUndeclaredMethod
482
-	 */
483
-	public static function tearDownFS() {
484
-		\OC\Files\Filesystem::tearDown();
485
-		\OC::$server->getRootFolder()->clearCache();
486
-		self::$fsSetup = false;
487
-		self::$rootMounted = false;
488
-	}
489
-
490
-	/**
491
-	 * get the current installed version of ownCloud
492
-	 *
493
-	 * @return array
494
-	 */
495
-	public static function getVersion() {
496
-		OC_Util::loadVersion();
497
-		return self::$versionCache['OC_Version'];
498
-	}
499
-
500
-	/**
501
-	 * get the current installed version string of ownCloud
502
-	 *
503
-	 * @return string
504
-	 */
505
-	public static function getVersionString() {
506
-		OC_Util::loadVersion();
507
-		return self::$versionCache['OC_VersionString'];
508
-	}
509
-
510
-	/**
511
-	 * @deprecated the value is of no use anymore
512
-	 * @return string
513
-	 */
514
-	public static function getEditionString() {
515
-		return '';
516
-	}
517
-
518
-	/**
519
-	 * @description get the update channel of the current installed of ownCloud.
520
-	 * @return string
521
-	 */
522
-	public static function getChannel() {
523
-		OC_Util::loadVersion();
524
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
-	}
526
-
527
-	/**
528
-	 * @description get the build number of the current installed of ownCloud.
529
-	 * @return string
530
-	 */
531
-	public static function getBuild() {
532
-		OC_Util::loadVersion();
533
-		return self::$versionCache['OC_Build'];
534
-	}
535
-
536
-	/**
537
-	 * @description load the version.php into the session as cache
538
-	 * @suppress PhanUndeclaredVariable
539
-	 */
540
-	private static function loadVersion() {
541
-		if (self::$versionCache !== null) {
542
-			return;
543
-		}
544
-
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
547
-		/** @var int $timestamp */
548
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
-		/** @var string $OC_Version */
550
-		self::$versionCache['OC_Version'] = $OC_Version;
551
-		/** @var string $OC_VersionString */
552
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
-		/** @var string $OC_Build */
554
-		self::$versionCache['OC_Build'] = $OC_Build;
555
-
556
-		/** @var string $OC_Channel */
557
-		self::$versionCache['OC_Channel'] = $OC_Channel;
558
-	}
559
-
560
-	/**
561
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
-	 *
563
-	 * @param string $application application to get the files from
564
-	 * @param string $directory directory within this application (css, js, vendor, etc)
565
-	 * @param string $file the file inside of the above folder
566
-	 * @return string the path
567
-	 */
568
-	private static function generatePath($application, $directory, $file) {
569
-		if (is_null($file)) {
570
-			$file = $application;
571
-			$application = "";
572
-		}
573
-		if (!empty($application)) {
574
-			return "$application/$directory/$file";
575
-		} else {
576
-			return "$directory/$file";
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * add a javascript file
582
-	 *
583
-	 * @deprecated 24.0.0 - Use \OCP\Util::addScript
584
-	 *
585
-	 * @param string $application application id
586
-	 * @param string|null $file filename
587
-	 * @param bool $prepend prepend the Script to the beginning of the list
588
-	 * @return void
589
-	 */
590
-	public static function addScript($application, $file = null, $prepend = false) {
591
-		$path = OC_Util::generatePath($application, 'js', $file);
592
-
593
-		// core js files need separate handling
594
-		if ($application !== 'core' && $file !== null) {
595
-			self::addTranslations($application);
596
-		}
597
-		self::addExternalResource($application, $prepend, $path, "script");
598
-	}
599
-
600
-	/**
601
-	 * add a javascript file from the vendor sub folder
602
-	 *
603
-	 * @param string $application application id
604
-	 * @param string|null $file filename
605
-	 * @param bool $prepend prepend the Script to the beginning of the list
606
-	 * @return void
607
-	 */
608
-	public static function addVendorScript($application, $file = null, $prepend = false) {
609
-		$path = OC_Util::generatePath($application, 'vendor', $file);
610
-		self::addExternalResource($application, $prepend, $path, "script");
611
-	}
612
-
613
-	/**
614
-	 * add a translation JS file
615
-	 *
616
-	 * @deprecated 24.0.0
617
-	 *
618
-	 * @param string $application application id
619
-	 * @param string|null $languageCode language code, defaults to the current language
620
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
621
-	 */
622
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
623
-		if (is_null($languageCode)) {
624
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
625
-		}
626
-		if (!empty($application)) {
627
-			$path = "$application/l10n/$languageCode";
628
-		} else {
629
-			$path = "l10n/$languageCode";
630
-		}
631
-		self::addExternalResource($application, $prepend, $path, "script");
632
-	}
633
-
634
-	/**
635
-	 * add a css file
636
-	 *
637
-	 * @param string $application application id
638
-	 * @param string|null $file filename
639
-	 * @param bool $prepend prepend the Style to the beginning of the list
640
-	 * @return void
641
-	 */
642
-	public static function addStyle($application, $file = null, $prepend = false) {
643
-		$path = OC_Util::generatePath($application, 'css', $file);
644
-		self::addExternalResource($application, $prepend, $path, "style");
645
-	}
646
-
647
-	/**
648
-	 * add a css file from the vendor sub folder
649
-	 *
650
-	 * @param string $application application id
651
-	 * @param string|null $file filename
652
-	 * @param bool $prepend prepend the Style to the beginning of the list
653
-	 * @return void
654
-	 */
655
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
656
-		$path = OC_Util::generatePath($application, 'vendor', $file);
657
-		self::addExternalResource($application, $prepend, $path, "style");
658
-	}
659
-
660
-	/**
661
-	 * add an external resource css/js file
662
-	 *
663
-	 * @param string $application application id
664
-	 * @param bool $prepend prepend the file to the beginning of the list
665
-	 * @param string $path
666
-	 * @param string $type (script or style)
667
-	 * @return void
668
-	 */
669
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
670
-		if ($type === "style") {
671
-			if (!in_array($path, self::$styles)) {
672
-				if ($prepend === true) {
673
-					array_unshift(self::$styles, $path);
674
-				} else {
675
-					self::$styles[] = $path;
676
-				}
677
-			}
678
-		} elseif ($type === "script") {
679
-			if (!in_array($path, self::$scripts)) {
680
-				if ($prepend === true) {
681
-					array_unshift(self::$scripts, $path);
682
-				} else {
683
-					self::$scripts [] = $path;
684
-				}
685
-			}
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * Add a custom element to the header
691
-	 * If $text is null then the element will be written as empty element.
692
-	 * So use "" to get a closing tag.
693
-	 * @param string $tag tag name of the element
694
-	 * @param array $attributes array of attributes for the element
695
-	 * @param string $text the text content for the element
696
-	 * @param bool $prepend prepend the header to the beginning of the list
697
-	 */
698
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
699
-		$header = [
700
-			'tag' => $tag,
701
-			'attributes' => $attributes,
702
-			'text' => $text
703
-		];
704
-		if ($prepend === true) {
705
-			array_unshift(self::$headers, $header);
706
-		} else {
707
-			self::$headers[] = $header;
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * check if the current server configuration is suitable for ownCloud
713
-	 *
714
-	 * @param \OC\SystemConfig $config
715
-	 * @return array arrays with error messages and hints
716
-	 */
717
-	public static function checkServer(\OC\SystemConfig $config) {
718
-		$l = \OC::$server->getL10N('lib');
719
-		$errors = [];
720
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
721
-
722
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
723
-			// this check needs to be done every time
724
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
725
-		}
726
-
727
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
728
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
729
-			return $errors;
730
-		}
731
-
732
-		$webServerRestart = false;
733
-		$setup = new \OC\Setup(
734
-			$config,
735
-			\OC::$server->get(IniGetWrapper::class),
736
-			\OC::$server->getL10N('lib'),
737
-			\OC::$server->get(\OCP\Defaults::class),
738
-			\OC::$server->get(LoggerInterface::class),
739
-			\OC::$server->getSecureRandom(),
740
-			\OC::$server->get(\OC\Installer::class)
741
-		);
742
-
743
-		$urlGenerator = \OC::$server->getURLGenerator();
744
-
745
-		$availableDatabases = $setup->getSupportedDatabases();
746
-		if (empty($availableDatabases)) {
747
-			$errors[] = [
748
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
749
-				'hint' => '' //TODO: sane hint
750
-			];
751
-			$webServerRestart = true;
752
-		}
753
-
754
-		// Check if config folder is writable.
755
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
756
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
757
-				$errors[] = [
758
-					'error' => $l->t('Cannot write into "config" directory.'),
759
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
761
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
762
-						[ $urlGenerator->linkToDocs('admin-config') ])
763
-				];
764
-			}
765
-		}
766
-
767
-		// Check if there is a writable install folder.
768
-		if ($config->getValue('appstoreenabled', true)) {
769
-			if (OC_App::getInstallPath() === null
770
-				|| !is_writable(OC_App::getInstallPath())
771
-				|| !is_readable(OC_App::getInstallPath())
772
-			) {
773
-				$errors[] = [
774
-					'error' => $l->t('Cannot write into "apps" directory.'),
775
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
776
-						. ' or disabling the App Store in the config file.')
777
-				];
778
-			}
779
-		}
780
-		// Create root dir.
781
-		if ($config->getValue('installed', false)) {
782
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
783
-				$success = @mkdir($CONFIG_DATADIRECTORY);
784
-				if ($success) {
785
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
786
-				} else {
787
-					$errors[] = [
788
-						'error' => $l->t('Cannot create "data" directory.'),
789
-						'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
790
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
791
-					];
792
-				}
793
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
794
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
795
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
796
-				$handle = fopen($testFile, 'w');
797
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
798
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
799
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
800
-					$errors[] = [
801
-						'error' => $l->t('Your data directory is not writable.'),
802
-						'hint' => $permissionsHint
803
-					];
804
-				} else {
805
-					fclose($handle);
806
-					unlink($testFile);
807
-				}
808
-			} else {
809
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
810
-			}
811
-		}
812
-
813
-		if (!OC_Util::isSetLocaleWorking()) {
814
-			$errors[] = [
815
-				'error' => $l->t('Setting locale to %s failed.',
816
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
817
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
818
-				'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
819
-			];
820
-		}
821
-
822
-		// Contains the dependencies that should be checked against
823
-		// classes = class_exists
824
-		// functions = function_exists
825
-		// defined = defined
826
-		// ini = ini_get
827
-		// If the dependency is not found the missing module name is shown to the EndUser
828
-		// When adding new checks always verify that they pass on Travis as well
829
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
830
-		$dependencies = [
831
-			'classes' => [
832
-				'ZipArchive' => 'zip',
833
-				'DOMDocument' => 'dom',
834
-				'XMLWriter' => 'XMLWriter',
835
-				'XMLReader' => 'XMLReader',
836
-			],
837
-			'functions' => [
838
-				'xml_parser_create' => 'libxml',
839
-				'mb_strcut' => 'mbstring',
840
-				'ctype_digit' => 'ctype',
841
-				'json_encode' => 'JSON',
842
-				'gd_info' => 'GD',
843
-				'gzencode' => 'zlib',
844
-				'simplexml_load_string' => 'SimpleXML',
845
-				'hash' => 'HASH Message Digest Framework',
846
-				'curl_init' => 'cURL',
847
-				'openssl_verify' => 'OpenSSL',
848
-			],
849
-			'defined' => [
850
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
851
-			],
852
-			'ini' => [
853
-				'default_charset' => 'UTF-8',
854
-			],
855
-		];
856
-		$missingDependencies = [];
857
-		$invalidIniSettings = [];
858
-
859
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
860
-		foreach ($dependencies['classes'] as $class => $module) {
861
-			if (!class_exists($class)) {
862
-				$missingDependencies[] = $module;
863
-			}
864
-		}
865
-		foreach ($dependencies['functions'] as $function => $module) {
866
-			if (!function_exists($function)) {
867
-				$missingDependencies[] = $module;
868
-			}
869
-		}
870
-		foreach ($dependencies['defined'] as $defined => $module) {
871
-			if (!defined($defined)) {
872
-				$missingDependencies[] = $module;
873
-			}
874
-		}
875
-		foreach ($dependencies['ini'] as $setting => $expected) {
876
-			if (is_bool($expected)) {
877
-				if ($iniWrapper->getBool($setting) !== $expected) {
878
-					$invalidIniSettings[] = [$setting, $expected];
879
-				}
880
-			}
881
-			if (is_int($expected)) {
882
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
883
-					$invalidIniSettings[] = [$setting, $expected];
884
-				}
885
-			}
886
-			if (is_string($expected)) {
887
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
-					$invalidIniSettings[] = [$setting, $expected];
889
-				}
890
-			}
891
-		}
892
-
893
-		foreach ($missingDependencies as $missingDependency) {
894
-			$errors[] = [
895
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
897
-			];
898
-			$webServerRestart = true;
899
-		}
900
-		foreach ($invalidIniSettings as $setting) {
901
-			if (is_bool($setting[1])) {
902
-				$setting[1] = $setting[1] ? 'on' : 'off';
903
-			}
904
-			$errors[] = [
905
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
-				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
-			];
908
-			$webServerRestart = true;
909
-		}
910
-
911
-		/**
912
-		 * The mbstring.func_overload check can only be performed if the mbstring
913
-		 * module is installed as it will return null if the checking setting is
914
-		 * not available and thus a check on the boolean value fails.
915
-		 *
916
-		 * TODO: Should probably be implemented in the above generic dependency
917
-		 *       check somehow in the long-term.
918
-		 */
919
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
921
-			$errors[] = [
922
-				'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
923
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
924
-			];
925
-		}
926
-
927
-		if (function_exists('xml_parser_create') &&
928
-			LIBXML_LOADED_VERSION < 20700) {
929
-			$version = LIBXML_LOADED_VERSION;
930
-			$major = floor($version / 10000);
931
-			$version -= ($major * 10000);
932
-			$minor = floor($version / 100);
933
-			$version -= ($minor * 100);
934
-			$patch = $version;
935
-			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
-			];
939
-		}
940
-
941
-		if (!self::isAnnotationsWorking()) {
942
-			$errors[] = [
943
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
-			];
946
-		}
947
-
948
-		if (!\OC::$CLI && $webServerRestart) {
949
-			$errors[] = [
950
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
-			];
953
-		}
954
-
955
-		$errors = array_merge($errors, self::checkDatabaseVersion());
956
-
957
-		// Cache the result of this function
958
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
-
960
-		return $errors;
961
-	}
962
-
963
-	/**
964
-	 * Check the database version
965
-	 *
966
-	 * @return array errors array
967
-	 */
968
-	public static function checkDatabaseVersion() {
969
-		$l = \OC::$server->getL10N('lib');
970
-		$errors = [];
971
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
-		if ($dbType === 'pgsql') {
973
-			// check PostgreSQL version
974
-			try {
975
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
-				$data = $result->fetchRow();
977
-				$result->closeCursor();
978
-				if (isset($data['server_version'])) {
979
-					$version = $data['server_version'];
980
-					if (version_compare($version, '9.0.0', '<')) {
981
-						$errors[] = [
982
-							'error' => $l->t('PostgreSQL >= 9 required.'),
983
-							'hint' => $l->t('Please upgrade your database version.')
984
-						];
985
-					}
986
-				}
987
-			} catch (\Doctrine\DBAL\Exception $e) {
988
-				$logger = \OC::$server->getLogger();
989
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
990
-				$logger->logException($e);
991
-			}
992
-		}
993
-		return $errors;
994
-	}
995
-
996
-	/**
997
-	 * Check for correct file permissions of data directory
998
-	 *
999
-	 * @param string $dataDirectory
1000
-	 * @return array arrays with error messages and hints
1001
-	 */
1002
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1003
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1004
-			return  [];
1005
-		}
1006
-
1007
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1008
-		if (substr($perms, -1) !== '0') {
1009
-			chmod($dataDirectory, 0770);
1010
-			clearstatcache();
1011
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1012
-			if ($perms[2] !== '0') {
1013
-				$l = \OC::$server->getL10N('lib');
1014
-				return [[
1015
-					'error' => $l->t('Your data directory is readable by other users.'),
1016
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1017
-				]];
1018
-			}
1019
-		}
1020
-		return [];
1021
-	}
1022
-
1023
-	/**
1024
-	 * Check that the data directory exists and is valid by
1025
-	 * checking the existence of the ".ocdata" file.
1026
-	 *
1027
-	 * @param string $dataDirectory data directory path
1028
-	 * @return array errors found
1029
-	 */
1030
-	public static function checkDataDirectoryValidity($dataDirectory) {
1031
-		$l = \OC::$server->getL10N('lib');
1032
-		$errors = [];
1033
-		if ($dataDirectory[0] !== '/') {
1034
-			$errors[] = [
1035
-				'error' => $l->t('Your data directory must be an absolute path.'),
1036
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
1037
-			];
1038
-		}
1039
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1040
-			$errors[] = [
1041
-				'error' => $l->t('Your data directory is invalid.'),
1042
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1043
-					' in the root of the data directory.')
1044
-			];
1045
-		}
1046
-		return $errors;
1047
-	}
1048
-
1049
-	/**
1050
-	 * Check if the user is logged in, redirects to home if not. With
1051
-	 * redirect URL parameter to the request URI.
1052
-	 *
1053
-	 * @return void
1054
-	 */
1055
-	public static function checkLoggedIn() {
1056
-		// Check if we are a user
1057
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1058
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1059
-						'core.login.showLoginForm',
1060
-						[
1061
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1062
-						]
1063
-					)
1064
-			);
1065
-			exit();
1066
-		}
1067
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1068
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1069
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1070
-			exit();
1071
-		}
1072
-	}
1073
-
1074
-	/**
1075
-	 * Check if the user is a admin, redirects to home if not
1076
-	 *
1077
-	 * @return void
1078
-	 */
1079
-	public static function checkAdminUser() {
1080
-		OC_Util::checkLoggedIn();
1081
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1082
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1083
-			exit();
1084
-		}
1085
-	}
1086
-
1087
-	/**
1088
-	 * Returns the URL of the default page
1089
-	 * based on the system configuration and
1090
-	 * the apps visible for the current user
1091
-	 *
1092
-	 * @return string URL
1093
-	 * @suppress PhanDeprecatedFunction
1094
-	 */
1095
-	public static function getDefaultPageUrl() {
1096
-		/** @var IURLGenerator $urlGenerator */
1097
-		$urlGenerator = \OC::$server->get(IURLGenerator::class);
1098
-		return $urlGenerator->linkToDefaultPageUrl();
1099
-	}
1100
-
1101
-	/**
1102
-	 * Redirect to the user default page
1103
-	 *
1104
-	 * @return void
1105
-	 */
1106
-	public static function redirectToDefaultPage() {
1107
-		$location = self::getDefaultPageUrl();
1108
-		header('Location: ' . $location);
1109
-		exit();
1110
-	}
1111
-
1112
-	/**
1113
-	 * get an id unique for this instance
1114
-	 *
1115
-	 * @return string
1116
-	 */
1117
-	public static function getInstanceId() {
1118
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1119
-		if (is_null($id)) {
1120
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1121
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1122
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1123
-		}
1124
-		return $id;
1125
-	}
1126
-
1127
-	/**
1128
-	 * Public function to sanitize HTML
1129
-	 *
1130
-	 * This function is used to sanitize HTML and should be applied on any
1131
-	 * string or array of strings before displaying it on a web page.
1132
-	 *
1133
-	 * @param string|string[] $value
1134
-	 * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
1135
-	 */
1136
-	public static function sanitizeHTML($value) {
1137
-		if (is_array($value)) {
1138
-			/** @var string[] $value */
1139
-			$value = array_map(function ($value) {
1140
-				return self::sanitizeHTML($value);
1141
-			}, $value);
1142
-		} else {
1143
-			// Specify encoding for PHP<5.4
1144
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1145
-		}
1146
-		return $value;
1147
-	}
1148
-
1149
-	/**
1150
-	 * Public function to encode url parameters
1151
-	 *
1152
-	 * This function is used to encode path to file before output.
1153
-	 * Encoding is done according to RFC 3986 with one exception:
1154
-	 * Character '/' is preserved as is.
1155
-	 *
1156
-	 * @param string $component part of URI to encode
1157
-	 * @return string
1158
-	 */
1159
-	public static function encodePath($component) {
1160
-		$encoded = rawurlencode($component);
1161
-		$encoded = str_replace('%2F', '/', $encoded);
1162
-		return $encoded;
1163
-	}
1164
-
1165
-
1166
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1167
-		// php dev server does not support htaccess
1168
-		if (php_sapi_name() === 'cli-server') {
1169
-			return false;
1170
-		}
1171
-
1172
-		// testdata
1173
-		$fileName = '/htaccesstest.txt';
1174
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1175
-
1176
-		// creating a test file
1177
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1178
-
1179
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1180
-			return false;
1181
-		}
1182
-
1183
-		$fp = @fopen($testFile, 'w');
1184
-		if (!$fp) {
1185
-			throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
1186
-				'Make sure it is possible for the web server to write to ' . $testFile);
1187
-		}
1188
-		fwrite($fp, $testContent);
1189
-		fclose($fp);
1190
-
1191
-		return $testContent;
1192
-	}
1193
-
1194
-	/**
1195
-	 * Check if the .htaccess file is working
1196
-	 *
1197
-	 * @param \OCP\IConfig $config
1198
-	 * @return bool
1199
-	 * @throws Exception
1200
-	 * @throws \OCP\HintException If the test file can't get written.
1201
-	 */
1202
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1203
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1204
-			return true;
1205
-		}
1206
-
1207
-		$testContent = $this->createHtaccessTestFile($config);
1208
-		if ($testContent === false) {
1209
-			return false;
1210
-		}
1211
-
1212
-		$fileName = '/htaccesstest.txt';
1213
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1214
-
1215
-		// accessing the file via http
1216
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1217
-		try {
1218
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1219
-		} catch (\Exception $e) {
1220
-			$content = false;
1221
-		}
1222
-
1223
-		if (strpos($url, 'https:') === 0) {
1224
-			$url = 'http:' . substr($url, 6);
1225
-		} else {
1226
-			$url = 'https:' . substr($url, 5);
1227
-		}
1228
-
1229
-		try {
1230
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1231
-		} catch (\Exception $e) {
1232
-			$fallbackContent = false;
1233
-		}
1234
-
1235
-		// cleanup
1236
-		@unlink($testFile);
1237
-
1238
-		/*
276
+            if ($mount->getOption('readonly', false)) {
277
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
278
+                    'storage' => $storage,
279
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
280
+                        \OCP\Constants::PERMISSION_UPDATE |
281
+                        \OCP\Constants::PERMISSION_CREATE |
282
+                        \OCP\Constants::PERMISSION_DELETE
283
+                    ),
284
+                ]);
285
+            }
286
+            return $storage;
287
+        });
288
+
289
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
290
+
291
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
292
+
293
+        //check if we are using an object storage
294
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
295
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
296
+
297
+        // use the same order as in ObjectHomeMountProvider
298
+        if (isset($objectStoreMultibucket)) {
299
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
300
+        } elseif (isset($objectStore)) {
301
+            self::initObjectStoreRootFS($objectStore);
302
+        } else {
303
+            self::initLocalStorageRootFS();
304
+        }
305
+
306
+        /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
307
+        $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
308
+        $rootMountProviders = $mountProviderCollection->getRootMounts();
309
+
310
+        /** @var \OC\Files\Mount\Manager $mountManager */
311
+        $mountManager = \OC\Files\Filesystem::getMountManager();
312
+        foreach ($rootMountProviders as $rootMountProvider) {
313
+            $mountManager->addMount($rootMountProvider);
314
+        }
315
+
316
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
317
+            \OC::$server->getEventLogger()->end('setup_fs');
318
+            return false;
319
+        }
320
+
321
+        //if we aren't logged in, there is no use to set up the filesystem
322
+        if ($user != "") {
323
+            $userDir = '/' . $user . '/files';
324
+
325
+            //jail the user into his "home" directory
326
+            \OC\Files\Filesystem::init($user, $userDir);
327
+
328
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
329
+        }
330
+        \OC::$server->getEventLogger()->end('setup_fs');
331
+        return true;
332
+    }
333
+
334
+    /**
335
+     * check if a password is required for each public link
336
+     *
337
+     * @return boolean
338
+     * @suppress PhanDeprecatedFunction
339
+     */
340
+    public static function isPublicLinkPasswordRequired() {
341
+        /** @var IManager $shareManager */
342
+        $shareManager = \OC::$server->get(IManager::class);
343
+        return $shareManager->shareApiLinkEnforcePassword();
344
+    }
345
+
346
+    /**
347
+     * check if sharing is disabled for the current user
348
+     * @param IConfig $config
349
+     * @param IGroupManager $groupManager
350
+     * @param IUser|null $user
351
+     * @return bool
352
+     */
353
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
354
+        /** @var IManager $shareManager */
355
+        $shareManager = \OC::$server->get(IManager::class);
356
+        $userId = $user ? $user->getUID() : null;
357
+        return $shareManager->sharingDisabledForUser($userId);
358
+    }
359
+
360
+    /**
361
+     * check if share API enforces a default expire date
362
+     *
363
+     * @return boolean
364
+     * @suppress PhanDeprecatedFunction
365
+     */
366
+    public static function isDefaultExpireDateEnforced() {
367
+        /** @var IManager $shareManager */
368
+        $shareManager = \OC::$server->get(IManager::class);
369
+        return $shareManager->shareApiLinkDefaultExpireDateEnforced();
370
+    }
371
+
372
+    /**
373
+     * Get the quota of a user
374
+     *
375
+     * @param IUser|null $user
376
+     * @return float Quota bytes
377
+     */
378
+    public static function getUserQuota(?IUser $user) {
379
+        if (is_null($user)) {
380
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
381
+        }
382
+        $userQuota = $user->getQuota();
383
+        if ($userQuota === 'none') {
384
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
+        }
386
+        return OC_Helper::computerFileSize($userQuota);
387
+    }
388
+
389
+    /**
390
+     * copies the skeleton to the users /files
391
+     *
392
+     * @param string $userId
393
+     * @param \OCP\Files\Folder $userDirectory
394
+     * @throws \OCP\Files\NotFoundException
395
+     * @throws \OCP\Files\NotPermittedException
396
+     * @suppress PhanDeprecatedFunction
397
+     */
398
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
399
+        /** @var LoggerInterface $logger */
400
+        $logger = \OC::$server->get(LoggerInterface::class);
401
+
402
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
404
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
+
406
+        if (!file_exists($skeletonDirectory)) {
407
+            $dialectStart = strpos($userLang, '_');
408
+            if ($dialectStart !== false) {
409
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
+            }
411
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
+            }
414
+            if (!file_exists($skeletonDirectory)) {
415
+                $skeletonDirectory = '';
416
+            }
417
+        }
418
+
419
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
+
421
+        if ($instanceId === null) {
422
+            throw new \RuntimeException('no instance id!');
423
+        }
424
+        $appdata = 'appdata_' . $instanceId;
425
+        if ($userId === $appdata) {
426
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
427
+        }
428
+
429
+        if (!empty($skeletonDirectory)) {
430
+            $logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
431
+            self::copyr($skeletonDirectory, $userDirectory);
432
+            // update the file cache
433
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
434
+
435
+            /** @var ITemplateManager $templateManager */
436
+            $templateManager = \OC::$server->get(ITemplateManager::class);
437
+            $templateManager->initializeTemplateDirectory(null, $userId);
438
+        }
439
+    }
440
+
441
+    /**
442
+     * copies a directory recursively by using streams
443
+     *
444
+     * @param string $source
445
+     * @param \OCP\Files\Folder $target
446
+     * @return void
447
+     */
448
+    public static function copyr($source, \OCP\Files\Folder $target) {
449
+        $logger = \OC::$server->getLogger();
450
+
451
+        // Verify if folder exists
452
+        $dir = opendir($source);
453
+        if ($dir === false) {
454
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
+            return;
456
+        }
457
+
458
+        // Copy the files
459
+        while (false !== ($file = readdir($dir))) {
460
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
+                if (is_dir($source . '/' . $file)) {
462
+                    $child = $target->newFolder($file);
463
+                    self::copyr($source . '/' . $file, $child);
464
+                } else {
465
+                    $child = $target->newFile($file);
466
+                    $sourceStream = fopen($source . '/' . $file, 'r');
467
+                    if ($sourceStream === false) {
468
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
+                        closedir($dir);
470
+                        return;
471
+                    }
472
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
+                }
474
+            }
475
+        }
476
+        closedir($dir);
477
+    }
478
+
479
+    /**
480
+     * @return void
481
+     * @suppress PhanUndeclaredMethod
482
+     */
483
+    public static function tearDownFS() {
484
+        \OC\Files\Filesystem::tearDown();
485
+        \OC::$server->getRootFolder()->clearCache();
486
+        self::$fsSetup = false;
487
+        self::$rootMounted = false;
488
+    }
489
+
490
+    /**
491
+     * get the current installed version of ownCloud
492
+     *
493
+     * @return array
494
+     */
495
+    public static function getVersion() {
496
+        OC_Util::loadVersion();
497
+        return self::$versionCache['OC_Version'];
498
+    }
499
+
500
+    /**
501
+     * get the current installed version string of ownCloud
502
+     *
503
+     * @return string
504
+     */
505
+    public static function getVersionString() {
506
+        OC_Util::loadVersion();
507
+        return self::$versionCache['OC_VersionString'];
508
+    }
509
+
510
+    /**
511
+     * @deprecated the value is of no use anymore
512
+     * @return string
513
+     */
514
+    public static function getEditionString() {
515
+        return '';
516
+    }
517
+
518
+    /**
519
+     * @description get the update channel of the current installed of ownCloud.
520
+     * @return string
521
+     */
522
+    public static function getChannel() {
523
+        OC_Util::loadVersion();
524
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
+    }
526
+
527
+    /**
528
+     * @description get the build number of the current installed of ownCloud.
529
+     * @return string
530
+     */
531
+    public static function getBuild() {
532
+        OC_Util::loadVersion();
533
+        return self::$versionCache['OC_Build'];
534
+    }
535
+
536
+    /**
537
+     * @description load the version.php into the session as cache
538
+     * @suppress PhanUndeclaredVariable
539
+     */
540
+    private static function loadVersion() {
541
+        if (self::$versionCache !== null) {
542
+            return;
543
+        }
544
+
545
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
+        require OC::$SERVERROOT . '/version.php';
547
+        /** @var int $timestamp */
548
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
+        /** @var string $OC_Version */
550
+        self::$versionCache['OC_Version'] = $OC_Version;
551
+        /** @var string $OC_VersionString */
552
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
+        /** @var string $OC_Build */
554
+        self::$versionCache['OC_Build'] = $OC_Build;
555
+
556
+        /** @var string $OC_Channel */
557
+        self::$versionCache['OC_Channel'] = $OC_Channel;
558
+    }
559
+
560
+    /**
561
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
+     *
563
+     * @param string $application application to get the files from
564
+     * @param string $directory directory within this application (css, js, vendor, etc)
565
+     * @param string $file the file inside of the above folder
566
+     * @return string the path
567
+     */
568
+    private static function generatePath($application, $directory, $file) {
569
+        if (is_null($file)) {
570
+            $file = $application;
571
+            $application = "";
572
+        }
573
+        if (!empty($application)) {
574
+            return "$application/$directory/$file";
575
+        } else {
576
+            return "$directory/$file";
577
+        }
578
+    }
579
+
580
+    /**
581
+     * add a javascript file
582
+     *
583
+     * @deprecated 24.0.0 - Use \OCP\Util::addScript
584
+     *
585
+     * @param string $application application id
586
+     * @param string|null $file filename
587
+     * @param bool $prepend prepend the Script to the beginning of the list
588
+     * @return void
589
+     */
590
+    public static function addScript($application, $file = null, $prepend = false) {
591
+        $path = OC_Util::generatePath($application, 'js', $file);
592
+
593
+        // core js files need separate handling
594
+        if ($application !== 'core' && $file !== null) {
595
+            self::addTranslations($application);
596
+        }
597
+        self::addExternalResource($application, $prepend, $path, "script");
598
+    }
599
+
600
+    /**
601
+     * add a javascript file from the vendor sub folder
602
+     *
603
+     * @param string $application application id
604
+     * @param string|null $file filename
605
+     * @param bool $prepend prepend the Script to the beginning of the list
606
+     * @return void
607
+     */
608
+    public static function addVendorScript($application, $file = null, $prepend = false) {
609
+        $path = OC_Util::generatePath($application, 'vendor', $file);
610
+        self::addExternalResource($application, $prepend, $path, "script");
611
+    }
612
+
613
+    /**
614
+     * add a translation JS file
615
+     *
616
+     * @deprecated 24.0.0
617
+     *
618
+     * @param string $application application id
619
+     * @param string|null $languageCode language code, defaults to the current language
620
+     * @param bool|null $prepend prepend the Script to the beginning of the list
621
+     */
622
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
623
+        if (is_null($languageCode)) {
624
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
625
+        }
626
+        if (!empty($application)) {
627
+            $path = "$application/l10n/$languageCode";
628
+        } else {
629
+            $path = "l10n/$languageCode";
630
+        }
631
+        self::addExternalResource($application, $prepend, $path, "script");
632
+    }
633
+
634
+    /**
635
+     * add a css file
636
+     *
637
+     * @param string $application application id
638
+     * @param string|null $file filename
639
+     * @param bool $prepend prepend the Style to the beginning of the list
640
+     * @return void
641
+     */
642
+    public static function addStyle($application, $file = null, $prepend = false) {
643
+        $path = OC_Util::generatePath($application, 'css', $file);
644
+        self::addExternalResource($application, $prepend, $path, "style");
645
+    }
646
+
647
+    /**
648
+     * add a css file from the vendor sub folder
649
+     *
650
+     * @param string $application application id
651
+     * @param string|null $file filename
652
+     * @param bool $prepend prepend the Style to the beginning of the list
653
+     * @return void
654
+     */
655
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
656
+        $path = OC_Util::generatePath($application, 'vendor', $file);
657
+        self::addExternalResource($application, $prepend, $path, "style");
658
+    }
659
+
660
+    /**
661
+     * add an external resource css/js file
662
+     *
663
+     * @param string $application application id
664
+     * @param bool $prepend prepend the file to the beginning of the list
665
+     * @param string $path
666
+     * @param string $type (script or style)
667
+     * @return void
668
+     */
669
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
670
+        if ($type === "style") {
671
+            if (!in_array($path, self::$styles)) {
672
+                if ($prepend === true) {
673
+                    array_unshift(self::$styles, $path);
674
+                } else {
675
+                    self::$styles[] = $path;
676
+                }
677
+            }
678
+        } elseif ($type === "script") {
679
+            if (!in_array($path, self::$scripts)) {
680
+                if ($prepend === true) {
681
+                    array_unshift(self::$scripts, $path);
682
+                } else {
683
+                    self::$scripts [] = $path;
684
+                }
685
+            }
686
+        }
687
+    }
688
+
689
+    /**
690
+     * Add a custom element to the header
691
+     * If $text is null then the element will be written as empty element.
692
+     * So use "" to get a closing tag.
693
+     * @param string $tag tag name of the element
694
+     * @param array $attributes array of attributes for the element
695
+     * @param string $text the text content for the element
696
+     * @param bool $prepend prepend the header to the beginning of the list
697
+     */
698
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
699
+        $header = [
700
+            'tag' => $tag,
701
+            'attributes' => $attributes,
702
+            'text' => $text
703
+        ];
704
+        if ($prepend === true) {
705
+            array_unshift(self::$headers, $header);
706
+        } else {
707
+            self::$headers[] = $header;
708
+        }
709
+    }
710
+
711
+    /**
712
+     * check if the current server configuration is suitable for ownCloud
713
+     *
714
+     * @param \OC\SystemConfig $config
715
+     * @return array arrays with error messages and hints
716
+     */
717
+    public static function checkServer(\OC\SystemConfig $config) {
718
+        $l = \OC::$server->getL10N('lib');
719
+        $errors = [];
720
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
721
+
722
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
723
+            // this check needs to be done every time
724
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
725
+        }
726
+
727
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
728
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
729
+            return $errors;
730
+        }
731
+
732
+        $webServerRestart = false;
733
+        $setup = new \OC\Setup(
734
+            $config,
735
+            \OC::$server->get(IniGetWrapper::class),
736
+            \OC::$server->getL10N('lib'),
737
+            \OC::$server->get(\OCP\Defaults::class),
738
+            \OC::$server->get(LoggerInterface::class),
739
+            \OC::$server->getSecureRandom(),
740
+            \OC::$server->get(\OC\Installer::class)
741
+        );
742
+
743
+        $urlGenerator = \OC::$server->getURLGenerator();
744
+
745
+        $availableDatabases = $setup->getSupportedDatabases();
746
+        if (empty($availableDatabases)) {
747
+            $errors[] = [
748
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
749
+                'hint' => '' //TODO: sane hint
750
+            ];
751
+            $webServerRestart = true;
752
+        }
753
+
754
+        // Check if config folder is writable.
755
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
756
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
757
+                $errors[] = [
758
+                    'error' => $l->t('Cannot write into "config" directory.'),
759
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
760
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
761
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
762
+                        [ $urlGenerator->linkToDocs('admin-config') ])
763
+                ];
764
+            }
765
+        }
766
+
767
+        // Check if there is a writable install folder.
768
+        if ($config->getValue('appstoreenabled', true)) {
769
+            if (OC_App::getInstallPath() === null
770
+                || !is_writable(OC_App::getInstallPath())
771
+                || !is_readable(OC_App::getInstallPath())
772
+            ) {
773
+                $errors[] = [
774
+                    'error' => $l->t('Cannot write into "apps" directory.'),
775
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
776
+                        . ' or disabling the App Store in the config file.')
777
+                ];
778
+            }
779
+        }
780
+        // Create root dir.
781
+        if ($config->getValue('installed', false)) {
782
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
783
+                $success = @mkdir($CONFIG_DATADIRECTORY);
784
+                if ($success) {
785
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
786
+                } else {
787
+                    $errors[] = [
788
+                        'error' => $l->t('Cannot create "data" directory.'),
789
+                        'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
790
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
791
+                    ];
792
+                }
793
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
794
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
795
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
796
+                $handle = fopen($testFile, 'w');
797
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
798
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
799
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
800
+                    $errors[] = [
801
+                        'error' => $l->t('Your data directory is not writable.'),
802
+                        'hint' => $permissionsHint
803
+                    ];
804
+                } else {
805
+                    fclose($handle);
806
+                    unlink($testFile);
807
+                }
808
+            } else {
809
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
810
+            }
811
+        }
812
+
813
+        if (!OC_Util::isSetLocaleWorking()) {
814
+            $errors[] = [
815
+                'error' => $l->t('Setting locale to %s failed.',
816
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
817
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
818
+                'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
819
+            ];
820
+        }
821
+
822
+        // Contains the dependencies that should be checked against
823
+        // classes = class_exists
824
+        // functions = function_exists
825
+        // defined = defined
826
+        // ini = ini_get
827
+        // If the dependency is not found the missing module name is shown to the EndUser
828
+        // When adding new checks always verify that they pass on Travis as well
829
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
830
+        $dependencies = [
831
+            'classes' => [
832
+                'ZipArchive' => 'zip',
833
+                'DOMDocument' => 'dom',
834
+                'XMLWriter' => 'XMLWriter',
835
+                'XMLReader' => 'XMLReader',
836
+            ],
837
+            'functions' => [
838
+                'xml_parser_create' => 'libxml',
839
+                'mb_strcut' => 'mbstring',
840
+                'ctype_digit' => 'ctype',
841
+                'json_encode' => 'JSON',
842
+                'gd_info' => 'GD',
843
+                'gzencode' => 'zlib',
844
+                'simplexml_load_string' => 'SimpleXML',
845
+                'hash' => 'HASH Message Digest Framework',
846
+                'curl_init' => 'cURL',
847
+                'openssl_verify' => 'OpenSSL',
848
+            ],
849
+            'defined' => [
850
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
851
+            ],
852
+            'ini' => [
853
+                'default_charset' => 'UTF-8',
854
+            ],
855
+        ];
856
+        $missingDependencies = [];
857
+        $invalidIniSettings = [];
858
+
859
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
860
+        foreach ($dependencies['classes'] as $class => $module) {
861
+            if (!class_exists($class)) {
862
+                $missingDependencies[] = $module;
863
+            }
864
+        }
865
+        foreach ($dependencies['functions'] as $function => $module) {
866
+            if (!function_exists($function)) {
867
+                $missingDependencies[] = $module;
868
+            }
869
+        }
870
+        foreach ($dependencies['defined'] as $defined => $module) {
871
+            if (!defined($defined)) {
872
+                $missingDependencies[] = $module;
873
+            }
874
+        }
875
+        foreach ($dependencies['ini'] as $setting => $expected) {
876
+            if (is_bool($expected)) {
877
+                if ($iniWrapper->getBool($setting) !== $expected) {
878
+                    $invalidIniSettings[] = [$setting, $expected];
879
+                }
880
+            }
881
+            if (is_int($expected)) {
882
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
883
+                    $invalidIniSettings[] = [$setting, $expected];
884
+                }
885
+            }
886
+            if (is_string($expected)) {
887
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
+                    $invalidIniSettings[] = [$setting, $expected];
889
+                }
890
+            }
891
+        }
892
+
893
+        foreach ($missingDependencies as $missingDependency) {
894
+            $errors[] = [
895
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
897
+            ];
898
+            $webServerRestart = true;
899
+        }
900
+        foreach ($invalidIniSettings as $setting) {
901
+            if (is_bool($setting[1])) {
902
+                $setting[1] = $setting[1] ? 'on' : 'off';
903
+            }
904
+            $errors[] = [
905
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
+                'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
+            ];
908
+            $webServerRestart = true;
909
+        }
910
+
911
+        /**
912
+         * The mbstring.func_overload check can only be performed if the mbstring
913
+         * module is installed as it will return null if the checking setting is
914
+         * not available and thus a check on the boolean value fails.
915
+         *
916
+         * TODO: Should probably be implemented in the above generic dependency
917
+         *       check somehow in the long-term.
918
+         */
919
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
921
+            $errors[] = [
922
+                'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
923
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
924
+            ];
925
+        }
926
+
927
+        if (function_exists('xml_parser_create') &&
928
+            LIBXML_LOADED_VERSION < 20700) {
929
+            $version = LIBXML_LOADED_VERSION;
930
+            $major = floor($version / 10000);
931
+            $version -= ($major * 10000);
932
+            $minor = floor($version / 100);
933
+            $version -= ($minor * 100);
934
+            $patch = $version;
935
+            $errors[] = [
936
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
+            ];
939
+        }
940
+
941
+        if (!self::isAnnotationsWorking()) {
942
+            $errors[] = [
943
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
+            ];
946
+        }
947
+
948
+        if (!\OC::$CLI && $webServerRestart) {
949
+            $errors[] = [
950
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
+            ];
953
+        }
954
+
955
+        $errors = array_merge($errors, self::checkDatabaseVersion());
956
+
957
+        // Cache the result of this function
958
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
+
960
+        return $errors;
961
+    }
962
+
963
+    /**
964
+     * Check the database version
965
+     *
966
+     * @return array errors array
967
+     */
968
+    public static function checkDatabaseVersion() {
969
+        $l = \OC::$server->getL10N('lib');
970
+        $errors = [];
971
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
+        if ($dbType === 'pgsql') {
973
+            // check PostgreSQL version
974
+            try {
975
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
+                $data = $result->fetchRow();
977
+                $result->closeCursor();
978
+                if (isset($data['server_version'])) {
979
+                    $version = $data['server_version'];
980
+                    if (version_compare($version, '9.0.0', '<')) {
981
+                        $errors[] = [
982
+                            'error' => $l->t('PostgreSQL >= 9 required.'),
983
+                            'hint' => $l->t('Please upgrade your database version.')
984
+                        ];
985
+                    }
986
+                }
987
+            } catch (\Doctrine\DBAL\Exception $e) {
988
+                $logger = \OC::$server->getLogger();
989
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
990
+                $logger->logException($e);
991
+            }
992
+        }
993
+        return $errors;
994
+    }
995
+
996
+    /**
997
+     * Check for correct file permissions of data directory
998
+     *
999
+     * @param string $dataDirectory
1000
+     * @return array arrays with error messages and hints
1001
+     */
1002
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1003
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1004
+            return  [];
1005
+        }
1006
+
1007
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1008
+        if (substr($perms, -1) !== '0') {
1009
+            chmod($dataDirectory, 0770);
1010
+            clearstatcache();
1011
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1012
+            if ($perms[2] !== '0') {
1013
+                $l = \OC::$server->getL10N('lib');
1014
+                return [[
1015
+                    'error' => $l->t('Your data directory is readable by other users.'),
1016
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1017
+                ]];
1018
+            }
1019
+        }
1020
+        return [];
1021
+    }
1022
+
1023
+    /**
1024
+     * Check that the data directory exists and is valid by
1025
+     * checking the existence of the ".ocdata" file.
1026
+     *
1027
+     * @param string $dataDirectory data directory path
1028
+     * @return array errors found
1029
+     */
1030
+    public static function checkDataDirectoryValidity($dataDirectory) {
1031
+        $l = \OC::$server->getL10N('lib');
1032
+        $errors = [];
1033
+        if ($dataDirectory[0] !== '/') {
1034
+            $errors[] = [
1035
+                'error' => $l->t('Your data directory must be an absolute path.'),
1036
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
1037
+            ];
1038
+        }
1039
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1040
+            $errors[] = [
1041
+                'error' => $l->t('Your data directory is invalid.'),
1042
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1043
+                    ' in the root of the data directory.')
1044
+            ];
1045
+        }
1046
+        return $errors;
1047
+    }
1048
+
1049
+    /**
1050
+     * Check if the user is logged in, redirects to home if not. With
1051
+     * redirect URL parameter to the request URI.
1052
+     *
1053
+     * @return void
1054
+     */
1055
+    public static function checkLoggedIn() {
1056
+        // Check if we are a user
1057
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1058
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1059
+                        'core.login.showLoginForm',
1060
+                        [
1061
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1062
+                        ]
1063
+                    )
1064
+            );
1065
+            exit();
1066
+        }
1067
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1068
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1069
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1070
+            exit();
1071
+        }
1072
+    }
1073
+
1074
+    /**
1075
+     * Check if the user is a admin, redirects to home if not
1076
+     *
1077
+     * @return void
1078
+     */
1079
+    public static function checkAdminUser() {
1080
+        OC_Util::checkLoggedIn();
1081
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1082
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1083
+            exit();
1084
+        }
1085
+    }
1086
+
1087
+    /**
1088
+     * Returns the URL of the default page
1089
+     * based on the system configuration and
1090
+     * the apps visible for the current user
1091
+     *
1092
+     * @return string URL
1093
+     * @suppress PhanDeprecatedFunction
1094
+     */
1095
+    public static function getDefaultPageUrl() {
1096
+        /** @var IURLGenerator $urlGenerator */
1097
+        $urlGenerator = \OC::$server->get(IURLGenerator::class);
1098
+        return $urlGenerator->linkToDefaultPageUrl();
1099
+    }
1100
+
1101
+    /**
1102
+     * Redirect to the user default page
1103
+     *
1104
+     * @return void
1105
+     */
1106
+    public static function redirectToDefaultPage() {
1107
+        $location = self::getDefaultPageUrl();
1108
+        header('Location: ' . $location);
1109
+        exit();
1110
+    }
1111
+
1112
+    /**
1113
+     * get an id unique for this instance
1114
+     *
1115
+     * @return string
1116
+     */
1117
+    public static function getInstanceId() {
1118
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1119
+        if (is_null($id)) {
1120
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1121
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1122
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1123
+        }
1124
+        return $id;
1125
+    }
1126
+
1127
+    /**
1128
+     * Public function to sanitize HTML
1129
+     *
1130
+     * This function is used to sanitize HTML and should be applied on any
1131
+     * string or array of strings before displaying it on a web page.
1132
+     *
1133
+     * @param string|string[] $value
1134
+     * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
1135
+     */
1136
+    public static function sanitizeHTML($value) {
1137
+        if (is_array($value)) {
1138
+            /** @var string[] $value */
1139
+            $value = array_map(function ($value) {
1140
+                return self::sanitizeHTML($value);
1141
+            }, $value);
1142
+        } else {
1143
+            // Specify encoding for PHP<5.4
1144
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1145
+        }
1146
+        return $value;
1147
+    }
1148
+
1149
+    /**
1150
+     * Public function to encode url parameters
1151
+     *
1152
+     * This function is used to encode path to file before output.
1153
+     * Encoding is done according to RFC 3986 with one exception:
1154
+     * Character '/' is preserved as is.
1155
+     *
1156
+     * @param string $component part of URI to encode
1157
+     * @return string
1158
+     */
1159
+    public static function encodePath($component) {
1160
+        $encoded = rawurlencode($component);
1161
+        $encoded = str_replace('%2F', '/', $encoded);
1162
+        return $encoded;
1163
+    }
1164
+
1165
+
1166
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1167
+        // php dev server does not support htaccess
1168
+        if (php_sapi_name() === 'cli-server') {
1169
+            return false;
1170
+        }
1171
+
1172
+        // testdata
1173
+        $fileName = '/htaccesstest.txt';
1174
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1175
+
1176
+        // creating a test file
1177
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1178
+
1179
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1180
+            return false;
1181
+        }
1182
+
1183
+        $fp = @fopen($testFile, 'w');
1184
+        if (!$fp) {
1185
+            throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
1186
+                'Make sure it is possible for the web server to write to ' . $testFile);
1187
+        }
1188
+        fwrite($fp, $testContent);
1189
+        fclose($fp);
1190
+
1191
+        return $testContent;
1192
+    }
1193
+
1194
+    /**
1195
+     * Check if the .htaccess file is working
1196
+     *
1197
+     * @param \OCP\IConfig $config
1198
+     * @return bool
1199
+     * @throws Exception
1200
+     * @throws \OCP\HintException If the test file can't get written.
1201
+     */
1202
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1203
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1204
+            return true;
1205
+        }
1206
+
1207
+        $testContent = $this->createHtaccessTestFile($config);
1208
+        if ($testContent === false) {
1209
+            return false;
1210
+        }
1211
+
1212
+        $fileName = '/htaccesstest.txt';
1213
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1214
+
1215
+        // accessing the file via http
1216
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1217
+        try {
1218
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1219
+        } catch (\Exception $e) {
1220
+            $content = false;
1221
+        }
1222
+
1223
+        if (strpos($url, 'https:') === 0) {
1224
+            $url = 'http:' . substr($url, 6);
1225
+        } else {
1226
+            $url = 'https:' . substr($url, 5);
1227
+        }
1228
+
1229
+        try {
1230
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1231
+        } catch (\Exception $e) {
1232
+            $fallbackContent = false;
1233
+        }
1234
+
1235
+        // cleanup
1236
+        @unlink($testFile);
1237
+
1238
+        /*
1239 1239
 		 * If the content is not equal to test content our .htaccess
1240 1240
 		 * is working as required
1241 1241
 		 */
1242
-		return $content !== $testContent && $fallbackContent !== $testContent;
1243
-	}
1244
-
1245
-	/**
1246
-	 * Check if current locale is non-UTF8
1247
-	 *
1248
-	 * @return bool
1249
-	 */
1250
-	private static function isNonUTF8Locale() {
1251
-		if (function_exists('escapeshellcmd')) {
1252
-			return '' === escapeshellcmd('§');
1253
-		} elseif (function_exists('escapeshellarg')) {
1254
-			return '\'\'' === escapeshellarg('§');
1255
-		} else {
1256
-			return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
1257
-		}
1258
-	}
1259
-
1260
-	/**
1261
-	 * Check if the setlocale call does not work. This can happen if the right
1262
-	 * local packages are not available on the server.
1263
-	 *
1264
-	 * @return bool
1265
-	 */
1266
-	public static function isSetLocaleWorking() {
1267
-		if (self::isNonUTF8Locale()) {
1268
-			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
1269
-			setlocale(LC_ALL, 'C.UTF-8', 'C');
1270
-			setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1271
-
1272
-			// Check again
1273
-			if (self::isNonUTF8Locale()) {
1274
-				return false;
1275
-			}
1276
-		}
1277
-
1278
-		return true;
1279
-	}
1280
-
1281
-	/**
1282
-	 * Check if it's possible to get the inline annotations
1283
-	 *
1284
-	 * @return bool
1285
-	 */
1286
-	public static function isAnnotationsWorking() {
1287
-		$reflection = new \ReflectionMethod(__METHOD__);
1288
-		$docs = $reflection->getDocComment();
1289
-
1290
-		return (is_string($docs) && strlen($docs) > 50);
1291
-	}
1292
-
1293
-	/**
1294
-	 * Check if the PHP module fileinfo is loaded.
1295
-	 *
1296
-	 * @return bool
1297
-	 */
1298
-	public static function fileInfoLoaded() {
1299
-		return function_exists('finfo_open');
1300
-	}
1301
-
1302
-	/**
1303
-	 * clear all levels of output buffering
1304
-	 *
1305
-	 * @return void
1306
-	 */
1307
-	public static function obEnd() {
1308
-		while (ob_get_level()) {
1309
-			ob_end_clean();
1310
-		}
1311
-	}
1312
-
1313
-	/**
1314
-	 * Checks whether the server is running on Mac OS X
1315
-	 *
1316
-	 * @return bool true if running on Mac OS X, false otherwise
1317
-	 */
1318
-	public static function runningOnMac() {
1319
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1320
-	}
1321
-
1322
-	/**
1323
-	 * Handles the case that there may not be a theme, then check if a "default"
1324
-	 * theme exists and take that one
1325
-	 *
1326
-	 * @return string the theme
1327
-	 */
1328
-	public static function getTheme() {
1329
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1330
-
1331
-		if ($theme === '') {
1332
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1333
-				$theme = 'default';
1334
-			}
1335
-		}
1336
-
1337
-		return $theme;
1338
-	}
1339
-
1340
-	/**
1341
-	 * Normalize a unicode string
1342
-	 *
1343
-	 * @param string $value a not normalized string
1344
-	 * @return bool|string
1345
-	 */
1346
-	public static function normalizeUnicode($value) {
1347
-		if (Normalizer::isNormalized($value)) {
1348
-			return $value;
1349
-		}
1350
-
1351
-		$normalizedValue = Normalizer::normalize($value);
1352
-		if ($normalizedValue === null || $normalizedValue === false) {
1353
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1354
-			return $value;
1355
-		}
1356
-
1357
-		return $normalizedValue;
1358
-	}
1359
-
1360
-	/**
1361
-	 * A human readable string is generated based on version and build number
1362
-	 *
1363
-	 * @return string
1364
-	 */
1365
-	public static function getHumanVersion() {
1366
-		$version = OC_Util::getVersionString();
1367
-		$build = OC_Util::getBuild();
1368
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1369
-			$version .= ' Build:' . $build;
1370
-		}
1371
-		return $version;
1372
-	}
1373
-
1374
-	/**
1375
-	 * Returns whether the given file name is valid
1376
-	 *
1377
-	 * @param string $file file name to check
1378
-	 * @return bool true if the file name is valid, false otherwise
1379
-	 * @deprecated use \OC\Files\View::verifyPath()
1380
-	 */
1381
-	public static function isValidFileName($file) {
1382
-		$trimmed = trim($file);
1383
-		if ($trimmed === '') {
1384
-			return false;
1385
-		}
1386
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1387
-			return false;
1388
-		}
1389
-
1390
-		// detect part files
1391
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1392
-			return false;
1393
-		}
1394
-
1395
-		foreach (str_split($trimmed) as $char) {
1396
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1397
-				return false;
1398
-			}
1399
-		}
1400
-		return true;
1401
-	}
1402
-
1403
-	/**
1404
-	 * Check whether the instance needs to perform an upgrade,
1405
-	 * either when the core version is higher or any app requires
1406
-	 * an upgrade.
1407
-	 *
1408
-	 * @param \OC\SystemConfig $config
1409
-	 * @return bool whether the core or any app needs an upgrade
1410
-	 * @throws \OCP\HintException When the upgrade from the given version is not allowed
1411
-	 */
1412
-	public static function needUpgrade(\OC\SystemConfig $config) {
1413
-		if ($config->getValue('installed', false)) {
1414
-			$installedVersion = $config->getValue('version', '0.0.0');
1415
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1416
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1417
-			if ($versionDiff > 0) {
1418
-				return true;
1419
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1420
-				// downgrade with debug
1421
-				$installedMajor = explode('.', $installedVersion);
1422
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1423
-				$currentMajor = explode('.', $currentVersion);
1424
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1425
-				if ($installedMajor === $currentMajor) {
1426
-					// Same major, allow downgrade for developers
1427
-					return true;
1428
-				} else {
1429
-					// downgrade attempt, throw exception
1430
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1431
-				}
1432
-			} elseif ($versionDiff < 0) {
1433
-				// downgrade attempt, throw exception
1434
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1435
-			}
1436
-
1437
-			// also check for upgrades for apps (independently from the user)
1438
-			$apps = \OC_App::getEnabledApps(false, true);
1439
-			$shouldUpgrade = false;
1440
-			foreach ($apps as $app) {
1441
-				if (\OC_App::shouldUpgrade($app)) {
1442
-					$shouldUpgrade = true;
1443
-					break;
1444
-				}
1445
-			}
1446
-			return $shouldUpgrade;
1447
-		} else {
1448
-			return false;
1449
-		}
1450
-	}
1242
+        return $content !== $testContent && $fallbackContent !== $testContent;
1243
+    }
1244
+
1245
+    /**
1246
+     * Check if current locale is non-UTF8
1247
+     *
1248
+     * @return bool
1249
+     */
1250
+    private static function isNonUTF8Locale() {
1251
+        if (function_exists('escapeshellcmd')) {
1252
+            return '' === escapeshellcmd('§');
1253
+        } elseif (function_exists('escapeshellarg')) {
1254
+            return '\'\'' === escapeshellarg('§');
1255
+        } else {
1256
+            return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
1257
+        }
1258
+    }
1259
+
1260
+    /**
1261
+     * Check if the setlocale call does not work. This can happen if the right
1262
+     * local packages are not available on the server.
1263
+     *
1264
+     * @return bool
1265
+     */
1266
+    public static function isSetLocaleWorking() {
1267
+        if (self::isNonUTF8Locale()) {
1268
+            // Borrowed from \Patchwork\Utf8\Bootup::initLocale
1269
+            setlocale(LC_ALL, 'C.UTF-8', 'C');
1270
+            setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1271
+
1272
+            // Check again
1273
+            if (self::isNonUTF8Locale()) {
1274
+                return false;
1275
+            }
1276
+        }
1277
+
1278
+        return true;
1279
+    }
1280
+
1281
+    /**
1282
+     * Check if it's possible to get the inline annotations
1283
+     *
1284
+     * @return bool
1285
+     */
1286
+    public static function isAnnotationsWorking() {
1287
+        $reflection = new \ReflectionMethod(__METHOD__);
1288
+        $docs = $reflection->getDocComment();
1289
+
1290
+        return (is_string($docs) && strlen($docs) > 50);
1291
+    }
1292
+
1293
+    /**
1294
+     * Check if the PHP module fileinfo is loaded.
1295
+     *
1296
+     * @return bool
1297
+     */
1298
+    public static function fileInfoLoaded() {
1299
+        return function_exists('finfo_open');
1300
+    }
1301
+
1302
+    /**
1303
+     * clear all levels of output buffering
1304
+     *
1305
+     * @return void
1306
+     */
1307
+    public static function obEnd() {
1308
+        while (ob_get_level()) {
1309
+            ob_end_clean();
1310
+        }
1311
+    }
1312
+
1313
+    /**
1314
+     * Checks whether the server is running on Mac OS X
1315
+     *
1316
+     * @return bool true if running on Mac OS X, false otherwise
1317
+     */
1318
+    public static function runningOnMac() {
1319
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1320
+    }
1321
+
1322
+    /**
1323
+     * Handles the case that there may not be a theme, then check if a "default"
1324
+     * theme exists and take that one
1325
+     *
1326
+     * @return string the theme
1327
+     */
1328
+    public static function getTheme() {
1329
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1330
+
1331
+        if ($theme === '') {
1332
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1333
+                $theme = 'default';
1334
+            }
1335
+        }
1336
+
1337
+        return $theme;
1338
+    }
1339
+
1340
+    /**
1341
+     * Normalize a unicode string
1342
+     *
1343
+     * @param string $value a not normalized string
1344
+     * @return bool|string
1345
+     */
1346
+    public static function normalizeUnicode($value) {
1347
+        if (Normalizer::isNormalized($value)) {
1348
+            return $value;
1349
+        }
1350
+
1351
+        $normalizedValue = Normalizer::normalize($value);
1352
+        if ($normalizedValue === null || $normalizedValue === false) {
1353
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1354
+            return $value;
1355
+        }
1356
+
1357
+        return $normalizedValue;
1358
+    }
1359
+
1360
+    /**
1361
+     * A human readable string is generated based on version and build number
1362
+     *
1363
+     * @return string
1364
+     */
1365
+    public static function getHumanVersion() {
1366
+        $version = OC_Util::getVersionString();
1367
+        $build = OC_Util::getBuild();
1368
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1369
+            $version .= ' Build:' . $build;
1370
+        }
1371
+        return $version;
1372
+    }
1373
+
1374
+    /**
1375
+     * Returns whether the given file name is valid
1376
+     *
1377
+     * @param string $file file name to check
1378
+     * @return bool true if the file name is valid, false otherwise
1379
+     * @deprecated use \OC\Files\View::verifyPath()
1380
+     */
1381
+    public static function isValidFileName($file) {
1382
+        $trimmed = trim($file);
1383
+        if ($trimmed === '') {
1384
+            return false;
1385
+        }
1386
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1387
+            return false;
1388
+        }
1389
+
1390
+        // detect part files
1391
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1392
+            return false;
1393
+        }
1394
+
1395
+        foreach (str_split($trimmed) as $char) {
1396
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1397
+                return false;
1398
+            }
1399
+        }
1400
+        return true;
1401
+    }
1402
+
1403
+    /**
1404
+     * Check whether the instance needs to perform an upgrade,
1405
+     * either when the core version is higher or any app requires
1406
+     * an upgrade.
1407
+     *
1408
+     * @param \OC\SystemConfig $config
1409
+     * @return bool whether the core or any app needs an upgrade
1410
+     * @throws \OCP\HintException When the upgrade from the given version is not allowed
1411
+     */
1412
+    public static function needUpgrade(\OC\SystemConfig $config) {
1413
+        if ($config->getValue('installed', false)) {
1414
+            $installedVersion = $config->getValue('version', '0.0.0');
1415
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1416
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1417
+            if ($versionDiff > 0) {
1418
+                return true;
1419
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1420
+                // downgrade with debug
1421
+                $installedMajor = explode('.', $installedVersion);
1422
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1423
+                $currentMajor = explode('.', $currentVersion);
1424
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1425
+                if ($installedMajor === $currentMajor) {
1426
+                    // Same major, allow downgrade for developers
1427
+                    return true;
1428
+                } else {
1429
+                    // downgrade attempt, throw exception
1430
+                    throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1431
+                }
1432
+            } elseif ($versionDiff < 0) {
1433
+                // downgrade attempt, throw exception
1434
+                throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1435
+            }
1436
+
1437
+            // also check for upgrades for apps (independently from the user)
1438
+            $apps = \OC_App::getEnabledApps(false, true);
1439
+            $shouldUpgrade = false;
1440
+            foreach ($apps as $app) {
1441
+                if (\OC_App::shouldUpgrade($app)) {
1442
+                    $shouldUpgrade = true;
1443
+                    break;
1444
+                }
1445
+            }
1446
+            return $shouldUpgrade;
1447
+        } else {
1448
+            return false;
1449
+        }
1450
+    }
1451 1451
 }
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 
93 93
 	private static function initLocalStorageRootFS() {
94 94
 		// mount local file backend as root
95
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
95
+		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT."/data");
96 96
 		//first set up the local "root" storage
97 97
 		\OC\Files\Filesystem::initMountManager();
98 98
 		if (!self::$rootMounted) {
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 		\OC\Files\Filesystem::initMountManager();
215 215
 
216 216
 		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
217
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
217
+		\OC\Files\Filesystem::addStorageWrapper('mount_options', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218 218
 			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
219 219
 				/** @var \OC\Files\Storage\Common $storage */
220 220
 				$storage->setMountOptions($mount->getOptions());
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 			return $storage;
223 223
 		});
224 224
 
225
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
225
+		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
226 226
 			if (!$mount->getOption('enable_sharing', true)) {
227 227
 				return new \OC\Files\Storage\Wrapper\PermissionsMask([
228 228
 					'storage' => $storage,
@@ -233,21 +233,21 @@  discard block
 block discarded – undo
233 233
 		});
234 234
 
235 235
 		// install storage availability wrapper, before most other wrappers
236
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
236
+		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function($mountPoint, \OCP\Files\Storage\IStorage $storage) {
237 237
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
238 238
 				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
239 239
 			}
240 240
 			return $storage;
241 241
 		});
242 242
 
243
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
243
+		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
244 244
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
245 245
 				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
246 246
 			}
247 247
 			return $storage;
248 248
 		});
249 249
 
250
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
250
+		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
251 251
 			// set up quota for home storages, even for other users
252 252
 			// which can happen when using sharing
253 253
 
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 			return $storage;
270 270
 		});
271 271
 
272
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
272
+		\OC\Files\Filesystem::addStorageWrapper('readonly', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
273 273
 			/*
274 274
 			 * Do not allow any operations that modify the storage
275 275
 			 */
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 
321 321
 		//if we aren't logged in, there is no use to set up the filesystem
322 322
 		if ($user != "") {
323
-			$userDir = '/' . $user . '/files';
323
+			$userDir = '/'.$user.'/files';
324 324
 
325 325
 			//jail the user into his "home" directory
326 326
 			\OC\Files\Filesystem::init($user, $userDir);
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 		/** @var LoggerInterface $logger */
400 400
 		$logger = \OC::$server->get(LoggerInterface::class);
401 401
 
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
402
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
403 403
 		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404 404
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405 405
 
@@ -421,9 +421,9 @@  discard block
 block discarded – undo
421 421
 		if ($instanceId === null) {
422 422
 			throw new \RuntimeException('no instance id!');
423 423
 		}
424
-		$appdata = 'appdata_' . $instanceId;
424
+		$appdata = 'appdata_'.$instanceId;
425 425
 		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
426
+			throw new \RuntimeException('username is reserved name: '.$appdata);
427 427
 		}
428 428
 
429 429
 		if (!empty($skeletonDirectory)) {
@@ -458,14 +458,14 @@  discard block
 block discarded – undo
458 458
 		// Copy the files
459 459
 		while (false !== ($file = readdir($dir))) {
460 460
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
461
+				if (is_dir($source.'/'.$file)) {
462 462
 					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
463
+					self::copyr($source.'/'.$file, $child);
464 464
 				} else {
465 465
 					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
466
+					$sourceStream = fopen($source.'/'.$file, 'r');
467 467
 					if ($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
468
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
469 469
 						closedir($dir);
470 470
 						return;
471 471
 					}
@@ -542,8 +542,8 @@  discard block
 block discarded – undo
542 542
 			return;
543 543
 		}
544 544
 
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
545
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
546
+		require OC::$SERVERROOT.'/version.php';
547 547
 		/** @var int $timestamp */
548 548
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549 549
 		/** @var string $OC_Version */
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
 	public static function checkServer(\OC\SystemConfig $config) {
718 718
 		$l = \OC::$server->getL10N('lib');
719 719
 		$errors = [];
720
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
720
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
721 721
 
722 722
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
723 723
 			// this check needs to be done every time
@@ -757,9 +757,9 @@  discard block
 block discarded – undo
757 757
 				$errors[] = [
758 758
 					'error' => $l->t('Cannot write into "config" directory.'),
759 759
 					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
760
+						[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
761 761
 						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
762
-						[ $urlGenerator->linkToDocs('admin-config') ])
762
+						[$urlGenerator->linkToDocs('admin-config')])
763 763
 				];
764 764
 			}
765 765
 		}
@@ -933,7 +933,7 @@  discard block
 block discarded – undo
933 933
 			$version -= ($minor * 100);
934 934
 			$patch = $version;
935 935
 			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
936
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
937 937
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938 938
 			];
939 939
 		}
@@ -1036,10 +1036,10 @@  discard block
 block discarded – undo
1036 1036
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
1037 1037
 			];
1038 1038
 		}
1039
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1039
+		if (!file_exists($dataDirectory.'/.ocdata')) {
1040 1040
 			$errors[] = [
1041 1041
 				'error' => $l->t('Your data directory is invalid.'),
1042
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1042
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
1043 1043
 					' in the root of the data directory.')
1044 1044
 			];
1045 1045
 		}
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
 	public static function checkLoggedIn() {
1056 1056
 		// Check if we are a user
1057 1057
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1058
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1058
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
1059 1059
 						'core.login.showLoginForm',
1060 1060
 						[
1061 1061
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
 		}
1067 1067
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1068 1068
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1069
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1069
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1070 1070
 			exit();
1071 1071
 		}
1072 1072
 	}
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 	public static function checkAdminUser() {
1080 1080
 		OC_Util::checkLoggedIn();
1081 1081
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
1082
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1082
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1083 1083
 			exit();
1084 1084
 		}
1085 1085
 	}
@@ -1105,7 +1105,7 @@  discard block
 block discarded – undo
1105 1105
 	 */
1106 1106
 	public static function redirectToDefaultPage() {
1107 1107
 		$location = self::getDefaultPageUrl();
1108
-		header('Location: ' . $location);
1108
+		header('Location: '.$location);
1109 1109
 		exit();
1110 1110
 	}
1111 1111
 
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1119 1119
 		if (is_null($id)) {
1120 1120
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1121
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1121
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1122 1122
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1123 1123
 		}
1124 1124
 		return $id;
@@ -1136,12 +1136,12 @@  discard block
 block discarded – undo
1136 1136
 	public static function sanitizeHTML($value) {
1137 1137
 		if (is_array($value)) {
1138 1138
 			/** @var string[] $value */
1139
-			$value = array_map(function ($value) {
1139
+			$value = array_map(function($value) {
1140 1140
 				return self::sanitizeHTML($value);
1141 1141
 			}, $value);
1142 1142
 		} else {
1143 1143
 			// Specify encoding for PHP<5.4
1144
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1144
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
1145 1145
 		}
1146 1146
 		return $value;
1147 1147
 	}
@@ -1174,7 +1174,7 @@  discard block
 block discarded – undo
1174 1174
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1175 1175
 
1176 1176
 		// creating a test file
1177
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1177
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1178 1178
 
1179 1179
 		if (file_exists($testFile)) {// already running this test, possible recursive call
1180 1180
 			return false;
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
 		$fp = @fopen($testFile, 'w');
1184 1184
 		if (!$fp) {
1185 1185
 			throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
1186
-				'Make sure it is possible for the web server to write to ' . $testFile);
1186
+				'Make sure it is possible for the web server to write to '.$testFile);
1187 1187
 		}
1188 1188
 		fwrite($fp, $testContent);
1189 1189
 		fclose($fp);
@@ -1210,10 +1210,10 @@  discard block
 block discarded – undo
1210 1210
 		}
1211 1211
 
1212 1212
 		$fileName = '/htaccesstest.txt';
1213
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1213
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1214 1214
 
1215 1215
 		// accessing the file via http
1216
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1216
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1217 1217
 		try {
1218 1218
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1219 1219
 		} catch (\Exception $e) {
@@ -1221,9 +1221,9 @@  discard block
 block discarded – undo
1221 1221
 		}
1222 1222
 
1223 1223
 		if (strpos($url, 'https:') === 0) {
1224
-			$url = 'http:' . substr($url, 6);
1224
+			$url = 'http:'.substr($url, 6);
1225 1225
 		} else {
1226
-			$url = 'https:' . substr($url, 5);
1226
+			$url = 'https:'.substr($url, 5);
1227 1227
 		}
1228 1228
 
1229 1229
 		try {
@@ -1329,7 +1329,7 @@  discard block
 block discarded – undo
1329 1329
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1330 1330
 
1331 1331
 		if ($theme === '') {
1332
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1332
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1333 1333
 				$theme = 'default';
1334 1334
 			}
1335 1335
 		}
@@ -1350,7 +1350,7 @@  discard block
 block discarded – undo
1350 1350
 
1351 1351
 		$normalizedValue = Normalizer::normalize($value);
1352 1352
 		if ($normalizedValue === null || $normalizedValue === false) {
1353
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1353
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1354 1354
 			return $value;
1355 1355
 		}
1356 1356
 
@@ -1366,7 +1366,7 @@  discard block
 block discarded – undo
1366 1366
 		$version = OC_Util::getVersionString();
1367 1367
 		$build = OC_Util::getBuild();
1368 1368
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1369
-			$version .= ' Build:' . $build;
1369
+			$version .= ' Build:'.$build;
1370 1370
 		}
1371 1371
 		return $version;
1372 1372
 	}
@@ -1388,7 +1388,7 @@  discard block
 block discarded – undo
1388 1388
 		}
1389 1389
 
1390 1390
 		// detect part files
1391
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1391
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1392 1392
 			return false;
1393 1393
 		}
1394 1394
 
@@ -1419,19 +1419,19 @@  discard block
 block discarded – undo
1419 1419
 			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1420 1420
 				// downgrade with debug
1421 1421
 				$installedMajor = explode('.', $installedVersion);
1422
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1422
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1423 1423
 				$currentMajor = explode('.', $currentVersion);
1424
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1424
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1425 1425
 				if ($installedMajor === $currentMajor) {
1426 1426
 					// Same major, allow downgrade for developers
1427 1427
 					return true;
1428 1428
 				} else {
1429 1429
 					// downgrade attempt, throw exception
1430
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1430
+					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1431 1431
 				}
1432 1432
 			} elseif ($versionDiff < 0) {
1433 1433
 				// downgrade attempt, throw exception
1434
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1434
+				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1435 1435
 			}
1436 1436
 
1437 1437
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/private/Memcache/Memcached.php 1 patch
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -35,180 +35,180 @@
 block discarded – undo
35 35
 use OCP\IMemcache;
36 36
 
37 37
 class Memcached extends Cache implements IMemcache {
38
-	use CASTrait;
39
-
40
-	/**
41
-	 * @var \Memcached $cache
42
-	 */
43
-	private static $cache = null;
44
-
45
-	use CADTrait;
46
-
47
-	public function __construct($prefix = '') {
48
-		parent::__construct($prefix);
49
-		if (is_null(self::$cache)) {
50
-			self::$cache = new \Memcached();
51
-
52
-			$defaultOptions = [
53
-				\Memcached::OPT_CONNECT_TIMEOUT => 50,
54
-				\Memcached::OPT_RETRY_TIMEOUT => 50,
55
-				\Memcached::OPT_SEND_TIMEOUT => 50,
56
-				\Memcached::OPT_RECV_TIMEOUT => 50,
57
-				\Memcached::OPT_POLL_TIMEOUT => 50,
58
-
59
-				// Enable compression
60
-				\Memcached::OPT_COMPRESSION => true,
61
-
62
-				// Turn on consistent hashing
63
-				\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
64
-
65
-				// Enable Binary Protocol
66
-				//\Memcached::OPT_BINARY_PROTOCOL =>      true,
67
-			];
68
-			/**
69
-			 * By default enable igbinary serializer if available
70
-			 *
71
-			 * Psalm checks depend on if igbinary is installed or not with memcached
72
-			 * @psalm-suppress RedundantCondition
73
-			 * @psalm-suppress TypeDoesNotContainType
74
-			 */
75
-			if (\Memcached::HAVE_IGBINARY) {
76
-				$defaultOptions[\Memcached::OPT_SERIALIZER] =
77
-					\Memcached::SERIALIZER_IGBINARY;
78
-			}
79
-			$options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
80
-			if (is_array($options)) {
81
-				$options = $options + $defaultOptions;
82
-				self::$cache->setOptions($options);
83
-			} else {
84
-				throw new HintException("Expected 'memcached_options' config to be an array, got $options");
85
-			}
86
-
87
-			$servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
88
-			if (!$servers) {
89
-				$server = \OC::$server->getSystemConfig()->getValue('memcached_server');
90
-				if ($server) {
91
-					$servers = [$server];
92
-				} else {
93
-					$servers = [['localhost', 11211]];
94
-				}
95
-			}
96
-			self::$cache->addServers($servers);
97
-		}
98
-	}
99
-
100
-	/**
101
-	 * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
102
-	 */
103
-	protected function getNameSpace() {
104
-		return $this->prefix;
105
-	}
106
-
107
-	public function get($key) {
108
-		$result = self::$cache->get($this->getNameSpace() . $key);
109
-		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
110
-			return null;
111
-		} else {
112
-			return $result;
113
-		}
114
-	}
115
-
116
-	public function set($key, $value, $ttl = 0) {
117
-		if ($ttl > 0) {
118
-			$result = self::$cache->set($this->getNameSpace() . $key, $value, $ttl);
119
-		} else {
120
-			$result = self::$cache->set($this->getNameSpace() . $key, $value);
121
-		}
122
-		if ($result !== true) {
123
-			$this->verifyReturnCode();
124
-		}
125
-		return $result;
126
-	}
127
-
128
-	public function hasKey($key) {
129
-		self::$cache->get($this->getNameSpace() . $key);
130
-		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
131
-	}
132
-
133
-	public function remove($key) {
134
-		$result = self::$cache->delete($this->getNameSpace() . $key);
135
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
136
-			$this->verifyReturnCode();
137
-		}
138
-		return $result;
139
-	}
140
-
141
-	public function clear($prefix = '') {
142
-		// Newer Memcached doesn't like getAllKeys(), flush everything
143
-		self::$cache->flush();
144
-		return true;
145
-	}
146
-
147
-	/**
148
-	 * Set a value in the cache if it's not already stored
149
-	 *
150
-	 * @param string $key
151
-	 * @param mixed $value
152
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
153
-	 * @return bool
154
-	 * @throws \Exception
155
-	 */
156
-	public function add($key, $value, $ttl = 0) {
157
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
158
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
159
-			$this->verifyReturnCode();
160
-		}
161
-		return $result;
162
-	}
163
-
164
-	/**
165
-	 * Increase a stored number
166
-	 *
167
-	 * @param string $key
168
-	 * @param int $step
169
-	 * @return int | bool
170
-	 */
171
-	public function inc($key, $step = 1) {
172
-		$this->add($key, 0);
173
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
174
-
175
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
176
-			return false;
177
-		}
178
-
179
-		return $result;
180
-	}
181
-
182
-	/**
183
-	 * Decrease a stored number
184
-	 *
185
-	 * @param string $key
186
-	 * @param int $step
187
-	 * @return int | bool
188
-	 */
189
-	public function dec($key, $step = 1) {
190
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
191
-
192
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
193
-			return false;
194
-		}
195
-
196
-		return $result;
197
-	}
198
-
199
-	public static function isAvailable() {
200
-		return extension_loaded('memcached');
201
-	}
202
-
203
-	/**
204
-	 * @throws \Exception
205
-	 */
206
-	private function verifyReturnCode() {
207
-		$code = self::$cache->getResultCode();
208
-		if ($code === \Memcached::RES_SUCCESS) {
209
-			return;
210
-		}
211
-		$message = self::$cache->getResultMessage();
212
-		throw new \Exception("Error $code interacting with memcached : $message");
213
-	}
38
+    use CASTrait;
39
+
40
+    /**
41
+     * @var \Memcached $cache
42
+     */
43
+    private static $cache = null;
44
+
45
+    use CADTrait;
46
+
47
+    public function __construct($prefix = '') {
48
+        parent::__construct($prefix);
49
+        if (is_null(self::$cache)) {
50
+            self::$cache = new \Memcached();
51
+
52
+            $defaultOptions = [
53
+                \Memcached::OPT_CONNECT_TIMEOUT => 50,
54
+                \Memcached::OPT_RETRY_TIMEOUT => 50,
55
+                \Memcached::OPT_SEND_TIMEOUT => 50,
56
+                \Memcached::OPT_RECV_TIMEOUT => 50,
57
+                \Memcached::OPT_POLL_TIMEOUT => 50,
58
+
59
+                // Enable compression
60
+                \Memcached::OPT_COMPRESSION => true,
61
+
62
+                // Turn on consistent hashing
63
+                \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
64
+
65
+                // Enable Binary Protocol
66
+                //\Memcached::OPT_BINARY_PROTOCOL =>      true,
67
+            ];
68
+            /**
69
+             * By default enable igbinary serializer if available
70
+             *
71
+             * Psalm checks depend on if igbinary is installed or not with memcached
72
+             * @psalm-suppress RedundantCondition
73
+             * @psalm-suppress TypeDoesNotContainType
74
+             */
75
+            if (\Memcached::HAVE_IGBINARY) {
76
+                $defaultOptions[\Memcached::OPT_SERIALIZER] =
77
+                    \Memcached::SERIALIZER_IGBINARY;
78
+            }
79
+            $options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
80
+            if (is_array($options)) {
81
+                $options = $options + $defaultOptions;
82
+                self::$cache->setOptions($options);
83
+            } else {
84
+                throw new HintException("Expected 'memcached_options' config to be an array, got $options");
85
+            }
86
+
87
+            $servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
88
+            if (!$servers) {
89
+                $server = \OC::$server->getSystemConfig()->getValue('memcached_server');
90
+                if ($server) {
91
+                    $servers = [$server];
92
+                } else {
93
+                    $servers = [['localhost', 11211]];
94
+                }
95
+            }
96
+            self::$cache->addServers($servers);
97
+        }
98
+    }
99
+
100
+    /**
101
+     * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
102
+     */
103
+    protected function getNameSpace() {
104
+        return $this->prefix;
105
+    }
106
+
107
+    public function get($key) {
108
+        $result = self::$cache->get($this->getNameSpace() . $key);
109
+        if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
110
+            return null;
111
+        } else {
112
+            return $result;
113
+        }
114
+    }
115
+
116
+    public function set($key, $value, $ttl = 0) {
117
+        if ($ttl > 0) {
118
+            $result = self::$cache->set($this->getNameSpace() . $key, $value, $ttl);
119
+        } else {
120
+            $result = self::$cache->set($this->getNameSpace() . $key, $value);
121
+        }
122
+        if ($result !== true) {
123
+            $this->verifyReturnCode();
124
+        }
125
+        return $result;
126
+    }
127
+
128
+    public function hasKey($key) {
129
+        self::$cache->get($this->getNameSpace() . $key);
130
+        return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
131
+    }
132
+
133
+    public function remove($key) {
134
+        $result = self::$cache->delete($this->getNameSpace() . $key);
135
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
136
+            $this->verifyReturnCode();
137
+        }
138
+        return $result;
139
+    }
140
+
141
+    public function clear($prefix = '') {
142
+        // Newer Memcached doesn't like getAllKeys(), flush everything
143
+        self::$cache->flush();
144
+        return true;
145
+    }
146
+
147
+    /**
148
+     * Set a value in the cache if it's not already stored
149
+     *
150
+     * @param string $key
151
+     * @param mixed $value
152
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
153
+     * @return bool
154
+     * @throws \Exception
155
+     */
156
+    public function add($key, $value, $ttl = 0) {
157
+        $result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
158
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
159
+            $this->verifyReturnCode();
160
+        }
161
+        return $result;
162
+    }
163
+
164
+    /**
165
+     * Increase a stored number
166
+     *
167
+     * @param string $key
168
+     * @param int $step
169
+     * @return int | bool
170
+     */
171
+    public function inc($key, $step = 1) {
172
+        $this->add($key, 0);
173
+        $result = self::$cache->increment($this->getPrefix() . $key, $step);
174
+
175
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
176
+            return false;
177
+        }
178
+
179
+        return $result;
180
+    }
181
+
182
+    /**
183
+     * Decrease a stored number
184
+     *
185
+     * @param string $key
186
+     * @param int $step
187
+     * @return int | bool
188
+     */
189
+    public function dec($key, $step = 1) {
190
+        $result = self::$cache->decrement($this->getPrefix() . $key, $step);
191
+
192
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
193
+            return false;
194
+        }
195
+
196
+        return $result;
197
+    }
198
+
199
+    public static function isAvailable() {
200
+        return extension_loaded('memcached');
201
+    }
202
+
203
+    /**
204
+     * @throws \Exception
205
+     */
206
+    private function verifyReturnCode() {
207
+        $code = self::$cache->getResultCode();
208
+        if ($code === \Memcached::RES_SUCCESS) {
209
+            return;
210
+        }
211
+        $message = self::$cache->getResultMessage();
212
+        throw new \Exception("Error $code interacting with memcached : $message");
213
+    }
214 214
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Bootstrap/IRegistrationContext.php 1 patch
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -47,221 +47,221 @@
 block discarded – undo
47 47
  */
48 48
 interface IRegistrationContext {
49 49
 
50
-	/**
51
-	 * @param string $capability
52
-	 * @psalm-param class-string<ICapability> $capability
53
-	 * @see IAppContainer::registerCapability
54
-	 *
55
-	 * @since 20.0.0
56
-	 */
57
-	public function registerCapability(string $capability): void;
50
+    /**
51
+     * @param string $capability
52
+     * @psalm-param class-string<ICapability> $capability
53
+     * @see IAppContainer::registerCapability
54
+     *
55
+     * @since 20.0.0
56
+     */
57
+    public function registerCapability(string $capability): void;
58 58
 
59
-	/**
60
-	 * Register an implementation of \OCP\Support\CrashReport\IReporter that
61
-	 * will receive unhandled exceptions and throwables
62
-	 *
63
-	 * @param string $reporterClass
64
-	 * @psalm-param class-string<\OCP\Support\CrashReport\IReporter> $reporterClass
65
-	 * @return void
66
-	 * @since 20.0.0
67
-	 */
68
-	public function registerCrashReporter(string $reporterClass): void;
59
+    /**
60
+     * Register an implementation of \OCP\Support\CrashReport\IReporter that
61
+     * will receive unhandled exceptions and throwables
62
+     *
63
+     * @param string $reporterClass
64
+     * @psalm-param class-string<\OCP\Support\CrashReport\IReporter> $reporterClass
65
+     * @return void
66
+     * @since 20.0.0
67
+     */
68
+    public function registerCrashReporter(string $reporterClass): void;
69 69
 
70
-	/**
71
-	 * Register an implementation of \OCP\Dashboard\IWidget that
72
-	 * will handle the implementation of a dashboard widget
73
-	 *
74
-	 * @param string $widgetClass
75
-	 * @psalm-param class-string<\OCP\Dashboard\IWidget> $widgetClass
76
-	 * @return void
77
-	 * @since 20.0.0
78
-	 */
79
-	public function registerDashboardWidget(string $widgetClass): void;
70
+    /**
71
+     * Register an implementation of \OCP\Dashboard\IWidget that
72
+     * will handle the implementation of a dashboard widget
73
+     *
74
+     * @param string $widgetClass
75
+     * @psalm-param class-string<\OCP\Dashboard\IWidget> $widgetClass
76
+     * @return void
77
+     * @since 20.0.0
78
+     */
79
+    public function registerDashboardWidget(string $widgetClass): void;
80 80
 
81
-	/**
82
-	 * Register a service
83
-	 *
84
-	 * @param string $name
85
-	 * @param callable $factory
86
-	 * @psalm-param callable(\Psr\Container\ContainerInterface): mixed $factory
87
-	 * @param bool $shared
88
-	 *
89
-	 * @return void
90
-	 * @see IContainer::registerService()
91
-	 *
92
-	 * @since 20.0.0
93
-	 */
94
-	public function registerService(string $name, callable $factory, bool $shared = true): void;
81
+    /**
82
+     * Register a service
83
+     *
84
+     * @param string $name
85
+     * @param callable $factory
86
+     * @psalm-param callable(\Psr\Container\ContainerInterface): mixed $factory
87
+     * @param bool $shared
88
+     *
89
+     * @return void
90
+     * @see IContainer::registerService()
91
+     *
92
+     * @since 20.0.0
93
+     */
94
+    public function registerService(string $name, callable $factory, bool $shared = true): void;
95 95
 
96
-	/**
97
-	 * @param string $alias
98
-	 * @psalm-param string|class-string $alias
99
-	 * @param string $target
100
-	 * @psalm-param string|class-string $target
101
-	 *
102
-	 * @return void
103
-	 * @see IContainer::registerAlias()
104
-	 *
105
-	 * @since 20.0.0
106
-	 */
107
-	public function registerServiceAlias(string $alias, string $target): void;
96
+    /**
97
+     * @param string $alias
98
+     * @psalm-param string|class-string $alias
99
+     * @param string $target
100
+     * @psalm-param string|class-string $target
101
+     *
102
+     * @return void
103
+     * @see IContainer::registerAlias()
104
+     *
105
+     * @since 20.0.0
106
+     */
107
+    public function registerServiceAlias(string $alias, string $target): void;
108 108
 
109
-	/**
110
-	 * @param string $name
111
-	 * @param mixed $value
112
-	 *
113
-	 * @return void
114
-	 * @see IContainer::registerParameter()
115
-	 *
116
-	 * @since 20.0.0
117
-	 */
118
-	public function registerParameter(string $name, $value): void;
109
+    /**
110
+     * @param string $name
111
+     * @param mixed $value
112
+     *
113
+     * @return void
114
+     * @see IContainer::registerParameter()
115
+     *
116
+     * @since 20.0.0
117
+     */
118
+    public function registerParameter(string $name, $value): void;
119 119
 
120
-	/**
121
-	 * Register a service listener
122
-	 *
123
-	 * This is equivalent to calling IEventDispatcher::addServiceListener
124
-	 *
125
-	 * @psalm-template T of \OCP\EventDispatcher\Event
126
-	 * @param string $event preferably the fully-qualified class name of the Event sub class to listen for
127
-	 * @psalm-param string|class-string<T> $event preferably the fully-qualified class name of the Event sub class to listen for
128
-	 * @param string $listener fully qualified class name (or ::class notation) of a \OCP\EventDispatcher\IEventListener that can be built by the DI container
129
-	 * @psalm-param class-string<\OCP\EventDispatcher\IEventListener> $listener fully qualified class name that can be built by the DI container
130
-	 * @param int $priority The higher this value, the earlier an event
131
-	 *                      listener will be triggered in the chain (defaults to 0)
132
-	 *
133
-	 * @see IEventDispatcher::addServiceListener()
134
-	 *
135
-	 * @since 20.0.0
136
-	 */
137
-	public function registerEventListener(string $event, string $listener, int $priority = 0): void;
120
+    /**
121
+     * Register a service listener
122
+     *
123
+     * This is equivalent to calling IEventDispatcher::addServiceListener
124
+     *
125
+     * @psalm-template T of \OCP\EventDispatcher\Event
126
+     * @param string $event preferably the fully-qualified class name of the Event sub class to listen for
127
+     * @psalm-param string|class-string<T> $event preferably the fully-qualified class name of the Event sub class to listen for
128
+     * @param string $listener fully qualified class name (or ::class notation) of a \OCP\EventDispatcher\IEventListener that can be built by the DI container
129
+     * @psalm-param class-string<\OCP\EventDispatcher\IEventListener> $listener fully qualified class name that can be built by the DI container
130
+     * @param int $priority The higher this value, the earlier an event
131
+     *                      listener will be triggered in the chain (defaults to 0)
132
+     *
133
+     * @see IEventDispatcher::addServiceListener()
134
+     *
135
+     * @since 20.0.0
136
+     */
137
+    public function registerEventListener(string $event, string $listener, int $priority = 0): void;
138 138
 
139
-	/**
140
-	 * @param string $class
141
-	 * @psalm-param class-string<\OCP\AppFramework\Middleware> $class
142
-	 *
143
-	 * @return void
144
-	 * @see IAppContainer::registerMiddleWare()
145
-	 *
146
-	 * @since 20.0.0
147
-	 */
148
-	public function registerMiddleware(string $class): void;
139
+    /**
140
+     * @param string $class
141
+     * @psalm-param class-string<\OCP\AppFramework\Middleware> $class
142
+     *
143
+     * @return void
144
+     * @see IAppContainer::registerMiddleWare()
145
+     *
146
+     * @since 20.0.0
147
+     */
148
+    public function registerMiddleware(string $class): void;
149 149
 
150
-	/**
151
-	 * Register a search provider for the unified search
152
-	 *
153
-	 * It is allowed to register more than one provider per app as the search
154
-	 * results can go into distinct sections, e.g. "Files" and "Files shared
155
-	 * with you" in the Files app.
156
-	 *
157
-	 * @param string $class
158
-	 * @psalm-param class-string<\OCP\Search\IProvider> $class
159
-	 *
160
-	 * @return void
161
-	 *
162
-	 * @since 20.0.0
163
-	 */
164
-	public function registerSearchProvider(string $class): void;
150
+    /**
151
+     * Register a search provider for the unified search
152
+     *
153
+     * It is allowed to register more than one provider per app as the search
154
+     * results can go into distinct sections, e.g. "Files" and "Files shared
155
+     * with you" in the Files app.
156
+     *
157
+     * @param string $class
158
+     * @psalm-param class-string<\OCP\Search\IProvider> $class
159
+     *
160
+     * @return void
161
+     *
162
+     * @since 20.0.0
163
+     */
164
+    public function registerSearchProvider(string $class): void;
165 165
 
166
-	/**
167
-	 * Register an alternative login option
168
-	 *
169
-	 * It is allowed to register more than one option per app.
170
-	 *
171
-	 * @param string $class
172
-	 * @psalm-param class-string<\OCP\Authentication\IAlternativeLogin> $class
173
-	 *
174
-	 * @return void
175
-	 *
176
-	 * @since 20.0.0
177
-	 */
178
-	public function registerAlternativeLogin(string $class): void;
166
+    /**
167
+     * Register an alternative login option
168
+     *
169
+     * It is allowed to register more than one option per app.
170
+     *
171
+     * @param string $class
172
+     * @psalm-param class-string<\OCP\Authentication\IAlternativeLogin> $class
173
+     *
174
+     * @return void
175
+     *
176
+     * @since 20.0.0
177
+     */
178
+    public function registerAlternativeLogin(string $class): void;
179 179
 
180
-	/**
181
-	 * Register an initialstate provider
182
-	 *
183
-	 * It is allowed to register more than one provider per app.
184
-	 *
185
-	 * @param string $class
186
-	 * @psalm-param class-string<\OCP\AppFramework\Services\InitialStateProvider> $class
187
-	 *
188
-	 * @return void
189
-	 *
190
-	 * @since 21.0.0
191
-	 */
192
-	public function registerInitialStateProvider(string $class): void;
180
+    /**
181
+     * Register an initialstate provider
182
+     *
183
+     * It is allowed to register more than one provider per app.
184
+     *
185
+     * @param string $class
186
+     * @psalm-param class-string<\OCP\AppFramework\Services\InitialStateProvider> $class
187
+     *
188
+     * @return void
189
+     *
190
+     * @since 21.0.0
191
+     */
192
+    public function registerInitialStateProvider(string $class): void;
193 193
 
194
-	/**
195
-	 * Register a well known protocol handler
196
-	 *
197
-	 * It is allowed to register more than one handler per app.
198
-	 *
199
-	 * @param string $class
200
-	 * @psalm-param class-string<\OCP\Http\WellKnown\IHandler> $class
201
-	 *
202
-	 * @return void
203
-	 *
204
-	 * @since 21.0.0
205
-	 */
206
-	public function registerWellKnownHandler(string $class): void;
194
+    /**
195
+     * Register a well known protocol handler
196
+     *
197
+     * It is allowed to register more than one handler per app.
198
+     *
199
+     * @param string $class
200
+     * @psalm-param class-string<\OCP\Http\WellKnown\IHandler> $class
201
+     *
202
+     * @return void
203
+     *
204
+     * @since 21.0.0
205
+     */
206
+    public function registerWellKnownHandler(string $class): void;
207 207
 
208
-	/**
209
-	 * Register a custom template provider class that is able to inject custom templates
210
-	 * in addition to the user defined ones
211
-	 *
212
-	 * @param string $providerClass
213
-	 * @psalm-param class-string<ICustomTemplateProvider> $providerClass
214
-	 * @since 21.0.0
215
-	 */
216
-	public function registerTemplateProvider(string $providerClass): void;
208
+    /**
209
+     * Register a custom template provider class that is able to inject custom templates
210
+     * in addition to the user defined ones
211
+     *
212
+     * @param string $providerClass
213
+     * @psalm-param class-string<ICustomTemplateProvider> $providerClass
214
+     * @since 21.0.0
215
+     */
216
+    public function registerTemplateProvider(string $providerClass): void;
217 217
 
218
-	/**
219
-	 * Register an INotifier class
220
-	 *
221
-	 * @param string $notifierClass
222
-	 * @psalm-param class-string<INotifier> $notifierClass
223
-	 * @since 22.0.0
224
-	 */
225
-	public function registerNotifierService(string $notifierClass): void;
218
+    /**
219
+     * Register an INotifier class
220
+     *
221
+     * @param string $notifierClass
222
+     * @psalm-param class-string<INotifier> $notifierClass
223
+     * @since 22.0.0
224
+     */
225
+    public function registerNotifierService(string $notifierClass): void;
226 226
 
227
-	/**
228
-	 * Register a two-factor provider
229
-	 *
230
-	 * @param string $twoFactorProviderClass
231
-	 * @psalm-param class-string<IProvider> $twoFactorProviderClass
232
-	 * @since 22.0.0
233
-	 */
234
-	public function registerTwoFactorProvider(string $twoFactorProviderClass): void;
227
+    /**
228
+     * Register a two-factor provider
229
+     *
230
+     * @param string $twoFactorProviderClass
231
+     * @psalm-param class-string<IProvider> $twoFactorProviderClass
232
+     * @since 22.0.0
233
+     */
234
+    public function registerTwoFactorProvider(string $twoFactorProviderClass): void;
235 235
 
236
-	/**
237
-	 * Register a preview provider
238
-	 *
239
-	 * It is allowed to register more than one provider per app.
240
-	 *
241
-	 * @param string $previewProviderClass
242
-	 * @param string $mimeTypeRegex
243
-	 * @psalm-param class-string<IProviderV2> $previewProviderClass
244
-	 * @since 23.0.0
245
-	 */
246
-	public function registerPreviewProvider(string $previewProviderClass, string $mimeTypeRegex): void;
236
+    /**
237
+     * Register a preview provider
238
+     *
239
+     * It is allowed to register more than one provider per app.
240
+     *
241
+     * @param string $previewProviderClass
242
+     * @param string $mimeTypeRegex
243
+     * @psalm-param class-string<IProviderV2> $previewProviderClass
244
+     * @since 23.0.0
245
+     */
246
+    public function registerPreviewProvider(string $previewProviderClass, string $mimeTypeRegex): void;
247 247
 
248
-	/**
249
-	 * Register a calendar provider
250
-	 *
251
-	 * @param string $class
252
-	 * @psalm-param class-string<ICalendarProvider> $class
253
-	 * @since 23.0.0
254
-	 */
255
-	public function registerCalendarProvider(string $class): void;
248
+    /**
249
+     * Register a calendar provider
250
+     *
251
+     * @param string $class
252
+     * @psalm-param class-string<ICalendarProvider> $class
253
+     * @since 23.0.0
254
+     */
255
+    public function registerCalendarProvider(string $class): void;
256 256
 
257
-	/**
258
-	 * Register an implementation of \OCP\Profile\ILinkAction that
259
-	 * will handle the implementation of a profile link action
260
-	 *
261
-	 * @param string $actionClass
262
-	 * @psalm-param class-string<\OCP\Profile\ILinkAction> $actionClass
263
-	 * @return void
264
-	 * @since 23.0.0
265
-	 */
266
-	public function registerProfileLinkAction(string $actionClass): void;
257
+    /**
258
+     * Register an implementation of \OCP\Profile\ILinkAction that
259
+     * will handle the implementation of a profile link action
260
+     *
261
+     * @param string $actionClass
262
+     * @psalm-param class-string<\OCP\Profile\ILinkAction> $actionClass
263
+     * @return void
264
+     * @since 23.0.0
265
+     */
266
+    public function registerProfileLinkAction(string $actionClass): void;
267 267
 }
Please login to merge, or discard this patch.