ImageManager.php 12 KB

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