1
0

ImageManager.php 12 KB

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