You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageManager.php 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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) <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. *
  17. * @license GNU AGPL version 3 or any later version
  18. *
  19. * This program is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License as
  21. * published by the Free Software Foundation, either version 3 of the
  22. * License, or (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  31. *
  32. */
  33. namespace OCA\Theming;
  34. use OCP\Files\IAppData;
  35. use OCP\Files\NotFoundException;
  36. use OCP\Files\NotPermittedException;
  37. use OCP\Files\SimpleFS\ISimpleFile;
  38. use OCP\Files\SimpleFS\ISimpleFolder;
  39. use OCP\ICacheFactory;
  40. use OCP\IConfig;
  41. use OCP\ILogger;
  42. use OCP\ITempManager;
  43. use OCP\IURLGenerator;
  44. class ImageManager {
  45. /** @var IConfig */
  46. private $config;
  47. /** @var IAppData */
  48. private $appData;
  49. /** @var IURLGenerator */
  50. private $urlGenerator;
  51. /** @var array */
  52. private $supportedImageKeys = ['background', 'logo', 'logoheader', 'favicon'];
  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. ) {
  66. $this->config = $config;
  67. $this->appData = $appData;
  68. $this->urlGenerator = $urlGenerator;
  69. $this->cacheFactory = $cacheFactory;
  70. $this->logger = $logger;
  71. $this->tempManager = $tempManager;
  72. }
  73. public function getImageUrl(string $key, bool $useSvg = true): string {
  74. $cacheBusterCounter = $this->config->getAppValue('theming', 'cachebuster', '0');
  75. try {
  76. $image = $this->getImage($key, $useSvg);
  77. return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
  78. } catch (NotFoundException $e) {
  79. }
  80. switch ($key) {
  81. case 'logo':
  82. case 'logoheader':
  83. case 'favicon':
  84. return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
  85. case 'background':
  86. return $this->urlGenerator->imagePath('core', 'background.png') . '?v=' . $cacheBusterCounter;
  87. }
  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 getCustomImages(): array {
  125. $images = [];
  126. foreach ($this->supportedImageKeys as $key) {
  127. $images[$key] = [
  128. 'mime' => $this->config->getAppValue('theming', $key . 'Mime', ''),
  129. 'url' => $this->getImageUrl($key),
  130. ];
  131. }
  132. return $images;
  133. }
  134. /**
  135. * Get folder for current theming files
  136. *
  137. * @return ISimpleFolder
  138. * @throws NotPermittedException
  139. */
  140. public function getCacheFolder(): ISimpleFolder {
  141. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  142. try {
  143. $folder = $this->appData->getFolder($cacheBusterValue);
  144. } catch (NotFoundException $e) {
  145. $folder = $this->appData->newFolder($cacheBusterValue);
  146. $this->cleanup();
  147. }
  148. return $folder;
  149. }
  150. /**
  151. * Get a file from AppData
  152. *
  153. * @param string $filename
  154. * @throws NotFoundException
  155. * @return \OCP\Files\SimpleFS\ISimpleFile
  156. * @throws NotPermittedException
  157. */
  158. public function getCachedImage(string $filename): ISimpleFile {
  159. $currentFolder = $this->getCacheFolder();
  160. return $currentFolder->getFile($filename);
  161. }
  162. /**
  163. * Store a file for theming in AppData
  164. *
  165. * @param string $filename
  166. * @param string $data
  167. * @return \OCP\Files\SimpleFS\ISimpleFile
  168. * @throws NotFoundException
  169. * @throws NotPermittedException
  170. */
  171. public function setCachedImage(string $filename, string $data): ISimpleFile {
  172. $currentFolder = $this->getCacheFolder();
  173. if ($currentFolder->fileExists($filename)) {
  174. $file = $currentFolder->getFile($filename);
  175. } else {
  176. $file = $currentFolder->newFile($filename);
  177. }
  178. $file->putContent($data);
  179. return $file;
  180. }
  181. public function delete(string $key) {
  182. /* ignore exceptions, since we don't want to fail hard if something goes wrong during cleanup */
  183. try {
  184. $file = $this->appData->getFolder('images')->getFile($key);
  185. $file->delete();
  186. } catch (NotFoundException $e) {
  187. } catch (NotPermittedException $e) {
  188. }
  189. try {
  190. $file = $this->appData->getFolder('images')->getFile($key . '.png');
  191. $file->delete();
  192. } catch (NotFoundException $e) {
  193. } catch (NotPermittedException $e) {
  194. }
  195. }
  196. public function updateImage(string $key, string $tmpFile) {
  197. $this->delete($key);
  198. try {
  199. $folder = $this->appData->getFolder('images');
  200. } catch (NotFoundException $e) {
  201. $folder = $this->appData->newFolder('images');
  202. }
  203. $target = $folder->newFile($key);
  204. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  205. $detectedMimeType = mime_content_type($tmpFile);
  206. if (!in_array($detectedMimeType, $supportedFormats, true)) {
  207. throw new \Exception('Unsupported image type');
  208. }
  209. if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
  210. // Optimize the image since some people may upload images that will be
  211. // either to big or are not progressive rendering.
  212. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  213. // Preserve transparency
  214. imagesavealpha($newImage, true);
  215. imagealphablending($newImage, true);
  216. $tmpFile = $this->tempManager->getTemporaryFile();
  217. $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
  218. $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
  219. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  220. imageinterlace($outputImage, 1);
  221. imagepng($outputImage, $tmpFile, 8);
  222. imagedestroy($outputImage);
  223. $target->putContent(file_get_contents($tmpFile));
  224. } else {
  225. $target->putContent(file_get_contents($tmpFile));
  226. }
  227. return $detectedMimeType;
  228. }
  229. /**
  230. * Returns a list of supported mime types for image uploads.
  231. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  232. *
  233. * @param string $key The image key, e.g. "favicon"
  234. * @return array
  235. */
  236. private function getSupportedUploadImageFormats(string $key): array {
  237. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif'];
  238. if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
  239. $supportedFormats[] = 'image/svg+xml';
  240. $supportedFormats[] = 'image/svg';
  241. }
  242. if ($key === 'favicon') {
  243. $supportedFormats[] = 'image/x-icon';
  244. $supportedFormats[] = 'image/vnd.microsoft.icon';
  245. }
  246. return $supportedFormats;
  247. }
  248. /**
  249. * remove cached files that are not required any longer
  250. *
  251. * @throws NotPermittedException
  252. * @throws NotFoundException
  253. */
  254. public function cleanup() {
  255. $currentFolder = $this->getCacheFolder();
  256. $folders = $this->appData->getDirectoryListing();
  257. foreach ($folders as $folder) {
  258. if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
  259. $folder->delete();
  260. }
  261. }
  262. }
  263. /**
  264. * Check if Imagemagick is enabled and if SVG is supported
  265. * otherwise we can't render custom icons
  266. *
  267. * @return bool
  268. */
  269. public function shouldReplaceIcons() {
  270. $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
  271. if ($value = $cache->get('shouldReplaceIcons')) {
  272. return (bool)$value;
  273. }
  274. $value = false;
  275. if (extension_loaded('imagick')) {
  276. if (count(\Imagick::queryFormats('SVG')) >= 1) {
  277. $value = true;
  278. }
  279. }
  280. $cache->set('shouldReplaceIcons', $value);
  281. return $value;
  282. }
  283. }