ImageManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Julius Härtl <jus@bitgrid.net>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Ferdinand Thiessen <opensource@fthiessen.de>
  8. * @author Gary Kim <gary@garykim.dev>
  9. * @author Jacob Neplokh <me@jacobneplokh.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Julien Veyssier <eneiluj@posteo.net>
  12. * @author Julius Haertl <jus@bitgrid.net>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Michael Weimann <mail@michael-weimann.eu>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author ste101 <stephan_bauer@gmx.de>
  18. *
  19. * @license GNU AGPL version 3 or any later version
  20. *
  21. * This program is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License as
  23. * published by the Free Software Foundation, either version 3 of the
  24. * License, or (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  33. *
  34. */
  35. namespace OCA\Theming;
  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\ITempManager;
  46. use OCP\IURLGenerator;
  47. use Psr\Log\LoggerInterface;
  48. class ImageManager {
  49. public const SUPPORTED_IMAGE_KEYS = ['background', 'logo', 'logoheader', 'favicon'];
  50. public function __construct(
  51. private IConfig $config,
  52. private IAppData $appData,
  53. private IURLGenerator $urlGenerator,
  54. private ICacheFactory $cacheFactory,
  55. private LoggerInterface $logger,
  56. private ITempManager $tempManager,
  57. private BackgroundService $backgroundService,
  58. ) {
  59. }
  60. /**
  61. * Get a globally defined image (admin theming settings)
  62. *
  63. * @param string $key the image key
  64. * @return string the image url
  65. */
  66. public function getImageUrl(string $key): string {
  67. $cacheBusterCounter = $this->config->getAppValue(Application::APP_ID, 'cachebuster', '0');
  68. if ($this->hasImage($key)) {
  69. return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
  70. }
  71. switch ($key) {
  72. case 'logo':
  73. case 'logoheader':
  74. case 'favicon':
  75. return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
  76. case 'background':
  77. // Removing the background defines its mime as 'backgroundColor'
  78. $mimeSetting = $this->config->getAppValue('theming', 'backgroundMime', '');
  79. if ($mimeSetting !== 'backgroundColor') {
  80. return $this->urlGenerator->linkTo(Application::APP_ID, 'img/background/' . BackgroundService::DEFAULT_BACKGROUND_IMAGE);
  81. }
  82. }
  83. return '';
  84. }
  85. /**
  86. * Get the absolute url. See getImageUrl
  87. */
  88. public function getImageUrlAbsolute(string $key): string {
  89. return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key));
  90. }
  91. /**
  92. * @param string $key
  93. * @param bool $useSvg
  94. * @return ISimpleFile
  95. * @throws NotFoundException
  96. * @throws NotPermittedException
  97. */
  98. public function getImage(string $key, bool $useSvg = true): ISimpleFile {
  99. $mime = $this->config->getAppValue('theming', $key . 'Mime', '');
  100. $folder = $this->getRootFolder()->getFolder('images');
  101. if ($mime === '' || !$folder->fileExists($key)) {
  102. throw new NotFoundException();
  103. }
  104. if (!$useSvg && $this->shouldReplaceIcons()) {
  105. if (!$folder->fileExists($key . '.png')) {
  106. try {
  107. $finalIconFile = new \Imagick();
  108. $finalIconFile->setBackgroundColor('none');
  109. $finalIconFile->readImageBlob($folder->getFile($key)->getContent());
  110. $finalIconFile->setImageFormat('png32');
  111. $pngFile = $folder->newFile($key . '.png');
  112. $pngFile->putContent($finalIconFile->getImageBlob());
  113. return $pngFile;
  114. } catch (\ImagickException $e) {
  115. $this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
  116. }
  117. } else {
  118. return $folder->getFile($key . '.png');
  119. }
  120. }
  121. return $folder->getFile($key);
  122. }
  123. public function hasImage(string $key): bool {
  124. $mimeSetting = $this->config->getAppValue('theming', $key . 'Mime', '');
  125. // Removing the background defines its mime as 'backgroundColor'
  126. return $mimeSetting !== '' && $mimeSetting !== 'backgroundColor';
  127. }
  128. /**
  129. * @return array<string, array{mime: string, url: string}>
  130. */
  131. public function getCustomImages(): array {
  132. $images = [];
  133. foreach (self::SUPPORTED_IMAGE_KEYS as $key) {
  134. $images[$key] = [
  135. 'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
  136. 'url' => $this->getImageUrl($key),
  137. ];
  138. }
  139. return $images;
  140. }
  141. /**
  142. * Get folder for current theming files
  143. *
  144. * @return ISimpleFolder
  145. * @throws NotPermittedException
  146. */
  147. public function getCacheFolder(): ISimpleFolder {
  148. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  149. try {
  150. $folder = $this->getRootFolder()->getFolder($cacheBusterValue);
  151. } catch (NotFoundException $e) {
  152. $folder = $this->getRootFolder()->newFolder($cacheBusterValue);
  153. $this->cleanup();
  154. }
  155. return $folder;
  156. }
  157. /**
  158. * Get a file from AppData
  159. *
  160. * @param string $filename
  161. * @throws NotFoundException
  162. * @return \OCP\Files\SimpleFS\ISimpleFile
  163. * @throws NotPermittedException
  164. */
  165. public function getCachedImage(string $filename): ISimpleFile {
  166. $currentFolder = $this->getCacheFolder();
  167. return $currentFolder->getFile($filename);
  168. }
  169. /**
  170. * Store a file for theming in AppData
  171. *
  172. * @param string $filename
  173. * @param string $data
  174. * @return \OCP\Files\SimpleFS\ISimpleFile
  175. * @throws NotFoundException
  176. * @throws NotPermittedException
  177. */
  178. public function setCachedImage(string $filename, string $data): ISimpleFile {
  179. $currentFolder = $this->getCacheFolder();
  180. if ($currentFolder->fileExists($filename)) {
  181. $file = $currentFolder->getFile($filename);
  182. } else {
  183. $file = $currentFolder->newFile($filename);
  184. }
  185. $file->putContent($data);
  186. return $file;
  187. }
  188. public function delete(string $key): void {
  189. /* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
  190. try {
  191. $file = $this->getRootFolder()->getFolder('images')->getFile($key);
  192. $file->delete();
  193. } catch (NotFoundException $e) {
  194. } catch (NotPermittedException $e) {
  195. }
  196. try {
  197. $file = $this->getRootFolder()->getFolder('images')->getFile($key . '.png');
  198. $file->delete();
  199. } catch (NotFoundException $e) {
  200. } catch (NotPermittedException $e) {
  201. }
  202. }
  203. public function updateImage(string $key, string $tmpFile): string {
  204. $this->delete($key);
  205. try {
  206. $folder = $this->getRootFolder()->getFolder('images');
  207. } catch (NotFoundException $e) {
  208. $folder = $this->getRootFolder()->newFolder('images');
  209. }
  210. $target = $folder->newFile($key);
  211. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  212. $detectedMimeType = mime_content_type($tmpFile);
  213. if (!in_array($detectedMimeType, $supportedFormats, true)) {
  214. throw new \Exception('Unsupported image type: ' . $detectedMimeType);
  215. }
  216. if ($key === 'background') {
  217. if ($this->shouldOptimizeBackgroundImage($detectedMimeType, filesize($tmpFile))) {
  218. try {
  219. // Optimize the image since some people may upload images that will be
  220. // either to big or are not progressive rendering.
  221. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  222. if ($newImage === false) {
  223. throw new \Exception('Could not read background image, possibly corrupted.');
  224. }
  225. // Preserve transparency
  226. imagesavealpha($newImage, true);
  227. imagealphablending($newImage, true);
  228. $imageWidth = imagesx($newImage);
  229. $imageHeight = imagesy($newImage);
  230. /** @var int */
  231. $newWidth = min(4096, $imageWidth);
  232. $newHeight = intval($imageHeight / ($imageWidth / $newWidth));
  233. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  234. if ($outputImage === false) {
  235. throw new \Exception('Could not scale uploaded background image.');
  236. }
  237. $newTmpFile = $this->tempManager->getTemporaryFile();
  238. imageinterlace($outputImage, true);
  239. // Keep jpeg images encoded as jpeg
  240. if (str_contains($detectedMimeType, 'image/jpeg')) {
  241. if (!imagejpeg($outputImage, $newTmpFile, 90)) {
  242. throw new \Exception('Could not recompress background image as JPEG');
  243. }
  244. } else {
  245. if (!imagepng($outputImage, $newTmpFile, 8)) {
  246. throw new \Exception('Could not recompress background image as PNG');
  247. }
  248. }
  249. $tmpFile = $newTmpFile;
  250. imagedestroy($outputImage);
  251. } catch (\Exception $e) {
  252. if (isset($outputImage) && is_resource($outputImage) || $outputImage instanceof \GdImage) {
  253. imagedestroy($outputImage);
  254. }
  255. $this->logger->debug($e->getMessage());
  256. }
  257. }
  258. // For background images we need to announce it
  259. $this->backgroundService->setGlobalBackground($tmpFile);
  260. }
  261. $target->putContent(file_get_contents($tmpFile));
  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. }