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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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);
  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' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
  226. // Optimize the image since some people may upload images that will be
  227. // either to big or are not progressive rendering.
  228. $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
  229. // Preserve transparency
  230. imagesavealpha($newImage, true);
  231. imagealphablending($newImage, true);
  232. $tmpFile = $this->tempManager->getTemporaryFile();
  233. $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
  234. $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
  235. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  236. imageinterlace($outputImage, 1);
  237. imagepng($outputImage, $tmpFile, 8);
  238. imagedestroy($outputImage);
  239. $target->putContent(file_get_contents($tmpFile));
  240. } else {
  241. $target->putContent(file_get_contents($tmpFile));
  242. }
  243. return $detectedMimeType;
  244. }
  245. /**
  246. * Returns a list of supported mime types for image uploads.
  247. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  248. *
  249. * @param string $key The image key, e.g. "favicon"
  250. * @return string[]
  251. */
  252. private function getSupportedUploadImageFormats(string $key): array {
  253. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  254. if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {
  255. $supportedFormats[] = 'image/svg+xml';
  256. $supportedFormats[] = 'image/svg';
  257. }
  258. if ($key === 'favicon') {
  259. $supportedFormats[] = 'image/x-icon';
  260. $supportedFormats[] = 'image/vnd.microsoft.icon';
  261. }
  262. return $supportedFormats;
  263. }
  264. /**
  265. * remove cached files that are not required any longer
  266. *
  267. * @throws NotPermittedException
  268. * @throws NotFoundException
  269. */
  270. public function cleanup() {
  271. $currentFolder = $this->getCacheFolder();
  272. $folders = $this->getRootFolder()->getDirectoryListing();
  273. foreach ($folders as $folder) {
  274. if ($folder->getName() !== 'images' && $folder->getName() !== $currentFolder->getName()) {
  275. $folder->delete();
  276. }
  277. }
  278. }
  279. /**
  280. * Check if Imagemagick is enabled and if SVG is supported
  281. * otherwise we can't render custom icons
  282. *
  283. * @return bool
  284. */
  285. public function shouldReplaceIcons() {
  286. $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl());
  287. if ($value = $cache->get('shouldReplaceIcons')) {
  288. return (bool)$value;
  289. }
  290. $value = false;
  291. if (extension_loaded('imagick')) {
  292. if (count(\Imagick::queryFormats('SVG')) >= 1) {
  293. $value = true;
  294. }
  295. }
  296. $cache->set('shouldReplaceIcons', $value);
  297. return $value;
  298. }
  299. private function getRootFolder(): ISimpleFolder {
  300. try {
  301. return $this->appData->getFolder('global');
  302. } catch (NotFoundException $e) {
  303. return $this->appData->newFolder('global');
  304. }
  305. }
  306. }