1
0

ImageManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. }
  197. public function updateImage(string $key, string $tmpFile): string {
  198. $this->delete($key);
  199. try {
  200. $folder = $this->getRootFolder()->getFolder('images');
  201. } catch (NotFoundException $e) {
  202. $folder = $this->getRootFolder()->newFolder('images');
  203. }
  204. $target = $folder->newFile($key);
  205. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  206. $detectedMimeType = mime_content_type($tmpFile);
  207. if (!in_array($detectedMimeType, $supportedFormats, true)) {
  208. throw new \Exception('Unsupported image type: ' . $detectedMimeType);
  209. }
  210. if ($key === 'background' && $this->shouldOptimizeBackgroundImage($detectedMimeType, filesize($tmpFile))) {
  211. try {
  212. // Optimize the image since some people may upload images that will be
  213. // either to big or are not progressive rendering.
  214. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  215. if ($newImage === false) {
  216. throw new \Exception('Could not read background image, possibly corrupted.');
  217. }
  218. // Preserve transparency
  219. imagesavealpha($newImage, true);
  220. imagealphablending($newImage, true);
  221. $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
  222. $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
  223. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  224. if ($outputImage === false) {
  225. throw new \Exception('Could not scale uploaded background image.');
  226. }
  227. $newTmpFile = $this->tempManager->getTemporaryFile();
  228. imageinterlace($outputImage, 1);
  229. // Keep jpeg images encoded as jpeg
  230. if (str_contains($detectedMimeType, 'image/jpeg')) {
  231. if (!imagejpeg($outputImage, $newTmpFile, 90)) {
  232. throw new \Exception('Could not recompress background image as JPEG');
  233. }
  234. } else {
  235. if (!imagepng($outputImage, $newTmpFile, 8)) {
  236. throw new \Exception('Could not recompress background image as PNG');
  237. }
  238. }
  239. $tmpFile = $newTmpFile;
  240. imagedestroy($outputImage);
  241. } catch (\Exception $e) {
  242. if (is_resource($outputImage) || $outputImage instanceof \GdImage) {
  243. imagedestroy($outputImage);
  244. }
  245. $this->logger->debug($e->getMessage());
  246. }
  247. }
  248. $target->putContent(file_get_contents($tmpFile));
  249. return $detectedMimeType;
  250. }
  251. /**
  252. * Decide whether an image benefits from shrinking and reconverting
  253. *
  254. * @param string $mimeType the mime type of the image
  255. * @param int $contentSize size of the image file
  256. * @return bool
  257. */
  258. private function shouldOptimizeBackgroundImage(string $mimeType, int $contentSize): bool {
  259. // Do not touch SVGs
  260. if (str_contains($mimeType, 'image/svg')) {
  261. return false;
  262. }
  263. // GIF does not benefit from converting
  264. if (str_contains($mimeType, 'image/gif')) {
  265. return false;
  266. }
  267. // WebP also does not benefit from converting
  268. // We could possibly try to convert to progressive image, but normally webP images are quite small
  269. if (str_contains($mimeType, 'image/webp')) {
  270. return false;
  271. }
  272. // As a rule of thumb background images should be max. 150-300 KiB, small images do not benefit from converting
  273. return $contentSize > 150000;
  274. }
  275. /**
  276. * Returns a list of supported mime types for image uploads.
  277. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  278. *
  279. * @param string $key The image key, e.g. "favicon"
  280. * @return string[]
  281. */
  282. public function getSupportedUploadImageFormats(string $key): array {
  283. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  284. if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
  285. $supportedFormats[] = 'image/svg+xml';
  286. $supportedFormats[] = 'image/svg';
  287. }
  288. if ($key === 'favicon') {
  289. $supportedFormats[] = 'image/x-icon';
  290. $supportedFormats[] = 'image/vnd.microsoft.icon';
  291. }
  292. return $supportedFormats;
  293. }
  294. /**
  295. * remove cached files that are not required any longer
  296. *
  297. * @throws NotPermittedException
  298. * @throws NotFoundException
  299. */
  300. public function cleanup() {
  301. $currentFolder = $this->getCacheFolder();
  302. $folders = $this->getRootFolder()->getDirectoryListing();
  303. foreach ($folders as $folder) {
  304. if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
  305. $folder->delete();
  306. }
  307. }
  308. }
  309. /**
  310. * Check if Imagemagick is enabled and if SVG is supported
  311. * otherwise we can't render custom icons
  312. *
  313. * @return bool
  314. */
  315. public function shouldReplaceIcons() {
  316. $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
  317. if ($value = $cache->get('shouldReplaceIcons')) {
  318. return (bool)$value;
  319. }
  320. $value = false;
  321. if (extension_loaded('imagick')) {
  322. if (count(\Imagick::queryFormats('SVG')) >= 1) {
  323. $value = true;
  324. }
  325. }
  326. $cache->set('shouldReplaceIcons', $value);
  327. return $value;
  328. }
  329. private function getRootFolder(): ISimpleFolder {
  330. try {
  331. return $this->appData->getFolder('global');
  332. } catch (NotFoundException $e) {
  333. return $this->appData->newFolder('global');
  334. }
  335. }
  336. }