4689d1ed82a5180f324a41312272069f257f5428
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Imaging / GifBuilder.php
1 <?php
2 namespace TYPO3\CMS\Frontend\Imaging;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19 /**
20 * GIFBUILDER
21 *
22 * Generating gif/png-files from TypoScript
23 * Used by the menu-objects and imgResource in TypoScript.
24 *
25 * This class allows for advanced rendering of images with various layers of images, text and graphical primitives.
26 * The concept is known from TypoScript as "GIFBUILDER" where you can define a "numerical array" (TypoScript term as well) of "GIFBUILDER OBJECTS" (like "TEXT", "IMAGE", etc.) and they will be rendered onto an image one by one.
27 * The name "GIFBUILDER" comes from the time where GIF was the only file format supported. PNG is just as well to create today (configured with TYPO3_CONF_VARS[GFX])
28 * Not all instances of this class is truely building gif/png files by layers; You may also see the class instantiated for the purpose of using the scaling functions in the parent class.
29 *
30 * Here is an example of how to use this class (from tslib_content.php, function getImgResource):
31 *
32 * $gifCreator = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class);
33 * $gifCreator->init();
34 * $theImage='';
35 * if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib']) {
36 * $gifCreator->start($fileArray, $this->data);
37 * $theImage = $gifCreator->gifBuild();
38 * }
39 * return $gifCreator->getImageDimensions($theImage);
40 *
41 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
42 */
43 class GifBuilder extends \TYPO3\CMS\Core\Imaging\GraphicalFunctions {
44
45 /**
46 * the main image
47 *
48 * @var string
49 */
50 public $im = '';
51
52 /**
53 * the image-width
54 *
55 * @var int
56 */
57 public $w = 0;
58
59 /**
60 * the image-height
61 *
62 * @var int
63 */
64 public $h = 0;
65
66 /**
67 * map-data
68 *
69 * @var string
70 */
71 public $map;
72
73 /**
74 * @var array
75 */
76 public $workArea;
77
78 /**
79 * This holds the operational setup for gifbuilder. Basically this is a TypoScript array with properties.
80 *
81 * @var array
82 */
83 public $setup = array();
84
85 /**
86 * Contains all text strings used on this image
87 *
88 * @var array
89 */
90 public $combinedTextStrings = array();
91
92 /**
93 * Contains all filenames (basename without extension) used on this image
94 *
95 * @var array
96 */
97 public $combinedFileNames = array();
98
99 /**
100 * This is the array from which data->field: [key] is fetched. So this is the current record!
101 *
102 * @var array
103 */
104 public $data = array();
105
106 /**
107 * @var array
108 */
109 public $objBB = array();
110
111 /**
112 * @var string
113 */
114 public $myClassName = 'gifbuilder';
115
116 /**
117 * @var array
118 */
119 public $charRangeMap = array();
120
121 /**
122 * @var int[]
123 */
124 public $XY = array();
125
126 /**
127 * Initialization of the GIFBUILDER objects, in particular TEXT and IMAGE. This includes finding the bounding box, setting dimensions and offset values before the actual rendering is started.
128 * Modifies the ->setup, ->objBB internal arrays
129 * Should be called after the ->init() function which initializes the parent class functions/variables in general.
130 * The class \TYPO3\CMS\Frontend\ContentObject\Menu\GraphicalMenuContentObject also uses gifbuilder and here there is an interesting use since the function findLargestDims() from that class calls the init() and start() functions to find the total dimensions before starting the rendering of the images.
131 *
132 * @param array $conf TypoScript properties for the GIFBUILDER session. Stored internally in the variable ->setup
133 * @param array $data The current data record from \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer. Stored internally in the variable ->data
134 * @return void
135 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource(), \TYPO3\CMS\Frontend\ContentObject\Menu\GraphicalMenuContentObject::makeGifs(), \TYPO3\CMS\Frontend\ContentObject\Menu\GraphicalMenuContentObject::findLargestDims()
136 */
137 public function start($conf, $data) {
138 if (is_array($conf)) {
139 $this->setup = $conf;
140 $this->data = $data;
141 $this->cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
142 $this->cObj->start($this->data);
143 // Hook preprocess gifbuilder conf
144 // Added by Julle for 3.8.0
145 //
146 // Let's you pre-process the gifbuilder configuration. for
147 // example you can split a string up into lines and render each
148 // line as TEXT obj, see extension julle_gifbconf
149 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_gifbuilder.php']['gifbuilder-ConfPreProcess'])) {
150 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_gifbuilder.php']['gifbuilder-ConfPreProcess'] as $_funcRef) {
151 $_params = $this->setup;
152 $this->setup = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
153 }
154 }
155 // Initializing global Char Range Map
156 $this->charRangeMap = array();
157 if (is_array($GLOBALS['TSFE']->tmpl->setup['_GIFBUILDER.']['charRangeMap.'])) {
158 foreach ($GLOBALS['TSFE']->tmpl->setup['_GIFBUILDER.']['charRangeMap.'] as $cRMcfgkey => $cRMcfg) {
159 if (is_array($cRMcfg)) {
160 // Initializing:
161 $cRMkey = $GLOBALS['TSFE']->tmpl->setup['_GIFBUILDER.']['charRangeMap.'][substr($cRMcfgkey, 0, -1)];
162 $this->charRangeMap[$cRMkey] = array();
163 $this->charRangeMap[$cRMkey]['charMapConfig'] = $cRMcfg['charMapConfig.'];
164 $this->charRangeMap[$cRMkey]['cfgKey'] = substr($cRMcfgkey, 0, -1);
165 $this->charRangeMap[$cRMkey]['multiplicator'] = (double) $cRMcfg['fontSizeMultiplicator'];
166 $this->charRangeMap[$cRMkey]['pixelSpace'] = (int)$cRMcfg['pixelSpaceFontSizeRef'];
167 }
168 }
169 }
170 // Getting sorted list of TypoScript keys from setup.
171 $sKeyArray = \TYPO3\CMS\Core\TypoScript\TemplateService::sortedKeyList($this->setup);
172 // Setting the background color, passing it through stdWrap
173 if ($conf['backColor.'] || $conf['backColor']) {
174 $this->setup['backColor'] = isset($this->setup['backColor.']) ? trim($this->cObj->stdWrap($this->setup['backColor'], $this->setup['backColor.'])) : $this->setup['backColor'];
175 }
176 if (!$this->setup['backColor']) {
177 $this->setup['backColor'] = 'white';
178 }
179 if ($conf['transparentColor.'] || $conf['transparentColor']) {
180 $this->setup['transparentColor_array'] = isset($this->setup['transparentColor.']) ? explode('|', trim($this->cObj->stdWrap($this->setup['transparentColor'], $this->setup['transparentColor.']))) : explode('|', trim($this->setup['transparentColor']));
181 }
182 if (isset($this->setup['transparentBackground.'])) {
183 $this->setup['transparentBackground'] = $this->cObj->stdWrap($this->setup['transparentBackground'], $this->setup['transparentBackground.']);
184 }
185 if (isset($this->setup['reduceColors.'])) {
186 $this->setup['reduceColors'] = $this->cObj->stdWrap($this->setup['reduceColors'], $this->setup['reduceColors.']);
187 }
188 // Set default dimensions
189 if (isset($this->setup['XY.'])) {
190 $this->setup['XY'] = $this->cObj->stdWrap($this->setup['XY'], $this->setup['XY.']);
191 }
192 if (!$this->setup['XY']) {
193 $this->setup['XY'] = '120,50';
194 }
195 // Checking TEXT and IMAGE objects for files. If any errors the objects are cleared.
196 // The Bounding Box for the objects is stored in an array
197 foreach ($sKeyArray as $theKey) {
198 $theValue = $this->setup[$theKey];
199 if ((int)$theKey && ($conf = $this->setup[$theKey . '.'])) {
200 // Swipes through TEXT and IMAGE-objects
201 switch ($theValue) {
202 case 'TEXT':
203 if ($this->setup[$theKey . '.'] = $this->checkTextObj($conf)) {
204 // Adjust font width if max size is set:
205 $maxWidth = isset($this->setup[$theKey . '.']['maxWidth.']) ? $this->cObj->stdWrap($this->setup[$theKey . '.']['maxWidth'], $this->setup[$theKey . '.']['maxWidth.']) : $this->setup[$theKey . '.']['maxWidth'];
206 if ($maxWidth) {
207 $this->setup[$theKey . '.']['fontSize'] = $this->fontResize($this->setup[$theKey . '.']);
208 }
209 // Calculate bounding box:
210 $txtInfo = $this->calcBBox($this->setup[$theKey . '.']);
211 $this->setup[$theKey . '.']['BBOX'] = $txtInfo;
212 $this->objBB[$theKey] = $txtInfo;
213 $this->setup[$theKey . '.']['imgMap'] = 0;
214 }
215 break;
216 case 'IMAGE':
217 $fileInfo = $this->getResource($conf['file'], $conf['file.']);
218 if ($fileInfo) {
219 $this->combinedFileNames[] = preg_replace('/\\.[[:alnum:]]+$/', '', basename($fileInfo[3]));
220 if ($fileInfo['originalFile'] instanceof \TYPO3\CMS\Core\Resource\File) {
221 $this->setup[$theKey . '.']['file'] = $fileInfo['originalFile']->getForLocalProcessing(FALSE);
222 } else {
223 $this->setup[$theKey . '.']['file'] = $fileInfo[3];
224 }
225 $this->setup[$theKey . '.']['BBOX'] = $fileInfo;
226 $this->objBB[$theKey] = $fileInfo;
227 if ($conf['mask']) {
228 $maskInfo = $this->getResource($conf['mask'], $conf['mask.']);
229 if ($maskInfo) {
230 if ($maskInfo['originalFile'] instanceof \TYPO3\CMS\Core\Resource\File) {
231 $this->setup[$theKey . '.']['mask'] = $maskInfo['originalFile']->getForLocalProcessing(FALSE);
232 } else {
233 $this->setup[$theKey . '.']['mask'] = $maskInfo[3];
234 }
235 } else {
236 $this->setup[$theKey . '.']['mask'] = '';
237 }
238 }
239 } else {
240 unset($this->setup[$theKey . '.']);
241 }
242 break;
243 }
244 // Checks if disabled is set... (this is also done in menu.php / imgmenu!!)
245 if ($conf['if.']) {
246 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
247 $cObj->start($this->data);
248 if (!$cObj->checkIf($conf['if.'])) {
249 unset($this->setup[$theKey]);
250 unset($this->setup[$theKey . '.']);
251 unset($this->objBB[$theKey]);
252 }
253 }
254 }
255 }
256 // Calculate offsets on elements
257 $this->setup['XY'] = $this->calcOffset($this->setup['XY']);
258 if (isset($this->setup['offset.'])) {
259 $this->setup['offset'] = $this->cObj->stdWrap($this->setup['offset'], $this->setup['offset.']);
260 }
261 $this->setup['offset'] = $this->calcOffset($this->setup['offset']);
262 if (isset($this->setup['workArea.'])) {
263 $this->setup['workArea'] = $this->cObj->stdWrap($this->setup['workArea'], $this->setup['workArea.']);
264 }
265 $this->setup['workArea'] = $this->calcOffset($this->setup['workArea']);
266 foreach ($sKeyArray as $theKey) {
267 $theValue = $this->setup[$theKey];
268 if ((int)$theKey && ($conf = $this->setup[$theKey . '.'])) {
269 switch ($theValue) {
270 case 'TEXT':
271
272 case 'IMAGE':
273 if (isset($this->setup[$theKey . '.']['offset.'])) {
274 $this->setup[$theKey . '.']['offset'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['offset'], $this->setup[$theKey . '.']['offset.']);
275 }
276 if ($this->setup[$theKey . '.']['offset']) {
277 $this->setup[$theKey . '.']['offset'] = $this->calcOffset($this->setup[$theKey . '.']['offset']);
278 }
279 break;
280 case 'BOX':
281
282 case 'ELLIPSE':
283 if (isset($this->setup[$theKey . '.']['dimensions.'])) {
284 $this->setup[$theKey . '.']['dimensions'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['dimensions'], $this->setup[$theKey . '.']['dimensions.']);
285 }
286 if ($this->setup[$theKey . '.']['dimensions']) {
287 $this->setup[$theKey . '.']['dimensions'] = $this->calcOffset($this->setup[$theKey . '.']['dimensions']);
288 }
289 break;
290 case 'WORKAREA':
291 if (isset($this->setup[$theKey . '.']['set.'])) {
292 $this->setup[$theKey . '.']['set'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['set'], $this->setup[$theKey . '.']['set.']);
293 }
294 if ($this->setup[$theKey . '.']['set']) {
295 $this->setup[$theKey . '.']['set'] = $this->calcOffset($this->setup[$theKey . '.']['set']);
296 }
297 break;
298 case 'CROP':
299 if (isset($this->setup[$theKey . '.']['crop.'])) {
300 $this->setup[$theKey . '.']['crop'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['crop'], $this->setup[$theKey . '.']['crop.']);
301 }
302 if ($this->setup[$theKey . '.']['crop']) {
303 $this->setup[$theKey . '.']['crop'] = $this->calcOffset($this->setup[$theKey . '.']['crop']);
304 }
305 break;
306 case 'SCALE':
307 if (isset($this->setup[$theKey . '.']['width.'])) {
308 $this->setup[$theKey . '.']['width'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['width'], $this->setup[$theKey . '.']['width.']);
309 }
310 if ($this->setup[$theKey . '.']['width']) {
311 $this->setup[$theKey . '.']['width'] = $this->calcOffset($this->setup[$theKey . '.']['width']);
312 }
313 if (isset($this->setup[$theKey . '.']['height.'])) {
314 $this->setup[$theKey . '.']['height'] = $this->cObj->stdWrap($this->setup[$theKey . '.']['height'], $this->setup[$theKey . '.']['height.']);
315 }
316 if ($this->setup[$theKey . '.']['height']) {
317 $this->setup[$theKey . '.']['height'] = $this->calcOffset($this->setup[$theKey . '.']['height']);
318 }
319 break;
320 }
321 }
322 }
323 // Get trivial data
324 $XY = GeneralUtility::intExplode(',', $this->setup['XY']);
325 $maxWidth = isset($this->setup['maxWidth.']) ? (int)$this->cObj->stdWrap($this->setup['maxWidth'], $this->setup['maxWidth.']) : (int)$this->setup['maxWidth'];
326 $maxHeight = isset($this->setup['maxHeight.']) ? (int)$this->cObj->stdWrap($this->setup['maxHeight'], $this->setup['maxHeight.']) : (int)$this->setup['maxHeight'];
327 $XY[0] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($XY[0], 1, $maxWidth ?: 2000);
328 $XY[1] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($XY[1], 1, $maxHeight ?: 2000);
329 $this->XY = $XY;
330 $this->w = $XY[0];
331 $this->h = $XY[1];
332 $this->OFFSET = GeneralUtility::intExplode(',', $this->setup['offset']);
333 // this sets the workArea
334 $this->setWorkArea($this->setup['workArea']);
335 // this sets the default to the current;
336 $this->defaultWorkArea = $this->workArea;
337 }
338 }
339
340 /**
341 * Initiates the image file generation if ->setup is TRUE and if the file did not exist already.
342 * Gets filename from fileName() and if file exists in typo3temp/ dir it will - of course - not be rendered again.
343 * Otherwise rendering means calling ->make(), then ->output(), then ->destroy()
344 *
345 * @return string The filename for the created GIF/PNG file. The filename will be prefixed "GB_
346 * @see make(), fileName()
347 */
348 public function gifBuild() {
349 if ($this->setup) {
350 // Relative to PATH_site
351 $gifFileName = $this->fileName('GB/');
352 // File exists
353 if (!file_exists($gifFileName)) {
354 // Create temporary directory if not done:
355 $this->createTempSubDir('GB/');
356 // Create file:
357 $this->make();
358 $this->output($gifFileName);
359 $this->destroy();
360 }
361 return $gifFileName;
362 }
363 }
364
365 /**
366 * The actual rendering of the image file.
367 * Basically sets the dimensions, the background color, the traverses the array of GIFBUILDER objects and finally setting the transparent color if defined.
368 * Creates a GDlib resource in $this->im and works on that
369 * Called by gifBuild()
370 *
371 * @return void
372 * @access private
373 * @see gifBuild()
374 */
375 public function make() {
376 // Get trivial data
377 $XY = $this->XY;
378 // Reset internal properties
379 $this->saveAlphaLayer = FALSE;
380 // Gif-start
381 $this->im = imagecreatetruecolor($XY[0], $XY[1]);
382 $this->w = $XY[0];
383 $this->h = $XY[1];
384 // Transparent layer as background if set and requirements are met
385 if (!empty($this->setup['backColor']) && $this->setup['backColor'] === 'transparent' && $this->png_truecolor && !$this->setup['reduceColors'] && (empty($this->setup['format']) || $this->setup['format'] === 'png')) {
386 // Set transparency properties
387 imagesavealpha($this->im, TRUE);
388 // Fill with a transparent background
389 $transparentColor = imagecolorallocatealpha($this->im, 0, 0, 0, 127);
390 imagefill($this->im, 0, 0, $transparentColor);
391 // Set internal properties to keep the transparency over the rendering process
392 $this->saveAlphaLayer = TRUE;
393 // Force PNG in case no format is set
394 $this->setup['format'] = 'png';
395 } else {
396 // Fill the background with the given color
397 $BGcols = $this->convertColor($this->setup['backColor']);
398 $Bcolor = ImageColorAllocate($this->im, $BGcols[0], $BGcols[1], $BGcols[2]);
399 ImageFilledRectangle($this->im, 0, 0, $XY[0], $XY[1], $Bcolor);
400 }
401 // Traverse the GIFBUILDER objects an render each one:
402 if (is_array($this->setup)) {
403 $sKeyArray = \TYPO3\CMS\Core\TypoScript\TemplateService::sortedKeyList($this->setup);
404 foreach ($sKeyArray as $theKey) {
405 $theValue = $this->setup[$theKey];
406 if ((int)$theKey && ($conf = $this->setup[$theKey . '.'])) {
407 // apply stdWrap to all properties, except for TEXT objects
408 // all properties of the TEXT sub-object have already been stdWrap-ped
409 // before in ->checkTextObj()
410 if ($theValue !== 'TEXT') {
411 $isStdWrapped = array();
412 foreach ($conf as $key => $value) {
413 $parameter = rtrim($key, '.');
414 if (!$isStdWrapped[$parameter] && isset($conf[$parameter . '.'])) {
415 $conf[$parameter] = $this->cObj->stdWrap($conf[$parameter], $conf[$parameter . '.']);
416 $isStdWrapped[$parameter] = 1;
417 }
418 }
419 }
420
421 switch ($theValue) {
422 case 'IMAGE':
423 if ($conf['mask']) {
424 $this->maskImageOntoImage($this->im, $conf, $this->workArea);
425 } else {
426 $this->copyImageOntoImage($this->im, $conf, $this->workArea);
427 }
428 break;
429 case 'TEXT':
430 if (!$conf['hide']) {
431 if (is_array($conf['shadow.'])) {
432 $isStdWrapped = array();
433 foreach ($conf['shadow.'] as $key => $value) {
434 $parameter = rtrim($key, '.');
435 if (!$isStdWrapped[$parameter] && isset($conf[$parameter . '.'])) {
436 $conf['shadow.'][$parameter] = $this->cObj->stdWrap($conf[$parameter], $conf[$parameter . '.']);
437 $isStdWrapped[$parameter] = 1;
438 }
439 }
440 $this->makeShadow($this->im, $conf['shadow.'], $this->workArea, $conf);
441 }
442 if (is_array($conf['emboss.'])) {
443 $isStdWrapped = array();
444 foreach ($conf['emboss.'] as $key => $value) {
445 $parameter = rtrim($key, '.');
446 if (!$isStdWrapped[$parameter] && isset($conf[$parameter . '.'])) {
447 $conf['emboss.'][$parameter] = $this->cObj->stdWrap($conf[$parameter], $conf[$parameter . '.']);
448 $isStdWrapped[$parameter] = 1;
449 }
450 }
451 $this->makeEmboss($this->im, $conf['emboss.'], $this->workArea, $conf);
452 }
453 if (is_array($conf['outline.'])) {
454 $isStdWrapped = array();
455 foreach ($conf['outline.'] as $key => $value) {
456 $parameter = rtrim($key, '.');
457 if (!$isStdWrapped[$parameter] && isset($conf[$parameter . '.'])) {
458 $conf['outline.'][$parameter] = $this->cObj->stdWrap($conf[$parameter], $conf[$parameter . '.']);
459 $isStdWrapped[$parameter] = 1;
460 }
461 }
462 $this->makeOutline($this->im, $conf['outline.'], $this->workArea, $conf);
463 }
464 $conf['imgMap'] = 1;
465 $this->makeText($this->im, $conf, $this->workArea);
466 }
467 break;
468 case 'OUTLINE':
469 if ($this->setup[$conf['textObjNum']] == 'TEXT' && ($txtConf = $this->checkTextObj($this->setup[$conf['textObjNum'] . '.']))) {
470 $this->makeOutline($this->im, $conf, $this->workArea, $txtConf);
471 }
472 break;
473 case 'EMBOSS':
474 if ($this->setup[$conf['textObjNum']] == 'TEXT' && ($txtConf = $this->checkTextObj($this->setup[$conf['textObjNum'] . '.']))) {
475 $this->makeEmboss($this->im, $conf, $this->workArea, $txtConf);
476 }
477 break;
478 case 'SHADOW':
479 if ($this->setup[$conf['textObjNum']] == 'TEXT' && ($txtConf = $this->checkTextObj($this->setup[$conf['textObjNum'] . '.']))) {
480 $this->makeShadow($this->im, $conf, $this->workArea, $txtConf);
481 }
482 break;
483 case 'BOX':
484 $this->makeBox($this->im, $conf, $this->workArea);
485 break;
486 case 'EFFECT':
487 $this->makeEffect($this->im, $conf);
488 break;
489 case 'ADJUST':
490 $this->adjust($this->im, $conf);
491 break;
492 case 'CROP':
493 $this->crop($this->im, $conf);
494 break;
495 case 'SCALE':
496 $this->scale($this->im, $conf);
497 break;
498 case 'WORKAREA':
499 if ($conf['set']) {
500 // this sets the workArea
501 $this->setWorkArea($conf['set']);
502 }
503 if (isset($conf['clear'])) {
504 // This sets the current to the default;
505 $this->workArea = $this->defaultWorkArea;
506 }
507 break;
508 case 'ELLIPSE':
509 $this->makeEllipse($this->im, $conf, $this->workArea);
510 break;
511 }
512 }
513 }
514 }
515 // Preserve alpha transparency
516 if (!$this->saveAlphaLayer) {
517 if ($this->setup['transparentBackground']) {
518 // Auto transparent background is set
519 $Bcolor = ImageColorClosest($this->im, $BGcols[0], $BGcols[1], $BGcols[2]);
520 imagecolortransparent($this->im, $Bcolor);
521 } elseif (is_array($this->setup['transparentColor_array'])) {
522 // Multiple transparent colors are set. This is done via the trick that all transparent colors get
523 // converted to one color and then this one gets set as transparent as png/gif can just have one
524 // transparent color.
525 $Tcolor = $this->unifyColors($this->im, $this->setup['transparentColor_array'], (int)$this->setup['transparentColor.']['closest']);
526 if ($Tcolor >= 0) {
527 imagecolortransparent($this->im, $Tcolor);
528 }
529 }
530 }
531 }
532
533 /*********************************************
534 *
535 * Various helper functions
536 *
537 ********************************************/
538 /**
539 * Initializing/Cleaning of TypoScript properties for TEXT GIFBUILDER objects
540 *
541 * 'cleans' TEXT-object; Checks fontfile and other vital setup
542 * Finds the title if its a 'variable' (instantiates a cObj and loads it with the ->data record)
543 * Performs caseshift if any.
544 *
545 * @param array $conf GIFBUILDER object TypoScript properties
546 * @return array Modified $conf array IF the "text" property is not blank
547 * @access private
548 */
549 public function checkTextObj($conf) {
550 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
551 $cObj->start($this->data);
552 $isStdWrapped = array();
553 foreach ($conf as $key => $value) {
554 $parameter = rtrim($key, '.');
555 if (!$isStdWrapped[$parameter] && isset($conf[$parameter . '.'])) {
556 $conf[$parameter] = $cObj->stdWrap($conf[$parameter], $conf[$parameter . '.']);
557 $isStdWrapped[$parameter] = 1;
558 }
559 }
560 $conf['fontFile'] = $this->checkFile($conf['fontFile']);
561 if (!$conf['fontFile']) {
562 $conf['fontFile'] = 'typo3/sysext/core/Resources/Private/Font/nimbus.ttf';
563 }
564 if (!$conf['iterations']) {
565 $conf['iterations'] = 1;
566 }
567 if (!$conf['fontSize']) {
568 $conf['fontSize'] = 12;
569 }
570 // If any kind of spacing applys, we cannot use angles!!
571 if ($conf['spacing'] || $conf['wordSpacing']) {
572 $conf['angle'] = 0;
573 }
574 if (!isset($conf['antiAlias'])) {
575 $conf['antiAlias'] = 1;
576 }
577 $conf['fontColor'] = trim($conf['fontColor']);
578 // Strip HTML
579 if (!$conf['doNotStripHTML']) {
580 $conf['text'] = strip_tags($conf['text']);
581 }
582 $this->combinedTextStrings[] = strip_tags($conf['text']);
583 // Max length = 100 if automatic line braks are not defined:
584 if (!isset($conf['breakWidth']) || !$conf['breakWidth']) {
585 $tlen = (int)$conf['textMaxLength'] ?: 100;
586 if ($this->nativeCharset) {
587 $conf['text'] = $this->csConvObj->substr($this->nativeCharset, $conf['text'], 0, $tlen);
588 } else {
589 $conf['text'] = substr($conf['text'], 0, $tlen);
590 }
591 }
592 if ((string)$conf['text'] != '') {
593 // Char range map thingie:
594 $fontBaseName = basename($conf['fontFile']);
595 if (is_array($this->charRangeMap[$fontBaseName])) {
596 // Initialize splitRendering array:
597 if (!is_array($conf['splitRendering.'])) {
598 $conf['splitRendering.'] = array();
599 }
600 $cfgK = $this->charRangeMap[$fontBaseName]['cfgKey'];
601 // Do not impose settings if a splitRendering object already exists:
602 if (!isset($conf['splitRendering.'][$cfgK])) {
603 // Set configuration:
604 $conf['splitRendering.'][$cfgK] = 'charRange';
605 $conf['splitRendering.'][$cfgK . '.'] = $this->charRangeMap[$fontBaseName]['charMapConfig'];
606 // Multiplicator of fontsize:
607 if ($this->charRangeMap[$fontBaseName]['multiplicator']) {
608 $conf['splitRendering.'][$cfgK . '.']['fontSize'] = round($conf['fontSize'] * $this->charRangeMap[$fontBaseName]['multiplicator']);
609 }
610 // Multiplicator of pixelSpace:
611 if ($this->charRangeMap[$fontBaseName]['pixelSpace']) {
612 $travKeys = array('xSpaceBefore', 'xSpaceAfter', 'ySpaceBefore', 'ySpaceAfter');
613 foreach ($travKeys as $pxKey) {
614 if (isset($conf['splitRendering.'][$cfgK . '.'][$pxKey])) {
615 $conf['splitRendering.'][$cfgK . '.'][$pxKey] = round($conf['splitRendering.'][($cfgK . '.')][$pxKey] * ($conf['fontSize'] / $this->charRangeMap[$fontBaseName]['pixelSpace']));
616 }
617 }
618 }
619 }
620 }
621 if (is_array($conf['splitRendering.'])) {
622 foreach ($conf['splitRendering.'] as $key => $value) {
623 if (is_array($conf['splitRendering.'][$key])) {
624 if (isset($conf['splitRendering.'][$key]['fontFile'])) {
625 $conf['splitRendering.'][$key]['fontFile'] = $this->checkFile($conf['splitRendering.'][$key]['fontFile']);
626 }
627 }
628 }
629 }
630 return $conf;
631 }
632 }
633
634 /**
635 * Calculation of offset using "splitCalc" and insertion of dimensions from other GIFBUILDER objects.
636 *
637 * Example:
638 * Input: 2+2, 2*3, 123, [10.w]
639 * Output: 4,6,123,45 (provided that the width of object in position 10 was 45 pixels wide)
640 *
641 * @param string $string The string to resolve/calculate the result of. The string is divided by a comma first and each resulting part is calculated into an integer.
642 * @return string The resolved string with each part (separated by comma) returned separated by comma
643 * @access private
644 */
645 public function calcOffset($string) {
646 $value = array();
647 $numbers = GeneralUtility::trimExplode(',', $this->calculateFunctions($string));
648 foreach ($numbers as $key => $val) {
649 if ((string)$val == (string)(int)$val) {
650 $value[$key] = (int)$val;
651 } else {
652 $value[$key] = $this->calculateValue($val);
653 }
654 }
655 $string = implode(',', $value);
656 return $string;
657 }
658
659 /**
660 * Returns an "imgResource" creating an instance of the ContentObjectRenderer class and calling ContentObjectRenderer::getImgResource
661 *
662 * @param string $file Filename value OR the string "GIFBUILDER", see documentation in TSref for the "datatype" called "imgResource
663 * @param array $fileArray TypoScript properties passed to the function. Either GIFBUILDER properties or imgResource properties, depending on the value of $file (whether that is "GIFBUILDER" or a file reference)
664 * @return array|NULL Returns an array with file information from ContentObjectRenderer::getImgResource()
665 * @access private
666 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource()
667 */
668 public function getResource($file, $fileArray) {
669 if (!GeneralUtility::inList($this->imageFileExt, $fileArray['ext'])) {
670 $fileArray['ext'] = $this->gifExtension;
671 }
672 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
673 $cObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
674 $cObj->start($this->data);
675 return $cObj->getImgResource($file, $fileArray);
676 }
677
678 /**
679 * Returns the reference to a "resource" in TypoScript.
680 *
681 * @param string $file The resource value.
682 * @return string Returns the relative filepath
683 * @access private
684 * @see \TYPO3\CMS\Core\TypoScript\TemplateService::getFileName()
685 */
686 public function checkFile($file) {
687 return $GLOBALS['TSFE']->tmpl->getFileName($file);
688 }
689
690 /**
691 * Calculates the GIFBUILDER output filename/path based on a serialized, hashed value of this->setup
692 * and prefixes the original filename
693 * also, the filename gets an additional prefix (max 100 characters),
694 * something like "GB_MD5HASH_myfilename_is_very_long_and_such.jpg"
695 *
696 * @param string $pre Filename prefix, eg. "GB_
697 * @return string The relative filepath (relative to PATH_site)
698 * @access private
699 */
700 public function fileName($pre) {
701 /** @var $basicFileFunctions \TYPO3\CMS\Core\Utility\File\BasicFileUtility */
702 $basicFileFunctions = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\File\\BasicFileUtility');
703 $filePrefix = implode('_', array_merge($this->combinedTextStrings, $this->combinedFileNames));
704 $filePrefix = $basicFileFunctions->cleanFileName($filePrefix);
705
706 return $this->tempPath . $pre . $filePrefix . '_' . GeneralUtility::shortMD5(serialize($this->setup)) . '.' . $this->extension();
707 }
708
709 /**
710 * Returns the file extension used in the filename
711 *
712 * @return string Extension; "jpg" or "gif"/"png
713 * @access private
714 */
715 public function extension() {
716 switch (strtolower($this->setup['format'])) {
717 case 'jpg':
718
719 case 'jpeg':
720 return 'jpg';
721 break;
722 case 'png':
723 return 'png';
724 break;
725 case 'gif':
726 return 'gif';
727 break;
728 default:
729 return $this->gifExtension;
730 }
731 }
732
733 /**
734 * Calculates the value concerning the dimensions of objects.
735 *
736 * @param string $string The string to be calculated (e.g. "[20.h]+13")
737 * @return int The calculated value (e.g. "23")
738 * @see calcOffset()
739 */
740 protected function calculateValue($string) {
741 $calculatedValue = 0;
742 $parts = GeneralUtility::splitCalc($string, '+-*/%');
743 foreach ($parts as $part) {
744 $theVal = $part[1];
745 $sign = $part[0];
746 if (((string)(int)$theVal) == ((string)$theVal)) {
747 $theVal = (int)$theVal;
748 } elseif ('[' . substr($theVal, 1, -1) . ']' == $theVal) {
749 $objParts = explode('.', substr($theVal, 1, -1));
750 $theVal = 0;
751 if (isset($this->objBB[$objParts[0]])) {
752 if ($objParts[1] == 'w') {
753 $theVal = $this->objBB[$objParts[0]][0];
754 } elseif ($objParts[1] == 'h') {
755 $theVal = $this->objBB[$objParts[0]][1];
756 } elseif ($objParts[1] == 'lineHeight') {
757 $theVal = $this->objBB[$objParts[0]][2]['lineHeight'];
758 }
759 $theVal = (int)$theVal;
760 }
761 } elseif (floatval($theVal)) {
762 $theVal = floatval($theVal);
763 } else {
764 $theVal = 0;
765 }
766 if ($sign == '-') {
767 $calculatedValue -= $theVal;
768 } elseif ($sign == '+') {
769 $calculatedValue += $theVal;
770 } elseif ($sign == '/' && $theVal) {
771 $calculatedValue = $calculatedValue / $theVal;
772 } elseif ($sign == '*') {
773 $calculatedValue = $calculatedValue * $theVal;
774 } elseif ($sign == '%' && $theVal) {
775 $calculatedValue %= $theVal;
776 }
777 }
778 return round($calculatedValue);
779 }
780
781 /**
782 * Calculates special functions:
783 * + max([10.h], [20.h]) -> gets the maximum of the given values
784 *
785 * @param string $string The raw string with functions to be calculated
786 * @return string The calculated values
787 */
788 protected function calculateFunctions($string) {
789 if (preg_match_all('#max\\(([^)]+)\\)#', $string, $matches)) {
790 foreach ($matches[1] as $index => $maxExpression) {
791 $string = str_replace($matches[0][$index], $this->calculateMaximum($maxExpression), $string);
792 }
793 }
794 return $string;
795 }
796
797 /**
798 * Calculates the maximum of a set of values defined like "[10.h],[20.h],1000"
799 *
800 * @param string $string The string to be used to calculate the maximum (e.g. "[10.h],[20.h],1000")
801 * @return int The maxium value of the given comma separated and calculated values
802 */
803 protected function calculateMaximum($string) {
804 $parts = GeneralUtility::trimExplode(',', $this->calcOffset($string), TRUE);
805 $maximum = count($parts) ? max($parts) : 0;
806 return $maximum;
807 }
808
809 }