ImageManager.php 9.2 KB

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