ImageManager.php 11 KB

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