aboutsummaryrefslogtreecommitdiffstats
path: root/apps/theming/lib/ImageManager.php
diff options
context:
space:
mode:
Diffstat (limited to 'apps/theming/lib/ImageManager.php')
-rw-r--r--apps/theming/lib/ImageManager.php215
1 files changed, 132 insertions, 83 deletions
diff --git a/apps/theming/lib/ImageManager.php b/apps/theming/lib/ImageManager.php
index f7b0c12844a..309bf192bc3 100644
--- a/apps/theming/lib/ImageManager.php
+++ b/apps/theming/lib/ImageManager.php
@@ -1,35 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2016 Julius Härtl <jus@bitgrid.net>
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Kesselberg <mail@danielkesselberg.de>
- * @author Gary Kim <gary@garykim.dev>
- * @author Jacob Neplokh <me@jacobneplokh.com>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Julien Veyssier <eneiluj@posteo.net>
- * @author Julius Haertl <jus@bitgrid.net>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Michael Weimann <mail@michael-weimann.eu>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author ste101 <stephan_bauer@gmx.de>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Theming;
@@ -42,38 +15,22 @@ use OCP\Files\SimpleFS\ISimpleFile;
use OCP\Files\SimpleFS\ISimpleFolder;
use OCP\ICacheFactory;
use OCP\IConfig;
-use OCP\ILogger;
use OCP\ITempManager;
use OCP\IURLGenerator;
+use Psr\Log\LoggerInterface;
class ImageManager {
public const SUPPORTED_IMAGE_KEYS = ['background', 'logo', 'logoheader', 'favicon'];
- /** @var IConfig */
- private $config;
- /** @var IAppData */
- private $appData;
- /** @var IURLGenerator */
- private $urlGenerator;
- /** @var ICacheFactory */
- private $cacheFactory;
- /** @var ILogger */
- private $logger;
- /** @var ITempManager */
- private $tempManager;
-
- public function __construct(IConfig $config,
- IAppData $appData,
- IURLGenerator $urlGenerator,
- ICacheFactory $cacheFactory,
- ILogger $logger,
- ITempManager $tempManager) {
- $this->config = $config;
- $this->urlGenerator = $urlGenerator;
- $this->cacheFactory = $cacheFactory;
- $this->logger = $logger;
- $this->tempManager = $tempManager;
- $this->appData = $appData;
+ public function __construct(
+ private IConfig $config,
+ private IAppData $appData,
+ private IURLGenerator $urlGenerator,
+ private ICacheFactory $cacheFactory,
+ private LoggerInterface $logger,
+ private ITempManager $tempManager,
+ private BackgroundService $backgroundService,
+ ) {
}
/**
@@ -86,6 +43,9 @@ class ImageManager {
$cacheBusterCounter = $this->config->getAppValue(Application::APP_ID, 'cachebuster', '0');
if ($this->hasImage($key)) {
return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => $key ]) . '?v=' . $cacheBusterCounter;
+ } elseif ($key === 'backgroundDark' && $this->hasImage('background')) {
+ // Fall back to light variant
+ return $this->urlGenerator->linkToRoute('theming.Theming.getImage', [ 'key' => 'background' ]) . '?v=' . $cacheBusterCounter;
}
switch ($key) {
@@ -93,8 +53,17 @@ class ImageManager {
case 'logoheader':
case 'favicon':
return $this->urlGenerator->imagePath('core', 'logo/logo.png') . '?v=' . $cacheBusterCounter;
+ case 'backgroundDark':
case 'background':
- return $this->urlGenerator->linkTo(Application::APP_ID, 'img/background/' . BackgroundService::DEFAULT_BACKGROUND_IMAGE);
+ // Removing the background defines its mime as 'backgroundColor'
+ $mimeSetting = $this->config->getAppValue('theming', 'backgroundMime', '');
+ if ($mimeSetting !== 'backgroundColor') {
+ $image = BackgroundService::DEFAULT_BACKGROUND_IMAGE;
+ if ($key === 'backgroundDark') {
+ $image = BackgroundService::SHIPPED_BACKGROUNDS[$image]['dark_variant'] ?? $image;
+ }
+ return $this->urlGenerator->linkTo(Application::APP_ID, "img/background/$image");
+ }
}
return '';
}
@@ -114,10 +83,10 @@ class ImageManager {
* @throws NotPermittedException
*/
public function getImage(string $key, bool $useSvg = true): ISimpleFile {
- $logo = $this->config->getAppValue('theming', $key . 'Mime', '');
+ $mime = $this->config->getAppValue('theming', $key . 'Mime', '');
$folder = $this->getRootFolder()->getFolder('images');
- if ($logo === '' || !$folder->fileExists($key)) {
+ if ($mime === '' || !$folder->fileExists($key)) {
throw new NotFoundException();
}
@@ -144,7 +113,8 @@ class ImageManager {
public function hasImage(string $key): bool {
$mimeSetting = $this->config->getAppValue('theming', $key . 'Mime', '');
- return $mimeSetting !== '';
+ // Removing the background defines its mime as 'backgroundColor'
+ return $mimeSetting !== '' && $mimeSetting !== 'backgroundColor';
}
/**
@@ -183,7 +153,7 @@ class ImageManager {
*
* @param string $filename
* @throws NotFoundException
- * @return \OCP\Files\SimpleFS\ISimpleFile
+ * @return ISimpleFile
* @throws NotPermittedException
*/
public function getCachedImage(string $filename): ISimpleFile {
@@ -196,7 +166,7 @@ class ImageManager {
*
* @param string $filename
* @param string $data
- * @return \OCP\Files\SimpleFS\ISimpleFile
+ * @return ISimpleFile
* @throws NotFoundException
* @throws NotPermittedException
*/
@@ -225,6 +195,10 @@ class ImageManager {
} catch (NotFoundException $e) {
} catch (NotPermittedException $e) {
}
+
+ if ($key === 'logo') {
+ $this->config->deleteAppValue('theming', 'logoDimensions');
+ }
}
public function updateImage(string $key, string $tmpFile): string {
@@ -240,43 +214,118 @@ class ImageManager {
$supportedFormats = $this->getSupportedUploadImageFormats($key);
$detectedMimeType = mime_content_type($tmpFile);
if (!in_array($detectedMimeType, $supportedFormats, true)) {
- throw new \Exception('Unsupported image type');
+ throw new \Exception('Unsupported image type: ' . $detectedMimeType);
}
- if ($key === 'background' && strpos($detectedMimeType, 'image/svg') === false && strpos($detectedMimeType, 'image/gif') === false) {
- // Optimize the image since some people may upload images that will be
- // either to big or are not progressive rendering.
- $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
-
- // Preserve transparency
- imagesavealpha($newImage, true);
- imagealphablending($newImage, true);
-
- $tmpFile = $this->tempManager->getTemporaryFile();
- $newWidth = (int)(imagesx($newImage) < 4096 ? imagesx($newImage) : 4096);
- $newHeight = (int)(imagesy($newImage) / (imagesx($newImage) / $newWidth));
- $outputImage = imagescale($newImage, $newWidth, $newHeight);
+ if ($key === 'background') {
+ if ($this->shouldOptimizeBackgroundImage($detectedMimeType, filesize($tmpFile))) {
+ try {
+ // Optimize the image since some people may upload images that will be
+ // either to big or are not progressive rendering.
+ $newImage = @imagecreatefromstring(file_get_contents($tmpFile));
+ if ($newImage === false) {
+ throw new \Exception('Could not read background image, possibly corrupted.');
+ }
+
+ // Preserve transparency
+ imagesavealpha($newImage, true);
+ imagealphablending($newImage, true);
+
+ $imageWidth = imagesx($newImage);
+ $imageHeight = imagesy($newImage);
+
+ /** @var int */
+ $newWidth = min(4096, $imageWidth);
+ $newHeight = intval($imageHeight / ($imageWidth / $newWidth));
+ $outputImage = imagescale($newImage, $newWidth, $newHeight);
+ if ($outputImage === false) {
+ throw new \Exception('Could not scale uploaded background image.');
+ }
+
+ $newTmpFile = $this->tempManager->getTemporaryFile();
+ imageinterlace($outputImage, true);
+ // Keep jpeg images encoded as jpeg
+ if (str_contains($detectedMimeType, 'image/jpeg')) {
+ if (!imagejpeg($outputImage, $newTmpFile, 90)) {
+ throw new \Exception('Could not recompress background image as JPEG');
+ }
+ } else {
+ if (!imagepng($outputImage, $newTmpFile, 8)) {
+ throw new \Exception('Could not recompress background image as PNG');
+ }
+ }
+ $tmpFile = $newTmpFile;
+ imagedestroy($outputImage);
+ } catch (\Exception $e) {
+ if (isset($outputImage) && is_resource($outputImage) || $outputImage instanceof \GdImage) {
+ imagedestroy($outputImage);
+ }
+
+ $this->logger->debug($e->getMessage());
+ }
+ }
- imageinterlace($outputImage, 1);
- imagepng($outputImage, $tmpFile, 8);
- imagedestroy($outputImage);
+ // For background images we need to announce it
+ $this->backgroundService->setGlobalBackground($tmpFile);
+ }
- $target->putContent(file_get_contents($tmpFile));
- } else {
- $target->putContent(file_get_contents($tmpFile));
+ $target->putContent(file_get_contents($tmpFile));
+
+ if ($key === 'logo') {
+ $content = file_get_contents($tmpFile);
+ $newImage = @imagecreatefromstring($content);
+ if ($newImage !== false) {
+ $this->config->setAppValue('theming', 'logoDimensions', imagesx($newImage) . 'x' . imagesy($newImage));
+ } elseif (str_starts_with($detectedMimeType, 'image/svg')) {
+ $matched = preg_match('/viewbox=["\']\d* \d* (\d*\.?\d*) (\d*\.?\d*)["\']/i', $content, $matches);
+ if ($matched) {
+ $this->config->setAppValue('theming', 'logoDimensions', $matches[1] . 'x' . $matches[2]);
+ } else {
+ $this->logger->warning('Could not read logo image dimensions to optimize for mail header');
+ $this->config->deleteAppValue('theming', 'logoDimensions');
+ }
+ } else {
+ $this->logger->warning('Could not read logo image dimensions to optimize for mail header');
+ $this->config->deleteAppValue('theming', 'logoDimensions');
+ }
}
return $detectedMimeType;
}
/**
+ * Decide whether an image benefits from shrinking and reconverting
+ *
+ * @param string $mimeType the mime type of the image
+ * @param int $contentSize size of the image file
+ * @return bool
+ */
+ private function shouldOptimizeBackgroundImage(string $mimeType, int $contentSize): bool {
+ // Do not touch SVGs
+ if (str_contains($mimeType, 'image/svg')) {
+ return false;
+ }
+ // GIF does not benefit from converting
+ if (str_contains($mimeType, 'image/gif')) {
+ return false;
+ }
+ // WebP also does not benefit from converting
+ // We could possibly try to convert to progressive image, but normally webP images are quite small
+ if (str_contains($mimeType, 'image/webp')) {
+ return false;
+ }
+ // As a rule of thumb background images should be max. 150-300 KiB, small images do not benefit from converting
+ return $contentSize > 150000;
+ }
+
+ /**
* Returns a list of supported mime types for image uploads.
* "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
*
* @param string $key The image key, e.g. "favicon"
* @return string[]
*/
- private function getSupportedUploadImageFormats(string $key): array {
+ public function getSupportedUploadImageFormats(string $key): array {
$supportedFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if ($key !== 'favicon' || $this->shouldReplaceIcons() === true) {