ImageViewHelper::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Fluid\ViewHelpers;
17
18
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
19
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use TYPO3\CMS\Extbase\Service\ImageService;
22
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
23
use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
24
25
/**
26
 * Resizes a given image (if required) and renders the respective img tag.
27
 *
28
 * External URLs are not processed. Only a given width and height will be set on the tag.
29
 *
30
 * Examples
31
 * ========
32
 *
33
 * Default
34
 * -------
35
 *
36
 * ::
37
 *
38
 *    <f:image src="EXT:myext/Resources/Public/typo3_logo.png" alt="alt text" />
39
 *
40
 * Output in frontend::
41
 *
42
 *    <img alt="alt text" src="typo3conf/ext/myext/Resources/Public/typo3_logo.png" width="396" height="375" />
43
 *
44
 * or in backend::
45
 *
46
 *    <img alt="alt text" src="../typo3conf/ext/viewhelpertest/Resources/Public/typo3_logo.png" width="396" height="375" />
47
 *
48
 * Image Object
49
 * ------------
50
 *
51
 * ::
52
 *
53
 *    <f:image image="{imageObject}" />
54
 *
55
 * Output::
56
 *
57
 *    <img alt="alt set in image record" src="fileadmin/_processed_/323223424.png" width="396" height="375" />
58
 *
59
 * Inline notation
60
 * ---------------
61
 *
62
 * ::
63
 *
64
 *    {f:image(src: 'EXT:viewhelpertest/Resources/Public/typo3_logo.png', alt: 'alt text', minWidth: 30, maxWidth: 40)}
65
 *
66
 * Output::
67
 *
68
 *    <img alt="alt text" src="../typo3temp/assets/images/f13d79a526.png" width="40" height="38" />
69
 *
70
 * Depending on your TYPO3s encryption key.
71
 *
72
 * Other resource type (e.g. PDF)
73
 * ------------------------------
74
 *
75
 * ::
76
 *
77
 *    <f:image src="fileadmin/user_upload/example.pdf" alt="foo" />
78
 *
79
 * If your graphics processing library is set up correctly then it will output a thumbnail of the first page of your PDF document:
80
 * ``<img src="fileadmin/_processed_/1/2/csm_example_aabbcc112233.gif" width="200" height="284" alt="foo">``
81
 *
82
 * Non-existent image
83
 * ------------------
84
 *
85
 * ::
86
 *
87
 *    <f:image src="NonExistingImage.png" alt="foo" />
88
 *
89
 * ``Could not get image resource for "NonExistingImage.png".``
90
 */
91
class ImageViewHelper extends AbstractTagBasedViewHelper
92
{
93
    /**
94
     * @var string
95
     */
96
    protected $tagName = 'img';
97
98
    protected ImageService $imageService;
99
100
    public function __construct()
101
    {
102
        parent::__construct();
103
        $this->imageService = GeneralUtility::makeInstance(ImageService::class);
104
    }
105
106
    /**
107
     * Initialize arguments.
108
     */
109
    public function initializeArguments()
110
    {
111
        parent::initializeArguments();
112
        $this->registerUniversalTagAttributes();
113
        $this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', false);
114
        $this->registerTagAttribute('ismap', 'string', 'Specifies an image as a server-side image-map. Rarely used. Look at usemap instead', false);
115
        $this->registerTagAttribute('longdesc', 'string', 'Specifies the URL to a document that contains a long description of an image', false);
116
        $this->registerTagAttribute('usemap', 'string', 'Specifies an image as a client-side image-map', false);
117
        $this->registerTagAttribute('loading', 'string', 'Native lazy-loading for images property. Can be "lazy", "eager" or "auto"', false);
118
        $this->registerTagAttribute('decoding', 'string', 'Provides an image decoding hint to the browser. Can be "sync", "async" or "auto"', false);
119
120
        $this->registerArgument('src', 'string', 'a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead', false, '');
121
        $this->registerArgument('treatIdAsReference', 'bool', 'given src argument is a sys_file_reference record', false, false);
122
        $this->registerArgument('image', 'object', 'a FAL object (\\TYPO3\\CMS\\Core\\Resource\\File or \\TYPO3\\CMS\\Core\\Resource\\FileReference)');
123
        $this->registerArgument('crop', 'string|bool', 'overrule cropping of image (setting to FALSE disables the cropping set in FileReference)');
124
        $this->registerArgument('cropVariant', 'string', 'select a cropping variant, in case multiple croppings have been specified or stored in FileReference', false, 'default');
125
        $this->registerArgument('fileExtension', 'string', 'Custom file extension to use');
126
127
        $this->registerArgument('width', 'string', '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.');
128
        $this->registerArgument('height', 'string', '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.');
129
        $this->registerArgument('minWidth', 'int', 'minimum width of the image');
130
        $this->registerArgument('minHeight', 'int', 'minimum height of the image');
131
        $this->registerArgument('maxWidth', 'int', 'maximum width of the image');
132
        $this->registerArgument('maxHeight', 'int', 'maximum height of the image');
133
        $this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
134
    }
135
136
    /**
137
     * Resizes a given image (if required) and renders the respective img tag
138
     *
139
     * @see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
140
     *
141
     * @throws Exception
142
     * @return string Rendered tag
143
     */
144
    public function render()
145
    {
146
        $src = (string)$this->arguments['src'];
147
        if (($src === '' && $this->arguments['image'] === null) || ($src !== '' && $this->arguments['image'] !== null)) {
148
            throw new Exception('You must either specify a string src or a File object.', 1382284106);
149
        }
150
151
        if ((string)$this->arguments['fileExtension'] && !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], (string)$this->arguments['fileExtension'])) {
152
            throw new Exception('The extension ' . $this->arguments['fileExtension'] . ' is not specified in $GLOBALS[\'TYPO3_CONF_VARS\'][\'GFX\'][\'imagefile_ext\'] as a valid image file extension and can not be processed.', 1618989190);
153
        }
