Skip to content
Snippets Groups Projects
Commit 3d976ac9 authored by Helmut Hummel's avatar Helmut Hummel Committed by Jigal van Hemert
Browse files

[TASK] Rework image viewHelper to use FAL

Currently in the worst case images are transformed
from Extbase domain objects to FAL objects to paths
to FAL objects again just to render an image.

Avoid back and forth conversions an directly use
FAL API instead of using the detour through
the content object renderer.

Resolves: #53700
Releases: 6.2
Change-Id: I5fe8d7c9d4ad94e99b5bac06e54ff1346e8cc187
Reviewed-on: https://review.typo3.org/24911
Reviewed-by: Markus Klein
Tested-by: Markus Klein
Reviewed-by: Jigal van Hemert
Tested-by: Jigal van Hemert
parent ab0a6fc0
Branches
Tags
No related merge requests found
<?php
namespace TYPO3\CMS\Extbase\Service;
/***************************************************************
* Copyright notice
*
* (c) 2010-2013 Extbase Team (http://forge.typo3.org/projects/typo3v4-mvc)
* Extbase is a backport of TYPO3 Flow. All credits go to the TYPO3 Flow team.
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script 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 General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Utility\MathUtility;
/**
* Service for processing images
*/
class ImageService implements \TYPO3\CMS\Core\SingletonInterface {
/**
* @var \TYPO3\CMS\Core\Resource\ResourceFactory
* @inject
*/
protected $resourceFactory;
/**
* @var \TYPO3\CMS\Extbase\Service\EnvironmentService
* @inject
*/
protected $environmentService;
/**
* Create a processed file
*
* @param File|FileReference $image
* @param array $processingInstructions
* @return ProcessedFile
* @api
*/
public function applyProcessingInstructions($image, $processingInstructions) {
if (is_callable(array($image, 'getOriginalFile'))) {
// Get the original file from the file reference
$image = $image->getOriginalFile();
}
$processedImage = $image->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $processingInstructions);
$this->setCompatibilityValues($processedImage);
return $processedImage;
}
/**
* Get public url of image depending on the environment
*
* @param FileInterface $image
* @return string
* @api
*/
public function getImageUri(FileInterface $image) {
if ($this->environmentService->isEnvironmentInFrontendMode()) {
$uriPrefix = $GLOBALS['TSFE']->absRefPrefix;
} else {
$uriPrefix = '../';
}
return $uriPrefix . $image->getPublicUrl();
}
/**
* Get File or FileReference object
*
* This method is a factory and compatibility method that does not belong to
* this service, but is put here for pragmatic reasons for the time being.
* It should be removed once we do not support string sources for images anymore.
*
* @param string $src
* @param mixed $image
* @param boolean $treatIdAsReference
* @return FileInterface
* @throws \UnexpectedValueException
* @internal
*/
public function getImage($src, $image, $treatIdAsReference) {
if (is_null($image)) {
$image = $this->getImageFromSourceString($src, $treatIdAsReference);
} elseif (is_callable(array($image, 'getOriginalResource'))) {
// We have a domain model, so we need to fetch the FAL resource object from there
$image = $image->getOriginalResource();
}
if (!($image instanceof File || $image instanceof FileReference)) {
throw new \UnexpectedValueException('Supplied file object type ' . get_class($image) . ' must be File or FileReference.', 1382687163);
}
return $image;
}
/**
* Get File or FileReference object by src
*
* @param string $src
* @param boolean $treatIdAsReference
* @return FileInterface|FileReference|\TYPO3\CMS\Core\Resource\Folder
*/
protected function getImageFromSourceString($src, $treatIdAsReference) {
if ($this->environmentService->isEnvironmentInBackendMode() && substr($src, 0, 3) === '../') {
$src = substr($src, 3);
}
if (MathUtility::canBeInterpretedAsInteger($src)) {
if ($treatIdAsReference) {
$image = $this->resourceFactory->getFileReferenceObject($src);
} else {
$image = $this->resourceFactory->getFileObject($src);
}
} else {
// We have a combined identifier or legacy (storage 0) path
$image = $this->resourceFactory->retrieveFileOrFolderObject($src);
}
return $image;
}
/**
* Set compatibility values to frontend controller object
* in case we are in frontend environment.
*
* @param ProcessedFile $processedImage
* @return void
*/
protected function setCompatibilityValues(ProcessedFile $processedImage) {
if ($this->environmentService->isEnvironmentInFrontendMode()) {
$imageInfo = $this->getCompatibilityImageResourceValues($processedImage);
$GLOBALS['TSFE']->lastImageInfo = $imageInfo;
$GLOBALS['TSFE']->imagesOnPage[] = $imageInfo[3];
}
}
/**
* Calculates the compatibility values
* This is duplicate code taken from ContentObjectRenderer::getImgResource()
* Ideally we should get rid of this code in both places.
*
* @param ProcessedFile $processedImage
* @return array
*/
protected function getCompatibilityImageResourceValues(ProcessedFile $processedImage) {
$hash = $processedImage->calculateChecksum();
if (isset($GLOBALS['TSFE']->tmpl->fileCache[$hash])) {
$compatibilityImageResourceValues = $GLOBALS['TSFE']->tmpl->fileCache[$hash];
} else {
$compatibilityImageResourceValues = array(
0 => $processedImage->getProperty('width'),
1 => $processedImage->getProperty('height'),
2 => $processedImage->getExtension(),
3 => $processedImage->getPublicUrl(),
'origFile' => $processedImage->getOriginalFile()->getPublicUrl(),
'origFile_mtime' => $processedImage->getOriginalFile()->getModificationTime(),
// This is needed by \TYPO3\CMS\Frontend\Imaging\GifBuilder,
// in order for the setup-array to create a unique filename hash.
'originalFile' => $processedImage->getOriginalFile(),
'processedFile' => $processedImage,
'fileCacheHash' => $hash
);
}
return $compatibilityImageResourceValues;
}
}
......@@ -13,6 +13,10 @@ namespace TYPO3\CMS\Fluid\ViewHelpers;
* TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
* Public License for more details. *
* */
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
/**
* Resizes a given image (if required) and renders the respective img tag
*
......@@ -27,6 +31,13 @@ namespace TYPO3\CMS\Fluid\ViewHelpers;
* <img alt="alt text" src="../typo3conf/ext/viewhelpertest/Resources/Public/typo3_logo.png" width="396" height="375" />
* </output>
*
* <code title="Image Object">
* <f:image image="{imageObject}" />
* </code>
* <output>
* <img alt="alt set in image record" src="fileadmin/_processed_/323223424.png" width="396" height="375" />
* </output>
*
* <code title="Inline notation">
* {f:image(src: 'EXT:viewhelpertest/Resources/Public/typo3_logo.png', alt: 'alt text', minWidth: 30, maxWidth: 40)}
* </code>
......@@ -43,41 +54,16 @@ namespace TYPO3\CMS\Fluid\ViewHelpers;
* </output>
*/
class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper {
/**
* @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
*/
protected $contentObject;
/**
* @var string
*/
protected $tagName = 'img';
/**
* @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController contains a backup of the current $GLOBALS['TSFE'] if used in BE mode
*/
protected $tsfeBackup;
/**
* @var string
*/
protected $workingDirectoryBackup;
/**
* @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
*/
protected $configurationManager;
/**
* @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
*
* @return void
* @var \TYPO3\CMS\Extbase\Service\ImageService
* @inject
*/
public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager) {
$this->configurationManager = $configurationManager;
$this->contentObject = $this->configurationManager->getContentObject();
}
protected $imageService;
/**
* Initialize arguments.
......@@ -87,7 +73,7 @@ class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractTagBasedV
public function initializeArguments() {
parent::initializeArguments();
$this->registerUniversalTagAttributes();
$this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', TRUE);
$this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', FALSE);
$this->registerTagAttribute('ismap', 'string', 'Specifies an image as a server-side image-map. Rarely used. Look at usemap instead', FALSE);
$this->registerTagAttribute('longdesc', 'string', 'Specifies the URL to a document that contains a long description of an image', FALSE);
$this->registerTagAttribute('usemap', 'string', 'Specifies an image as a client-side image-map', FALSE);
......@@ -97,8 +83,8 @@ class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractTagBasedV
* Resizes a given image (if required) and renders the respective img tag
*
* @see http://typo3.org/documentation/document-library/references/doc_core_tsref/4.2.0/view/1/5/#id4164427
*
* @param string $src
* @param FileInterface|AbstractFileFolder $image
* @param string $width width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* @param string $height height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* @param integer $minWidth minimum width of the image
......@@ -108,79 +94,39 @@ class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractTagBasedV
* @param boolean $treatIdAsReference given src argument is a sys_file_reference record
*
* @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
* @return string rendered tag.
* @return string Rendered tag
*/
public function render($src, $width = NULL, $height = NULL, $minWidth = NULL, $minHeight = NULL, $maxWidth = NULL, $maxHeight = NULL, $treatIdAsReference = FALSE) {
if (TYPO3_MODE === 'BE') {
$this->simulateFrontendEnvironment();
public function render($src = NULL, $image = NULL, $width = NULL, $height = NULL, $minWidth = NULL, $minHeight = NULL, $maxWidth = NULL, $maxHeight = NULL, $treatIdAsReference = FALSE) {
if (is_null($src) && is_null($image) || !is_null($src) && !is_null($image)) {
throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('You must either specify a string src or a File object.', 1382284105);
}
$setup = array(
$image = $this->imageService->getImage($src, $image, $treatIdAsReference);
$processingInstructions = array(
'width' => $width,
'height' => $height,
'minW' => $minWidth,
'minH' => $minHeight,
'maxW' => $maxWidth,
'maxH' => $maxHeight,
'treatIdAsReference' => $treatIdAsReference
'minWidth' => $minWidth,
'minHeight' => $minHeight,
'maxWidth' => $maxWidth,
'maxHeight' => $maxHeight,
);
if (TYPO3_MODE === 'BE' && substr($src, 0, 3) === '../') {
$src = substr($src, 3);
}
$imageInfo = $this->contentObject->getImgResource($src, $setup);
$GLOBALS['TSFE']->lastImageInfo = $imageInfo;
if (!is_array($imageInfo)) {
if (TYPO3_MODE === 'BE') {
$this->resetFrontendEnvironment();
}
throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('Could not get image resource for "' . htmlspecialchars($src) . '".', 1253191060);
}
$imageInfo[3] = \TYPO3\CMS\Core\Utility\GeneralUtility::png_to_gif_by_imagemagick($imageInfo[3]);
$GLOBALS['TSFE']->imagesOnPage[] = $imageInfo[3];
$imageSource = $GLOBALS['TSFE']->absRefPrefix . \TYPO3\CMS\Core\Utility\GeneralUtility::rawUrlEncodeFP($imageInfo[3]);
if (TYPO3_MODE === 'BE') {
$imageSource = '../' . $imageSource;
$this->resetFrontendEnvironment();
}
$this->tag->addAttribute('src', $imageSource);
$this->tag->addAttribute('width', $imageInfo[0]);
$this->tag->addAttribute('height', $imageInfo[1]);
//the alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
$processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
$imageUri = $this->imageService->getImageUri($processedImage);
$this->tag->addAttribute('src', $imageUri);
$this->tag->addAttribute('width', $processedImage->getProperty('width'));
$this->tag->addAttribute('height', $processedImage->getProperty('height'));
$alt = $image->getProperty('alternative');
$title = $image->getProperty('title');
// The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
if (empty($this->arguments['alt'])) {
$this->tag->addAttribute('alt', '');
$this->tag->addAttribute('alt', $alt);
}
if (empty($this->arguments['title']) && $title) {
$this->tag->addAttribute('title', $title);
}
return $this->tag->render();
}
/**
* Prepares $GLOBALS['TSFE'] for Backend mode
* This somewhat hacky work around is currently needed because the getImgResource() function of \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer relies on those variables to be set
*
* @return void
*/
protected function simulateFrontendEnvironment() {
$this->tsfeBackup = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE'] : NULL;
// set the working directory to the site root
$this->workingDirectoryBackup = getcwd();
chdir(PATH_site);
$typoScriptSetup = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
$GLOBALS['TSFE'] = new \stdClass();
$template = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\TemplateService');
$template->tt_track = 0;
$template->init();
$template->getFileName_backPath = PATH_site;
$GLOBALS['TSFE']->tmpl = $template;
$GLOBALS['TSFE']->tmpl->setup = $typoScriptSetup;
$GLOBALS['TSFE']->config = $typoScriptSetup;
}
/**
* Resets $GLOBALS['TSFE'] if it was previously changed by simulateFrontendEnvironment()
*
* @return void
* @see simulateFrontendEnvironment()
*/
protected function resetFrontendEnvironment() {
$GLOBALS['TSFE'] = $this->tsfeBackup;
chdir($this->workingDirectoryBackup);
return $this->tag->render();
}
}
......@@ -13,6 +13,10 @@ namespace TYPO3\CMS\Fluid\ViewHelpers\Uri;
* TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
* Public License for more details. *
* */
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
/**
* Resizes a given image (if required) and returns its relative path.
*
......@@ -27,6 +31,15 @@ namespace TYPO3\CMS\Fluid\ViewHelpers\Uri;
* ../typo3conf/ext/myext/Resources/Public/typo3_logo.png
* </output>
*
* <code title="Image Object">
* <f:uri.image image="{imageObject}" />
* </code>
* <output>
* fileadmin/images/image.png
* or (in BE mode):
* fileadmin/images/image.png
* </output>
*
* <code title="Inline notation">
* {f:uri.image(src: 'EXT:myext/Resources/Public/typo3_logo.png' minWidth: 30, maxWidth: 40)}
* </code>
......@@ -43,43 +56,18 @@ namespace TYPO3\CMS\Fluid\ViewHelpers\Uri;
* </output>
*/
class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
*/
protected $contentObject;
/**
* @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
*/
protected $configurationManager;
/**
* Contains a backup of the current $GLOBALS['TSFE'] if used in BE mode
*
* @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
*/
protected $tsfeBackup;
/**
* @var string
* @var \TYPO3\CMS\Extbase\Service\ImageService
* @inject
*/
protected $workingDirectoryBackup;
/**
* @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
* @return void
*/
public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager) {
$this->configurationManager = $configurationManager;
$this->contentObject = $this->configurationManager->getContentObject();
}
protected $imageService;
/**
* Resizes the image (if required) and returns its path. If the image was not resized, the path will be equal to $src
*
* @see http://typo3.org/documentation/document-library/references/doc_core_tsref/4.2.0/view/1/5/#id4164427
* @param string $src
* @param FileInterface|AbstractFileFolder $image
* @param string $width width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* @param string $height height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* @param integer $minWidth minimum width of the image
......@@ -90,67 +78,20 @@ class ImageViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelpe
* @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
* @return string path to the image
*/
public function render($src, $width = NULL, $height = NULL, $minWidth = NULL, $minHeight = NULL, $maxWidth = NULL, $maxHeight = NULL, $treatIdAsReference = FALSE) {
if (TYPO3_MODE === 'BE') {
$this->simulateFrontendEnvironment();
public function render($src = NULL, $image = NULL, $width = NULL, $height = NULL, $minWidth = NULL, $minHeight = NULL, $maxWidth = NULL, $maxHeight = NULL, $treatIdAsReference = FALSE) {
if (is_null($src) && is_null($image) || !is_null($src) && !is_null($image)) {
throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('You must either specify a string src or a File object.', 1382284105);
}
$setup = array(
$image = $this->imageService->getImage($src, $image, $treatIdAsReference);
$processingInstructions = array(
'width' => $width,
'height' => $height,
'minW' => $minWidth,
'minH' => $minHeight,
'maxW' => $maxWidth,
'maxH' => $maxHeight,
'treatIdAsReference' => $treatIdAsReference
'minWidth' => $minWidth,
'minHeight' => $minHeight,
'maxWidth' => $maxWidth,
'maxHeight' => $maxHeight,
);
if (TYPO3_MODE === 'BE' && substr($src, 0, 3) === '../') {
$src = substr($src, 3);
}
$imageInfo = $this->contentObject->getImgResource($src, $setup);
$GLOBALS['TSFE']->lastImageInfo = $imageInfo;
if (!is_array($imageInfo)) {
throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('Could not get image resource for "' . htmlspecialchars($src) . '".', 1277367645);
}
$imageInfo[3] = \TYPO3\CMS\Core\Utility\GeneralUtility::png_to_gif_by_imagemagick($imageInfo[3]);
$GLOBALS['TSFE']->imagesOnPage[] = $imageInfo[3];
$imageSource = $GLOBALS['TSFE']->absRefPrefix . \TYPO3\CMS\Core\Utility\GeneralUtility::rawUrlEncodeFP($imageInfo[3]);
if (TYPO3_MODE === 'BE') {
$imageSource = '../' . $imageSource;
$this->resetFrontendEnvironment();
}
return $imageSource;
}
/**
* Prepares $GLOBALS['TSFE'] for Backend mode
* This somewhat hacky work around is currently needed because the getImgResource() function of \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer relies on those variables to be set
*
* @return void
*/
protected function simulateFrontendEnvironment() {
$this->tsfeBackup = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE'] : NULL;
// Set the working directory to the site root
$this->workingDirectoryBackup = getcwd();
chdir(PATH_site);
$typoScriptSetup = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
$GLOBALS['TSFE'] = new \stdClass();
$template = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\TemplateService');
$template->tt_track = 0;
$template->init();
$template->getFileName_backPath = PATH_site;
$GLOBALS['TSFE']->tmpl = $template;
$GLOBALS['TSFE']->tmpl->setup = $typoScriptSetup;
$GLOBALS['TSFE']->config = $typoScriptSetup;
}
/**
* Resets $GLOBALS['TSFE'] if it was previously changed by simulateFrontendEnvironment()
*
* @return void
* @see simulateFrontendEnvironment()
*/
protected function resetFrontendEnvironment() {
$GLOBALS['TSFE'] = $this->tsfeBackup;
chdir($this->workingDirectoryBackup);
$processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
return $this->imageService->getImageUri($processedImage);
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment