1
0

ImageManager.php 9.7 KB

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