Passed
Push — master ( a884f3...785682 )
by
unknown
14:57 queued 14s
created

ImageManager::getCustomImages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Julius Härtl <[email protected]>
4
 *
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Daniel Kesselberg <[email protected]>
7
 * @author Gary Kim <[email protected]>
8
 * @author Jacob Neplokh <[email protected]>
9
 * @author John Molakvoæ <[email protected]>
10
 * @author Julien Veyssier <[email protected]>
11
 * @author Julius Haertl <[email protected]>
12
 * @author Julius Härtl <[email protected]>
13
 * @author Michael Weimann <[email protected]>
14
 * @author Morris Jobke <[email protected]>
15
 * @author Roeland Jago Douma <[email protected]>
16
 * @author ste101 <[email protected]>
17
 *
18
 * @license GNU AGPL version 3 or any later version
19
 *
20
 * This program is free software: you can redistribute it and/or modify
21
 * it under the terms of the GNU Affero General Public License as
22
 * published by the Free Software Foundation, either version 3 of the
23
 * License, or (at your option) any later version.
24
 *
25
 * This program is distributed in the hope that it will be useful,
26
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28
 * GNU Affero General Public License for more details.
29
 *
30
 * You should have received a copy of the GNU Affero General Public License
31
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32
 *
33
 */
34
namespace OCA\Theming;
35
36
use OCA\Theming\AppInfo\Application;
37
use OCA\Theming\Service\BackgroundService;
38
use OCP\Files\IAppData;
39
use OCP\Files\NotFoundException;
40
use OCP\Files\NotPermittedException;
41
use OCP\Files\SimpleFS\ISimpleFile;
42
use OCP\Files\SimpleFS\ISimpleFolder;
43
use OCP\ICacheFactory;
44
use OCP\IConfig;
45
use OCP\ILogger;
46
use OCP\ITempManager;
47
use OCP\IURLGenerator;
48
49
class ImageManager {
50
	public const SUPPORTED_IMAGE_KEYS = ['background', 'logo', 'logoheader', 'favicon'];
51
52
	/** @var IConfig */
53
	private $config;
54
	/** @var IAppData */
55
	private $appData;
56
	/** @var IURLGenerator */
57
	private $urlGenerator;
58
	/** @var ICacheFactory */
59
	private $cacheFactory;
60
	/** @var ILogger */
61
	private $logger;
62
	/** @var ITempManager */
63
	private $tempManager;
64
65
	public function __construct(IConfig $config,
66
								IAppData $appData,
67
								IURLGenerator $urlGenerator,
68
								ICacheFactory $cacheFactory,
69
								ILogger $logger,
70
								ITempManager $tempManager) {
71
		$this->config = $config;
72
		$this->urlGenerator = $urlGenerator;
73
		$this->cacheFactory = $cacheFactory;
74
		$this->logger = $logger;
75
		$this->tempManager = $tempManager;
76
		$this->appData = $appData;
77
	}
78
79
	/**
80
	 * Get a globally defined image (admin theming settings)
81
	 *
82
	 * @param string $key the image key
83
	 * @return string the image url
84
	 */
85
	public function getImageUrl(string $key): string {
86
		$cacheBusterCounter = $this->config->getAppValue(Application::APP_ID, 'cachebuster', '0');
87
		if ($this->hasImage($key)) {
88
			return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
89
		}
90
91
		switch ($key) {
92
			case 'logo':
93
			case 'logoheader':
94
			case 'favicon':
95
				return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
96
			case 'background':
97
				return $this->urlGenerator->linkTo(Application::APP_ID, 'img/background/' . BackgroundService::DEFAULT_BACKGROUND_IMAGE);
98
		}
99
		return '';
100
	}
101
102
	/**
103
	 * Get the absolute url. See getImageUrl
104
	 */
105
	public function getImageUrlAbsolute(string $key): string {
106
		return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key));
107
	}
108
109
	/**
110
	 * @param string $key
111
	 * @param bool $useSvg
112
	 * @return ISimpleFile
113
	 * @throws NotFoundException
114
	 * @throws NotPermittedException
115
	 */
116
	public function getImage(string $key, bool $useSvg = true): ISimpleFile {
117
		$logo = $this->config->getAppValue('theming', $key . 'Mime', '');
118
		$folder = $this->getRootFolder()->getFolder('images');
119
120
		if ($logo === '' || !$folder->fileExists($key)) {
121
			throw new NotFoundException();
122
		}
123
124
		if (!$useSvg && $this->shouldReplaceIcons()) {
125
			if (!$folder->fileExists($key . '.png')) {
126
				try {
127
					$finalIconFile = new \Imagick();
128
					$finalIconFile->setBackgroundColor('none');
129
					$finalIconFile->readImageBlob($folder->getFile($key)->getContent());
130
					$finalIconFile->setImageFormat('png32');
131
					$pngFile = $folder->newFile($key . '.png');
132
					$pngFile->putContent($finalIconFile->getImageBlob());
133
					return $pngFile;
134
				} catch (\ImagickException $e) {
135
					$this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
136
				}
137
			} else {
138
				return $folder->getFile($key . '.png');
139
			}
140
		}
141
142
		return $folder->getFile($key);
143
	}
144
145
	public function hasImage(string $key): bool {
146
		$mimeSetting = $this->config->getAppValue('theming', $key . 'Mime', '');
147
		return $mimeSetting !== '';
148
	}
149
150
	/**
151
	 * @return array<string, array{mime: string, url: string}>
152
	 */
153
	public function getCustomImages(): array {
154
		$images = [];
155
		foreach (self::SUPPORTED_IMAGE_KEYS as $key) {
156
			$images[$key] = [
157
				'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
158
				'url' => $this->getImageUrl($key),
159
			];
160
		}
161
		return $images;
162
	}
