1
0

ImageManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Theming;
  7. use OCA\Theming\AppInfo\Application;
  8. use OCA\Theming\Service\BackgroundService;
  9. use OCP\Files\IAppData;
  10. use OCP\Files\NotFoundException;
  11. use OCP\Files\NotPermittedException;
  12. use OCP\Files\SimpleFS\ISimpleFile;
  13. use OCP\Files\SimpleFS\ISimpleFolder;
  14. use OCP\ICacheFactory;
  15. use OCP\IConfig;
  16. use OCP\ITempManager;
  17. use OCP\IURLGenerator;
  18. use Psr\Log\LoggerInterface;
  19. class ImageManager {
  20. public const SUPPORTED_IMAGE_KEYS = ['background', 'logo', 'logoheader', 'favicon'];
  21. public function __construct(
  22. private IConfig $config,
  23. private IAppData $appData,
  24. private IURLGenerator $urlGenerator,
  25. private ICacheFactory $cacheFactory,
  26. private LoggerInterface $logger,
  27. private ITempManager $tempManager,
  28. private BackgroundService $backgroundService,
  29. ) {
  30. }
  31. /**
  32. * Get a globally defined image (admin theming settings)
  33. *
  34. * @param string $key the image key
  35. * @return string the image url
  36. */
  37. public function getImageUrl(string $key): string {
  38. $cacheBusterCounter = $this->config->getAppValue(Application::APP_ID, 'cachebuster', '0');
  39. if ($this->hasImage($key)) {
  40. return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
  41. } elseif ($key === 'backgroundDark' && $this->hasImage('background')) {
  42. // Fall back to light variant
  43. return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => 'background' ]) . '?v=' . $cacheBusterCounter;
  44. }
  45. switch ($key) {
  46. case 'logo':
  47. case 'logoheader':
  48. case 'favicon':
  49. return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
  50. case 'backgroundDark':
  51. case 'background':
  52. // Removing the background defines its mime as 'backgroundColor'
  53. $mimeSetting = $this->config->getAppValue('theming', 'backgroundMime', '');
  54. if ($mimeSetting !== 'backgroundColor') {
  55. $image = BackgroundService::DEFAULT_BACKGROUND_IMAGE;
  56. if ($key === 'backgroundDark') {
  57. $image = BackgroundService::SHIPPED_BACKGROUNDS[$image]['dark_variant'] ?? $image;
  58. }
  59. return $this->urlGenerator->linkTo(Application::APP_ID, "img/background/$image");
  60. }
  61. }
  62. return '';
  63. }
  64. /**
  65. * Get the absolute url. See getImageUrl
  66. */
  67. public function getImageUrlAbsolute(string $key): string {
  68. return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key));
  69. }
  70. /**
  71. * @param string $key
  72. * @param bool $useSvg
  73. * @return ISimpleFile
  74. * @throws NotFoundException
  75. * @throws NotPermittedException
  76. */
  77. public function getImage(string $key, bool $useSvg = true): ISimpleFile {
  78. $mime = $this->config->getAppValue('theming', $key . 'Mime', '');
  79. $folder = $this->getRootFolder()->getFolder('images');
  80. if ($mime === '' || !$folder->fileExists($key)) {
  81. throw new NotFoundException();
  82. }
  83. if (!$useSvg && $this->shouldReplaceIcons()) {
  84. if (!$folder->fileExists($key . '.png')) {
  85. try {
  86. $finalIconFile = new \Imagick();
  87. $finalIconFile->setBackgroundColor('none');
  88. $finalIconFile->readImageBlob($folder->getFile($key)->getContent());
  89. $finalIconFile->setImageFormat('png32');
  90. $pngFile = $folder->newFile($key . '.png');
  91. $pngFile->putContent($finalIconFile->getImageBlob());
  92. return $pngFile;
  93. } catch (\ImagickException $e) {
  94. $this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
  95. }
  96. } else {
  97. return $folder->getFile($key . '.png');
  98. }
  99. }
  100. return $folder->getFile($key);
  101. }
  102. public function hasImage(string $key): bool {
  103. $mimeSetting = $this->config->getAppValue('theming', $key . 'Mime', '');
  104. // Removing the background defines its mime as 'backgroundColor'
  105. return $mimeSetting !== '' && $mimeSetting !== 'backgroundColor';
  106. }
  107. /**
  108. * @return array<string, array{mime: string, url: string}>
  109. */
  110. public function getCustomImages(): array {
  111. $images = [];
  112. foreach (self::SUPPORTED_IMAGE_KEYS as $key) {
  113. $images[$key] = [
  114. 'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
  115. 'url' => $this->getImageUrl($key),
  116. ];
  117. }
  118. return $images;
  119. }
  120. /**
  121. * Get folder for current theming files
  122. *
  123. * @return ISimpleFolder
  124. * @throws NotPermittedException
  125. */
  126. public function getCacheFolder(): ISimpleFolder {
  127. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  128. try {
  129. $folder = $this->getRootFolder()->getFolder($cacheBusterValue);
  130. } catch (NotFoundException $e) {
  131. $folder = $this->getRootFolder()->newFolder($cacheBusterValue);
  132. $this->cleanup();
  133. }
  134. return $folder;
  135. }
  136. /**
  137. * Get a file from AppData
  138. *
  139. * @param string $filename
  140. * @throws NotFoundException
  141. * @return ISimpleFile
  142. * @throws NotPermittedException
  143. */
  144. public function getCachedImage(string $filename): ISimpleFile {
  145. $currentFolder = $this->getCacheFolder();
  146. return $currentFolder->getFile($filename);
  147. }
  148. /**
  149. * Store a file for theming in AppData
  150. *
  151. * @param string $filename
  152. * @param string $data
  153. * @return ISimpleFile
  154. * @throws NotFoundException
  155. * @throws NotPermittedException
  156. */
  157. public function setCachedImage(string $filename, string $data): ISimpleFile {
  158. $currentFolder = $this->getCacheFolder();
  159. if ($currentFolder->fileExists($filename)) {
  160. $file = $currentFolder->getFile($filename);
  161. } else {
  162. $file = $currentFolder->newFile($filename);
  163. }
  164. $file->putContent($data);
  165. return $file;
  166. }
  167. public function delete(string $key): void {
  168. /* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
  169. try {
  170. $file = $this->getRootFolder()->getFolder('images')->getFile($key);
  171. $file->delete();
  172. } catch (NotFoundException $e) {
  173. } catch (NotPermittedException $e) {
  174. }
  175. try {
  176. $file = $this->getRootFolder()->getFolder('images')->getFile($key . '.png');
  177. $file->delete();
  178. } catch (NotFoundException $e) {
  179. } catch (NotPermittedException $e) {
  180. }
  181. if ($key === 'logo') {
  182. $this->config->deleteAppValue('theming', 'logoDimensions');
  183. }
  184. }
  185. public function updateImage(string $key, string $tmpFile): string {
  186. $this->delete($key);
  187. try {
  188. $folder = $this->getRootFolder()->getFolder('images');
  189. } catch (NotFoundException $e) {
  190. $folder = $this->getRootFolder()->newFolder('images');
  191. }
  192. $target = $folder->newFile($key);
  193. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  194. $detectedMimeType = mime_content_type($tmpFile);
  195. if (!in_array($detectedMimeType, $supportedFormats, true)) {
  196. throw new \Exception('Unsupported image type: ' . $detectedMimeType);
  197. }
  198. if ($key === 'background') {
  199. if ($this->shouldOptimizeBackgroundImage($detectedMimeType, filesize($tmpFile))) {
  200. try {
  201. // Optimize the image since some people may upload images that will be
  202. // either to big or are not progressive rendering.
  203. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  204. if ($newImage === false) {
  205. throw new \Exception('Could not read background image, possibly corrupted.');
  206. }
  207. // Preserve transparency
  208. imagesavealpha($newImage, true);
  209. imagealphablending($newImage, true);
  210. $imageWidth = imagesx($newImage);
  211. $imageHeight = imagesy($newImage);
  212. /** @var int */
  213. $newWidth = min(4096, $imageWidth);
  214. $newHeight = intval($imageHeight / ($imageWidth / $newWidth));
  215. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  216. if ($outputImage === false) {
  217. throw new \Exception('Could not scale uploaded background image.');
  218. }
  219. $newTmpFile = $this->tempManager->getTemporaryFile();
  220. imageinterlace($outputImage, true);
  221. // Keep jpeg images encoded as jpeg
  222. if (str_contains($detectedMimeType, 'image/jpeg')) {
  223. if (!imagejpeg($outputImage, $newTmpFile, 90)) {
  224. throw new \Exception('Could not recompress background image as JPEG');
  225. }
  226. } else {
  227. if (!imagepng($outputImage, $newTmpFile, 8)) {
  228. throw new \Exception('Could not recompress background image as PNG');
  229. }
  230. }
  231. $tmpFile = $newTmpFile;
  232. imagedestroy($outputImage);
  233. } catch (\Exception $e) {
  234. if (isset($outputImage) && is_resource($outputImage) || $outputImage instanceof \GdImage) {
  235. imagedestroy($outputImage);
  236. }
  237. $this->logger->debug($e->getMessage());
  238. }
  239. }
  240. // For background images we need to announce it
  241. $this->backgroundService->setGlobalBackground($tmpFile);
  242. }
  243. $target->putContent(file_get_contents($tmpFile));
  244. if ($key === 'logo') {
  245. $content = file_get_contents($tmpFile);
  246. $newImage = @imagecreatefromstring($content);
  247. if ($newImage !== false) {
  248. $this->config->setAppValue('theming', 'logoDimensions', imagesx($newImage) . 'x' . imagesy($newImage));
  249. } elseif (str_starts_with($detectedMimeType, 'image/svg')) {
  250. $matched = preg_match('/viewbox=["\']\d* \d* (\d*\.?\d*) (\d*\.?\d*)["\']/i', $content, $matches);
  251. if ($matched) {
  252. $this->config->setAppValue('theming', 'logoDimensions', $matches[1] . 'x' . $matches[2]);
  253. } else {
  254. $this->logger->warning('Could not read logo image dimensions to optimize for mail header');
  255. $this->config->deleteAppValue('theming', 'logoDimensions');
  256. }
  257. } else {
  258. $this->logger->warning('Could not read logo image dimensions to optimize for mail header');
  259. $this->config->deleteAppValue('theming', 'logoDimensions');
  260. }
  261. }
  262. return $detectedMimeType;
  263. }
  264. /**
  265. * Decide whether an image benefits from shrinking and reconverting
  266. *
  267. * @param string $mimeType the mime type of the image
  268. * @param int $contentSize size of the image file
  269. * @return bool
  270. */
  271. private function shouldOptimizeBackgroundImage(string $mimeType, int $contentSize): bool {
  272. // Do not touch SVGs
  273. if (str_contains($mimeType, 'image/svg')) {
  274. return false;
  275. }
  276. // GIF does not benefit from converting
  277. if (str_contains($mimeType, 'image/gif')) {
  278. return false;
  279. }
  280. // WebP also does not benefit from converting
  281. // We could possibly try to convert to progressive image, but normally webP images are quite small
  282. if (str_contains($mimeType, 'image/webp')) {
  283. return false;
  284. }
  285. // As a rule of thumb background images should be max. 150-300 KiB, small images do not benefit from converting
  286. return $contentSize > 150000;
  287. }
  288. /**
  289. * Returns a list of supported mime types for image uploads.
  290. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  291. *
  292. * @param string $key The image key, e.g. "favicon"
  293. * @return string[]
  294. */
  295. public function getSupportedUploadImageFormats(string $key): array {
  296. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  297. if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
  298. $supportedFormats[] = 'image/svg+xml';
  299. $supportedFormats[] = 'image/svg';
  300. }
  301. if ($key === 'favicon') {
  302. $supportedFormats[] = 'image/x-icon';
  303. $supportedFormats[] = 'image/vnd.microsoft.icon';
  304. }
  305. return $supportedFormats;
  306. }
  307. /**
  308. * remove cached files that are not required any longer
  309. *
  310. * @throws NotPermittedException
  311. * @throws NotFoundException
  312. */
  313. public function cleanup() {
  314. $currentFolder = $this->getCacheFolder();
  315. $folders = $this->getRootFolder()->getDirectoryListing();
  316. foreach ($folders as $folder) {
  317. if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
  318. $folder->delete();
  319. }
  320. }
  321. }
  322. /**
  323. * Check if Imagemagick is enabled and if SVG is supported
  324. * otherwise we can't render custom icons
  325. *
  326. * @return bool
  327. */
  328. public function shouldReplaceIcons() {
  329. $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
  330. if ($value = $cache->get('shouldReplaceIcons')) {
  331. return (bool)$value;
  332. }
  333. $value = false;
  334. if (extension_loaded('imagick')) {
  335. if (count(\Imagick::queryFormats('SVG')) >= 1) {
  336. $value = true;
  337. }
  338. }
  339. $cache->set('shouldReplaceIcons', $value);
  340. return $value;
  341. }
  342. private function getRootFolder(): ISimpleFolder {
  343. try {
  344. return $this->appData->getFolder('global');
  345. } catch (NotFoundException $e) {
  346. return $this->appData->newFolder('global');
  347. }
  348. }
  349. }