ImageManager.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 ICacheFactory */
  54. private $cacheFactory;
  55. /** @var ILogger */
  56. private $logger;
  57. /** @var ITempManager */
  58. private $tempManager;
  59. public function __construct(IConfig $config,
  60. IAppData $appData,
  61. IURLGenerator $urlGenerator,
  62. ICacheFactory $cacheFactory,
  63. ILogger $logger,
  64. ITempManager $tempManager) {
  65. $this->config = $config;
  66. $this->urlGenerator = $urlGenerator;
  67. $this->cacheFactory = $cacheFactory;
  68. $this->logger = $logger;
  69. $this->tempManager = $tempManager;
  70. $this->appData = $appData;
  71. }
  72. public function getImageUrl(string $key, bool $useSvg = true): string {
  73. $cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
  74. if ($this->hasImage($key)) {
  75. return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
  76. }
  77. switch ($key) {
  78. case 'logo':
  79. case 'logoheader':
  80. case 'favicon':
  81. return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
  82. case 'background':
  83. return $this->urlGenerator->imagePath('core', 'background.png') . '?v=' . $cacheBusterCounter;
  84. }
  85. return '';
  86. }
  87. public function getImageUrlAbsolute(string $key, bool $useSvg = true): string {
  88. return $this->urlGenerator->getAbsoluteURL($this->getImageUrl($key, $useSvg));
  89. }
  90. /**
  91. * @param string $key
  92. * @param bool $useSvg
  93. * @return ISimpleFile
  94. * @throws NotFoundException
  95. * @throws NotPermittedException
  96. */
  97. public function getImage(string $key, bool $useSvg = true): ISimpleFile {
  98. $logo = $this->config->getAppValue('theming', $key . 'Mime', '');
  99. $folder = $this->getRootFolder()->getFolder('images');
  100. if ($logo === '' || !$folder->fileExists($key)) {
  101. throw new NotFoundException();
  102. }
  103. if (!$useSvg && $this->shouldReplaceIcons()) {
  104. if (!$folder->fileExists($key . '.png')) {
  105. try {
  106. $finalIconFile = new \Imagick();
  107. $finalIconFile->setBackgroundColor('none');
  108. $finalIconFile->readImageBlob($folder->getFile($key)->getContent());
  109. $finalIconFile->setImageFormat('png32');
  110. $pngFile = $folder->newFile($key . '.png');
  111. $pngFile->putContent($finalIconFile->getImageBlob());
  112. return $pngFile;
  113. } catch (\ImagickException $e) {
  114. $this->logger->info('The image was requested to be no SVG file, but converting it to PNG failed: ' . $e->getMessage());
  115. }
  116. } else {
  117. return $folder->getFile($key . '.png');
  118. }
  119. }
  120. return $folder->getFile($key);
  121. }
  122. public function hasImage(string $key): bool {
  123. $mimeSetting = $this->config->getAppValue('theming', $key . 'Mime', '');
  124. return $mimeSetting !== '';
  125. }
  126. /**
  127. * Get folder for current theming files
  128. *
  129. * @return ISimpleFolder
  130. * @throws NotPermittedException
  131. */
  132. public function getCacheFolder(): ISimpleFolder {
  133. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  134. try {
  135. $folder = $this->getRootFolder()->getFolder($cacheBusterValue);
  136. } catch (NotFoundException $e) {
  137. $folder = $this->getRootFolder()->newFolder($cacheBusterValue);
  138. $this->cleanup();
  139. }
  140. return $folder;
  141. }
  142. /**
  143. * Get a file from AppData
  144. *
  145. * @param string $filename
  146. * @throws NotFoundException
  147. * @return \OCP\Files\SimpleFS\ISimpleFile
  148. * @throws NotPermittedException
  149. */
  150. public function getCachedImage(string $filename): ISimpleFile {
  151. $currentFolder = $this->getCacheFolder();
  152. return $currentFolder->getFile($filename);
  153. }
  154. /**
  155. * Store a file for theming in AppData
  156. *
  157. * @param string $filename
  158. * @param string $data
  159. * @return \OCP\Files\SimpleFS\ISimpleFile
  160. * @throws NotFoundException
  161. * @throws NotPermittedException
  162. */
  163. public function setCachedImage(string $filename, string $data): ISimpleFile {
  164. $currentFolder = $this->getCacheFolder();
  165. if ($currentFolder->fileExists($filename)) {
  166. $file = $currentFolder->getFile($filename);
  167. } else {
  168. $file = $currentFolder->newFile($filename);
  169. }
  170. $file->putContent($data);
  171. return $file;
  172. }
  173. public function delete(string $key): void {
  174. /* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
  175. try {
  176. $file = $this->getRootFolder()->getFolder('images')->getFile($key);
  177. $file->delete();
  178. } catch (NotFoundException $e) {
  179. } catch (NotPermittedException $e) {
  180. }
  181. try {
  182. $file = $this->getRootFolder()->getFolder('images')->getFile($key . '.png');
  183. $file->delete();
  184. } catch (NotFoundException $e) {
  185. } catch (NotPermittedException $e) {
  186. }
  187. }
  188. public function updateImage(string $key, string $tmpFile): string {
  189. $this->delete($key);
  190. try {
  191. $folder = $this->getRootFolder()->getFolder('images');
  192. } catch (NotFoundException $e) {
  193. $folder = $this->getRootFolder()->newFolder('images');
  194. }
  195. $target = $folder->newFile($key);
  196. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  197. $detectedMimeType = mime_content_type($tmpFile);
  198. if (!in_array($detectedMimeType, $supportedFormats, true)) {
  199. throw new \Exception('Unsupported image type');
  200. }
  201. if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
  202. // Optimize the image since some people may upload images that will be
  203. // either to big or are not progressive rendering.
  204. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  205. // Preserve transparency
  206. imagesavealpha($newImage, true);
  207. imagealphablending($newImage, true);
  208. $tmpFile = $this->tempManager->getTemporaryFile();
  209. $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
  210. $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
  211. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  212. imageinterlace($outputImage, 1);
  213. imagepng($outputImage, $tmpFile, 8);
  214. imagedestroy($outputImage);
  215. $target->putContent(file_get_contents($tmpFile));
  216. } else {
  217. $target->putContent(file_get_contents($tmpFile));
  218. }
  219. return $detectedMimeType;
  220. }
  221. /**
  222. * Returns a list of supported mime types for image uploads.
  223. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  224. *
  225. * @param string $key The image key, e.g. "favicon"
  226. * @return string[]
  227. */
  228. private function getSupportedUploadImageFormats(string $key): array {
  229. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  230. if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
  231. $supportedFormats[] = 'image/svg+xml';
  232. $supportedFormats[] = 'image/svg';
  233. }
  234. if ($key === 'favicon') {
  235. $supportedFormats[] = 'image/x-icon';
  236. $supportedFormats[] = 'image/vnd.microsoft.icon';
  237. }
  238. return $supportedFormats;
  239. }
  240. /**
  241. * remove cached files that are not required any longer
  242. *
  243. * @throws NotPermittedException
  244. * @throws NotFoundException
  245. */
  246. public function cleanup() {
  247. $currentFolder = $this->getCacheFolder();
  248. $folders = $this->getRootFolder()->getDirectoryListing();
  249. foreach ($folders as $folder) {
  250. if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
  251. $folder->delete();
  252. }
  253. }
  254. }
  255. /**
  256. * Check if Imagemagick is enabled and if SVG is supported
  257. * otherwise we can't render custom icons
  258. *
  259. * @return bool
  260. */
  261. public function shouldReplaceIcons() {
  262. $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
  263. if ($value = $cache->get('shouldReplaceIcons')) {
  264. return (bool)$value;
  265. }
  266. $value = false;
  267. if (extension_loaded('imagick')) {
  268. if (count(\Imagick::queryFormats('SVG')) >= 1) {
  269. $value = true;
  270. }
  271. }
  272. $cache->set('shouldReplaceIcons', $value);
  273. return $value;
  274. }
  275. private function getRootFolder(): ISimpleFolder {
  276. try {
  277. return $this->appData->getFolder('global');
  278. } catch (NotFoundException $e) {
  279. return $this->appData->newFolder('global');
  280. }
  281. }
  282. }