163
164
	/**
165
	 * Get folder for current theming files
166
	 *
167
	 * @return ISimpleFolder
168
	 * @throws NotPermittedException
169
	 */
170
	public function getCacheFolder(): ISimpleFolder {
171
		$cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
172
		try {
173
			$folder = $this->getRootFolder()->getFolder($cacheBusterValue);
174
		} catch (NotFoundException $e) {
175
			$folder = $this->getRootFolder()->newFolder($cacheBusterValue);
176
			$this->cleanup();
177
		}
178
		return $folder;
179
	}
180
181
	/**
182
	 * Get a file from AppData
183
	 *
184
	 * @param string $filename
185
	 * @throws NotFoundException
186
	 * @return \OCP\Files\SimpleFS\ISimpleFile
187
	 * @throws NotPermittedException
188
	 */
189
	public function getCachedImage(string $filename): ISimpleFile {
190
		$currentFolder = $this->getCacheFolder();
191
		return $currentFolder->getFile($filename);
192
	}
193
194
	/**
195
	 * Store a file for theming in AppData
196
	 *
197
	 * @param string $filename
198
	 * @param string $data
199
	 * @return \OCP\Files\SimpleFS\ISimpleFile
200
	 * @throws NotFoundException
201
	 * @throws NotPermittedException
202
	 */
203
	public function setCachedImage(string $filename, string $data): ISimpleFile {
204
		$currentFolder = $this->getCacheFolder();
205
		if ($currentFolder->fileExists($filename)) {
206
			$file = $currentFolder->getFile($filename);
207
		} else {
208
			$file = $currentFolder->newFile($filename);
209
		}
210
		$file->putContent($data);
211
		return $file;
212
	}
213
214
	public function delete(string $key): void {
215
		/* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
216
		try {
217
			$file = $this->getRootFolder()->getFolder('images')->getFile($key);
218
			$file->delete();
219
		} catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
220
		} catch (NotPermittedException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
221
		}
222
		try {
223
			$file = $this->getRootFolder()->getFolder('images')->getFile($key . '.png');
224
			$file->delete();
225
		} catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
226
		} catch (NotPermittedException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
227
		}
228
	}
229
230
	public function updateImage(string $key, string $tmpFile): string {
231
		$this->delete($key);
232
233
		try {
234
			$folder = $this->getRootFolder()->getFolder('images');
235
		} catch (NotFoundException $e) {
236
			$folder = $this->getRootFolder()->newFolder('images');
237
		}
238
239
		$target = $folder->newFile($key);
240
		$supportedFormats = $this->getSupportedUploadImageFormats($key);
241
		$detectedMimeType = mime_content_type($tmpFile);
242
		if (!in_array($detectedMimeType, $supportedFormats, true)) {
243
			throw new \Exception('Unsupported image type');
244
		}
245
246
		if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
247
			// Optimize the image since some people may upload images that will be
248
			// either to big or are not progressive rendering.
249
			$newImage = @imagecreatefromstring(file_get_contents($tmpFile));
250
251
			// Preserve transparency
252
			imagesavealpha($newImage, true);
253
			imagealphablending($newImage, true);
254
255
			$tmpFile = $this->tempManager->getTemporaryFile();
256
			$newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
257
			$newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
258
			$outputImage = imagescale($newImage, $newWidth, $newHeight);
259
260
			imageinterlace($outputImage, 1);
261
			imagepng($outputImage, $tmpFile, 8);
262
			imagedestroy($outputImage);
263
264
			$target->putContent(file_get_contents($tmpFile));
265
		} else {
266
			$target->putContent(file_get_contents($tmpFile));
267
		}
268
269
		return $detectedMimeType;
270
	}
271
272
	/**
273
	 * Returns a list of supported mime types for image uploads.
274
	 * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
275
	 *
276
	 * @param string $key The image key, e.g. "favicon"
277
	 * @return string[]
278
	 */
279
	private function getSupportedUploadImageFormats(string $key): array {
280
		$supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
281
282
		if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
283
			$supportedFormats[] = 'image/svg+xml';
284
			$supportedFormats[] = 'image/svg';
285
		}
286
287
		if ($key === 'favicon') {
288
			$supportedFormats[] = 'image/x-icon';
289
			$supportedFormats[] = 'image/vnd.microsoft.icon';
290
		}
291
292
		return $supportedFormats;
293
	}
294
295
	/**
296
	 * remove cached files that are not required any longer
297
	 *
298
	 * @throws NotPermittedException
299
	 * @throws NotFoundException
300
	 */
301
	public function cleanup() {
302
		$currentFolder = $this->getCacheFolder();
303
		$folders = $this->getRootFolder()->getDirectoryListing();
304
		foreach ($folders as $folder) {
305
			if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
306
				$folder->delete();
307
			}
308
		}
309
	}
310
311
	/**
312
	 * Check if Imagemagick is enabled and if SVG is supported
313
	 * otherwise we can't render custom icons
314
	 *
315
	 * @return bool
316
	 */
317
	public function shouldReplaceIcons() {
318
		$cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
319
		if ($value = $cache->get('shouldReplaceIcons')) {
320
			return (bool)$value;
321
		}
322
		$value = false;
323
		if (extension_loaded('imagick')) {
324
			if (count(\Imagick::queryFormats('SVG')) >= 1) {
325
				$value = true;
326
			}
327
		}
328
		$cache->set('shouldReplaceIcons', $value);
329
		return $value;
330
	}
331
332
	private function getRootFolder(): ISimpleFolder {
333
		try {
334
			return $this->appData->getFolder('global');
335
		} catch (NotFoundException $e) {
336
			return $this->appData->newFolder('global');
337
		}
338
	}
339
}
340