ImageManager.php 12 KB

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