154
155
        try {
156
            $image = $this->imageService->getImage($src, $this->arguments['image'], (bool)$this->arguments['treatIdAsReference']);
157
            $cropString = $this->arguments['crop'];
158
            if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) {
159
                $cropString = $image->getProperty('crop');
160
            }
161
            $cropVariantCollection = CropVariantCollection::create((string)$cropString);
162
            $cropVariant = $this->arguments['cropVariant'] ?: 'default';
163
            $cropArea = $cropVariantCollection->getCropArea($cropVariant);
164
            $processingInstructions = [
165
                'width' => $this->arguments['width'],
166
                'height' => $this->arguments['height'],
167
                'minWidth' => $this->arguments['minWidth'],
168
                'minHeight' => $this->arguments['minHeight'],
169
                'maxWidth' => $this->arguments['maxWidth'],
170
                'maxHeight' => $this->arguments['maxHeight'],
171
                'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image),
172
            ];
173
            if (!empty($this->arguments['fileExtension'] ?? '')) {
174
                $processingInstructions['fileExtension'] = $this->arguments['fileExtension'];
175
            }
176
            $processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
177
            $imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);
178
179
            if (!$this->tag->hasAttribute('data-focus-area')) {
180
                $focusArea = $cropVariantCollection->getFocusArea($cropVariant);
181
                if (!$focusArea->isEmpty()) {
182
                    $this->tag->addAttribute('data-focus-area', $focusArea->makeAbsoluteBasedOnFile($image));
183
                }
184
            }
185
            $this->tag->addAttribute('src', $imageUri);
186
            $this->tag->addAttribute('width', $processedImage->getProperty('width'));
187
            $this->tag->addAttribute('height', $processedImage->getProperty('height'));
188
189
            // The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
190
            if (empty($this->arguments['alt'])) {
191
                $this->tag->addAttribute('alt', $image->hasProperty('alternative') ? $image->getProperty('alternative') : '');
192
            }
193
            // Add title-attribute from property if not already set and the property is not an empty string
194
            $title = (string)($image->hasProperty('title') ? $image->getProperty('title') : '');
195
            if (empty($this->arguments['title']) && $title !== '') {
196
                $this->tag->addAttribute('title', $title);
197
            }
198
        } catch (ResourceDoesNotExistException $e) {
199
            // thrown if file does not exist
200
            throw new Exception($e->getMessage(), 1509741911, $e);
201
        } catch (\UnexpectedValueException $e) {
202
            // thrown if a file has been replaced with a folder
203
            throw new Exception($e->getMessage(), 1509741912, $e);
204
        } catch (\RuntimeException $e) {
205
            // RuntimeException thrown if a file is outside of a storage
206
            throw new Exception($e->getMessage(), 1509741913, $e);
207
        } catch (\InvalidArgumentException $e) {
208
            // thrown if file storage does not exist
209
            throw new Exception($e->getMessage(), 1509741914, $e);
210
        }
211
        return $this->tag->render();
212
    }
213
}
214