GraphicalFunctions.php 121 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Core\Imaging;

18
19
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Charset\CharsetConverter;
20
use TYPO3\CMS\Core\Core\Environment;
21
use TYPO3\CMS\Core\Type\File\ImageInfo;
22
use TYPO3\CMS\Core\Utility\ArrayUtility;
23
use TYPO3\CMS\Core\Utility\CommandUtility;
24
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
25
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
27
use TYPO3\CMS\Core\Utility\PathUtility;
28
use TYPO3\CMS\Core\Utility\StringUtility;
29

30
31
32
/**
 * Standard graphical functions
 *
33
 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick.
34
35
 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
 */
36
37
38
class GraphicalFunctions
{
    /**
39
     * If set, the frame pointer is appended to the filenames.
40
41
42
     *
     * @var bool
     */
43
    public $addFrameSelection = true;
44
45
46
47
48
49
50
51
52
53
54

    /**
     * This should be changed to 'png' if you want this class to read/make PNG-files instead!
     *
     * @var string
     */
    public $gifExtension = 'gif';

    /**
     * File formats supported by gdlib. This variable get's filled in "init" method
     *
55
     * @var array
56
     */
57
    protected $gdlibExtensions = [];
58
59
60
61
62
63
64
65
66
67
68
69
70

    /**
     * defines the RGB colorspace to use
     *
     * @var string
     */
    protected $colorspace = 'RGB';

    /**
     * colorspace names allowed
     *
     * @var array
     */
71
    protected $allowedColorSpaceNames = [
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        'CMY',
        'CMYK',
        'Gray',
        'HCL',
        'HSB',
        'HSL',
        'HWB',
        'Lab',
        'LCH',
        'LMS',
        'Log',
        'Luv',
        'OHTA',
        'Rec601Luma',
        'Rec601YCbCr',
        'Rec709Luma',
        'Rec709YCbCr',
        'RGB',
        'sRGB',
        'Transparent',
        'XYZ',
        'YCbCr',
        'YCC',
        'YIQ',
        'YCbCr',
        'YUV'
98
    ];
99
100
101
102
103
104
105
106
107

    /**
     * 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
     *
     * @var int
     */
    public $truecolorColors = 16777215;

    /**
108
109
     * Allowed file extensions perceived as images by TYPO3.
     * List should be set to 'gif,png,jpeg,jpg' if IM is not available.
110
     *
111
     * @var array
112
     */
113
    protected $imageFileExt = ['gif', 'jpg', 'jpeg', 'png', 'tif', 'bmp', 'tga', 'pcx', 'ai', 'pdf'];
114
115

    /**
116
     * Web image extensions (can be shown by a webbrowser)
117
     *
118
     * @var array
119
     */
120
    protected $webImageExt = ['gif', 'jpg', 'jpeg', 'png'];
121
122

    /**
123
124
125
     * Enable ImageMagick effects, disabled by default as IM5+ effects slow down the image generation
     *
     * @var bool
126
     */
127
    protected $processorEffectsEnabled = false;
128
129
130
131

    /**
     * @var array
     */
132
    public $cmds = [
133
134
135
        'jpg' => '',
        'jpeg' => '',
        'gif' => '',
136
        'png' => ''
137
    ];
138
139

    /**
140
     * Whether ImageMagick/GraphicsMagick is enabled or not
141
     * @var bool
142
     */
143
    protected $processorEnabled;
144
145
146
147

    /**
     * @var bool
     */
148
    protected $mayScaleUp = true;
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

    /**
     * Filename prefix for images scaled in imageMagickConvert()
     *
     * @var string
     */
    public $filenamePrefix = '';

    /**
     * Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
     *
     * @var string
     */
    public $imageMagickConvert_forceFileNameBody = '';

    /**
     * This flag should always be FALSE. If set TRUE, imageMagickConvert will always write a new file to the tempdir! Used for debugging.
     *
     * @var bool
     */
169
    public $dontCheckForExistingTempFile = false;
170
171
172
173
174
175

    /**
     * Prevents imageMagickConvert() from compressing the gif-files with self::gifCompress()
     *
     * @var bool
     */
176
    public $dontCompress = false;
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

    /**
     * For debugging only.
     * Filenames will not be based on mtime and only filename (not path) will be used.
     * This key is also included in the hash of the filename...
     *
     * @var string
     */
    public $alternativeOutputKey = '';

    /**
     * All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
     *
     * @var array
     */
192
    public $IM_commands = [];
193
194
195
196

    /**
     * @var array
     */
197
    public $workArea = [];
198
199
200
201
202
203
204
205
206

    /**
     * Preserve the alpha transparency layer of read PNG images
     *
     * @var bool
     */
    protected $saveAlphaLayer = false;

    /**
207
     * ImageMagick scaling command; "-auto-orient -geometry" or "-auto-orient -sample". Used in makeText() and imageMagickConvert()
208
209
210
     *
     * @var string
     */
211
    public $scalecmd = '-auto-orient -geometry';
212
213
214
215
216
217

    /**
     * Used by v5_blur() to simulate 10 continuous steps of blurring
     *
     * @var string
     */
218
    protected $im5fx_blurSteps = '1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5';
219
220
221
222
223
224

    /**
     * Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
     *
     * @var string
     */
225
    protected $im5fx_sharpenSteps = '1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5';
226
227
228
229
230
231

    /**
     * This is the limit for the number of pixels in an image before it will be rendered as JPG instead of GIF/PNG
     *
     * @var int
     */
232
    protected $pixelLimitGif = 10000;
233
234
235
236
237
238

    /**
     * Array mapping HTML color names to RGB values.
     *
     * @var array
     */
239
    protected $colMap = [
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        'aqua' => [0, 255, 255],
        'black' => [0, 0, 0],
        'blue' => [0, 0, 255],
        'fuchsia' => [255, 0, 255],
        'gray' => [128, 128, 128],
        'green' => [0, 128, 0],
        'lime' => [0, 255, 0],
        'maroon' => [128, 0, 0],
        'navy' => [0, 0, 128],
        'olive' => [128, 128, 0],
        'purple' => [128, 0, 128],
        'red' => [255, 0, 0],
        'silver' => [192, 192, 192],
        'teal' => [0, 128, 128],
        'yellow' => [255, 255, 0],
        'white' => [255, 255, 255]
    ];
257
258
259
260

    /**
     * Charset conversion object:
     *
261
     * @var CharsetConverter
262
     */
263
    protected $csConvObj;
264

265
266
267
    /**
     * @var int
     */
268
    protected $jpegQuality = 85;
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

    /**
     * @var string
     */
    public $map = '';

    /**
     * This holds the operational setup.
     * Basically this is a TypoScript array with properties.
     *
     * @var array
     */
    public $setup = [];

    /**
     * @var int
     */
    public $w = 0;

    /**
     * @var int
     */
    public $h = 0;

    /**
     * @var array
     */
296
    protected $OFFSET;
297
298
299
300
301
302

    /**
     * @var resource
     */
    protected $im;

303
    /**
304
305
     * Reads configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX']
     * and sets some values in internal variables.
306
     */
307
    public function __construct()
308
309
    {
        $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
310
311
312
313
314
315
316
317
318
319
320
321
322
        if (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
            $this->gdlibExtensions[] = 'jpg';
            $this->gdlibExtensions[] = 'jpeg';
        }
        if (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
            $this->gdlibExtensions[] = 'png';
        }
        if (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
            $this->gdlibExtensions[] = 'gif';
        }

        if ($gfxConf['processor_colorspace'] && in_array($gfxConf['processor_colorspace'], $this->allowedColorSpaceNames, true)) {
            $this->colorspace = $gfxConf['processor_colorspace'];
323
        }
324
325

        $this->processorEnabled = (bool)$gfxConf['processor_enabled'];
326
        // Setting default JPG parameters:
327
        $this->jpegQuality = MathUtility::forceIntegerInRange($gfxConf['jpg_quality'], 10, 100, 85);
328
        $this->addFrameSelection = (bool)$gfxConf['processor_allowFrameSelection'];
329
330
331
        if ($gfxConf['gdlib_png']) {
            $this->gifExtension = 'png';
        }
332
        $this->imageFileExt = GeneralUtility::trimExplode(',', $gfxConf['imagefile_ext']);
333
334
335
336

        // Boolean. This is necessary if using ImageMagick 5+.
        // Effects in Imagemagick 5+ tends to render very slowly!!
        // - therefore must be disabled in order not to perform sharpen, blurring and such.
337
        $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace ' . $this->colorspace . ' -quality ' . $this->jpegQuality;
338

339
340
        // ... but if 'processor_effects' is set, enable effects
        if ($gfxConf['processor_effects']) {
341
            $this->processorEffectsEnabled = true;
342
343
            $this->cmds['jpg'] .= $this->v5_sharpen(10);
            $this->cmds['jpeg'] .= $this->v5_sharpen(10);
344
345
        }
        // Secures that images are not scaled up.
346
        $this->mayScaleUp = (bool)$gfxConf['processor_allowUpscaling'];
347
        $this->csConvObj = GeneralUtility::makeInstance(CharsetConverter::class);
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    }

    /*************************************************
     *
     * Layering images / "IMAGE" GIFBUILDER object
     *
     *************************************************/
    /**
     * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is TRUE.
     * It reads the two images defined by $conf['file'] and $conf['mask'] and copies the $conf['file'] onto the input image pointer image using the $conf['mask'] as a grayscale mask
     * The operation involves ImageMagick for combining.
     *
     * @param resource $im GDlib image pointer
     * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
     * @param array $workArea The current working area coordinates.
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
     */
    public function maskImageOntoImage(&$im, $conf, $workArea)
    {
        if ($conf['file'] && $conf['mask']) {
            $imgInf = pathinfo($conf['file']);
            $imgExt = strtolower($imgInf['extension']);
370
            if (!in_array($imgExt, $this->gdlibExtensions, true)) {
371
372
373
374
375
376
                $BBimage = $this->imageMagickConvert($conf['file'], $this->gifExtension);
            } else {
                $BBimage = $this->getImageDimensions($conf['file']);
            }
            $maskInf = pathinfo($conf['mask']);
            $maskExt = strtolower($maskInf['extension']);
377
            if (!in_array($maskExt, $this->gdlibExtensions, true)) {
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
                $BBmask = $this->imageMagickConvert($conf['mask'], $this->gifExtension);
            } else {
                $BBmask = $this->getImageDimensions($conf['mask']);
            }
            if ($BBimage && $BBmask) {
                $w = imagesx($im);
                $h = imagesy($im);
                $tmpStr = $this->randomName();
                $theImage = $tmpStr . '_img.' . $this->gifExtension;
                $theDest = $tmpStr . '_dest.' . $this->gifExtension;
                $theMask = $tmpStr . '_mask.' . $this->gifExtension;
                // Prepare overlay image
                $cpImg = $this->imageCreateFromFile($BBimage[3]);
                $destImg = imagecreatetruecolor($w, $h);
                // Preserve alpha transparency
                if ($this->saveAlphaLayer) {
                    imagesavealpha($destImg, true);
                    $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
                    imagefill($destImg, 0, 0, $Bcolor);
                } else {
398
399
                    $Bcolor = imagecolorallocate($destImg, 0, 0, 0);
                    imagefilledrectangle($destImg, 0, 0, $w, $h, $Bcolor);
400
401
402
                }
                $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
                $this->ImageWrite($destImg, $theImage);
403
404
                imagedestroy($cpImg);
                imagedestroy($destImg);
405
406
407
408
409
410
411
412
                // Prepare mask image
                $cpImg = $this->imageCreateFromFile($BBmask[3]);
                $destImg = imagecreatetruecolor($w, $h);
                if ($this->saveAlphaLayer) {
                    imagesavealpha($destImg, true);
                    $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
                    imagefill($destImg, 0, 0, $Bcolor);
                } else {
413
414
                    $Bcolor = imagecolorallocate($destImg, 0, 0, 0);
                    imagefilledrectangle($destImg, 0, 0, $w, $h, $Bcolor);
415
416
417
                }
                $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
                $this->ImageWrite($destImg, $theMask);
418
419
                imagedestroy($cpImg);
                imagedestroy($destImg);
420
421
422
                // Mask the images
                $this->ImageWrite($im, $theDest);
                // Let combineExec handle maskNegation
423
                $this->combineExec($theDest, $theImage, $theMask, $theDest);
424
425
426
427
428
                // The main image is loaded again...
                $backIm = $this->imageCreateFromFile($theDest);
                // ... and if nothing went wrong we load it onto the old one.
                if ($backIm) {
                    if (!$this->saveAlphaLayer) {
429
                        imagecolortransparent($backIm, -1);
430
431
432
433
                    }
                    $im = $backIm;
                }
                // Unlink files from process
434
435
436
                unlink($theDest);
                unlink($theImage);
                unlink($theMask);
437
438
439
440
441
442
443
444
445
446
            }
        }
    }

    /**
     * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is FALSE (using only $conf['file'])
     *
     * @param resource $im GDlib image pointer
     * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
     * @param array $workArea The current working area coordinates.
447
448
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
     * @see maskImageOntoImage()
449
450
451
452
     */
    public function copyImageOntoImage(&$im, $conf, $workArea)
    {
        if ($conf['file']) {
453
            if (!in_array($conf['BBOX'][2], $this->gdlibExtensions, true)) {
454
455
456
457
458
                $conf['BBOX'] = $this->imageMagickConvert($conf['BBOX'][3], $this->gifExtension);
                $conf['file'] = $conf['BBOX'][3];
            }
            $cpImg = $this->imageCreateFromFile($conf['file']);
            $this->copyGifOntoGif($im, $cpImg, $conf, $workArea);
459
            imagedestroy($cpImg);
460
461
462
463
464
465
466
467
468
469
        }
    }

    /**
     * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
     *
     * @param resource $im GDlib image pointer, destination (bottom image)
     * @param resource $cpImg GDlib image pointer, source (top image)
     * @param array $conf TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
     * @param array $workArea Work area
470
     * @internal
471
472
473
474
475
476
477
478
     */
    public function copyGifOntoGif(&$im, $cpImg, $conf, $workArea)
    {
        $cpW = imagesx($cpImg);
        $cpH = imagesy($cpImg);
        $tile = GeneralUtility::intExplode(',', $conf['tile']);
        $tile[0] = MathUtility::forceIntegerInRange($tile[0], 1, 20);
        $tile[1] = MathUtility::forceIntegerInRange($tile[1], 1, 20);
479
        $cpOff = $this->objPosition($conf, $workArea, [$cpW * $tile[0], $cpH * $tile[1]]);
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        for ($xt = 0; $xt < $tile[0]; $xt++) {
            $Xstart = $cpOff[0] + $cpW * $xt;
            // If this image is inside of the workArea, then go on
            if ($Xstart + $cpW > $workArea[0]) {
                // X:
                if ($Xstart < $workArea[0]) {
                    $cpImgCutX = $workArea[0] - $Xstart;
                    $Xstart = $workArea[0];
                } else {
                    $cpImgCutX = 0;
                }
                $w = $cpW - $cpImgCutX;
                if ($Xstart > $workArea[0] + $workArea[2] - $w) {
                    $w = $workArea[0] + $workArea[2] - $Xstart;
                }
                // If this image is inside of the workArea, then go on
                if ($Xstart < $workArea[0] + $workArea[2]) {
                    // Y:
                    for ($yt = 0; $yt < $tile[1]; $yt++) {
                        $Ystart = $cpOff[1] + $cpH * $yt;
                        // If this image is inside of the workArea, then go on
                        if ($Ystart + $cpH > $workArea[1]) {
                            if ($Ystart < $workArea[1]) {
                                $cpImgCutY = $workArea[1] - $Ystart;
                                $Ystart = $workArea[1];
                            } else {
                                $cpImgCutY = 0;
                            }
                            $h = $cpH - $cpImgCutY;
                            if ($Ystart > $workArea[1] + $workArea[3] - $h) {
                                $h = $workArea[1] + $workArea[3] - $Ystart;
                            }
                            // If this image is inside of the workArea, then go on
                            if ($Ystart < $workArea[1] + $workArea[3]) {
                                $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
     *
     * OK, the reason for this stupid fix is the following story:
     * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
     * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
     * copy a color-ful image onto the destination.
     * The GD2-fix is to
     * 1) Create a blank TRUE-COLOR image
     * 2) Copy the destination image onto that one
     * 3) Then do the actual operation; Copying the source (top image) onto that
     * 4) ... and return the result pointer.
     * 5) Reduce colors (if we do not, the result may become strange!)
     * It works, but the resulting images is now a true-color PNG which may be very large.
     * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
     *
     * @param resource $dstImg Destination image
     * @param resource $srcImg Source image
     * @param int $dstX Destination x-coordinate
     * @param int $dstY Destination y-coordinate
     * @param int $srcX Source x-coordinate
     * @param int $srcY Source y-coordinate
     * @param int $dstWidth Destination width
     * @param int $dstHeight Destination height
     * @param int $srcWidth Source width
     * @param int $srcHeight Source height
549
     * @internal
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
     */
    public function imagecopyresized(&$dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight)
    {
        if (!$this->saveAlphaLayer) {
            // Make true color image
            $tmpImg = imagecreatetruecolor(imagesx($dstImg), imagesy($dstImg));
            // Copy the source image onto that
            imagecopyresized($tmpImg, $dstImg, 0, 0, 0, 0, imagesx($dstImg), imagesy($dstImg), imagesx($dstImg), imagesy($dstImg));
            // Then copy the source image onto that (the actual operation!)
            imagecopyresized($tmpImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
            // Set the destination image
            $dstImg = $tmpImg;
        } else {
            imagecopyresized($dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
        }
    }

    /********************************
     *
     * Text / "TEXT" GIFBUILDER object
     *
     ********************************/
    /**
     * Implements the "TEXT" GIFBUILDER object
     *
     * @param resource $im GDlib image pointer
     * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
     * @param array $workArea The current working area coordinates.
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
     */
    public function makeText(&$im, $conf, $workArea)
    {
        // Spacing
583
        [$spacing, $wordSpacing] = $this->calcWordSpacing($conf);
584
585
        // Position
        $txtPos = $this->txtPosition($conf, $workArea, $conf['BBOX']);
586
        $theText = $conf['text'];
587
588
589
590
591
592
593
594
        if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
            $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2], $txtPos, $conf['imgMap.']), $conf['imgMap.']);
        }
        if (!$conf['hideButCreateMap']) {
            // Font Color:
            $cols = $this->convertColor($conf['fontColor']);
            // NiceText is calculated
            if (!$conf['niceText']) {
595
                $Fcolor = imagecolorallocate($im, $cols[0], $cols[1], $cols[2]);
596
597
598
                // antiAliasing is setup:
                $Fcolor = $conf['antiAlias'] ? $Fcolor : -$Fcolor;
                for ($a = 0; $a < $conf['iterations']; $a++) {
599
                    // If any kind of spacing applies, we use this function:
600
                    if ($spacing || $wordSpacing) {
601
                        $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, GeneralUtility::getFileAbsFileName($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
                    } else {
                        $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
                    }
                }
            } else {
                // NICETEXT::
                // options anti_aliased and iterations is NOT available when doing this!!
                $w = imagesx($im);
                $h = imagesy($im);
                $tmpStr = $this->randomName();
                $fileMenu = $tmpStr . '_menuNT.' . $this->gifExtension;
                $fileColor = $tmpStr . '_colorNT.' . $this->gifExtension;
                $fileMask = $tmpStr . '_maskNT.' . $this->gifExtension;
                // Scalefactor
                $sF = MathUtility::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
617
618
                $newW = (int)ceil($sF * imagesx($im));
                $newH = (int)ceil($sF * imagesy($im));
619
620
                // Make mask
                $maskImg = imagecreatetruecolor($newW, $newH);
621
622
623
                $Bcolor = imagecolorallocate($maskImg, 255, 255, 255);
                imagefilledrectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
                $Fcolor = imagecolorallocate($maskImg, 0, 0, 0);
624
625
                // If any kind of spacing applies, we use this function:
                if ($spacing || $wordSpacing) {
626
                    $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, GeneralUtility::getFileAbsFileName($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'], $sF);
627
628
629
630
                } else {
                    $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
                }
                $this->ImageWrite($maskImg, $fileMask);
631
                imagedestroy($maskImg);
632
                // Downscales the mask
633
                if (!$this->processorEffectsEnabled) {
634
635
636
637
                    $command = trim($this->scalecmd . ' ' . $w . 'x' . $h . '! -negate');
                } else {
                    $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd . ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after'] . ' -negate');
                    if ($conf['niceText.']['sharpen']) {
638
                        $command .= $this->v5_sharpen($conf['niceText.']['sharpen']);
639
640
641
642
643
                    }
                }
                $this->imageMagickExec($fileMask, $fileMask, $command);
                // Make the color-file
                $colorImg = imagecreatetruecolor($w, $h);
644
645
                $Ccolor = imagecolorallocate($colorImg, $cols[0], $cols[1], $cols[2]);
                imagefilledrectangle($colorImg, 0, 0, $w, $h, $Ccolor);
646
                $this->ImageWrite($colorImg, $fileColor);
647
                imagedestroy($colorImg);
648
649
650
651
652
653
654
655
656
                // The mask is applied
                // The main pictures is saved temporarily
                $this->ImageWrite($im, $fileMenu);
                $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
                // The main image is loaded again...
                $backIm = $this->imageCreateFromFile($fileMenu);
                // ... and if nothing went wrong we load it onto the old one.
                if ($backIm) {
                    if (!$this->saveAlphaLayer) {
657
                        imagecolortransparent($backIm, -1);
658
659
660
661
                    }
                    $im = $backIm;
                }
                // Deleting temporary files;
662
663
664
                unlink($fileMenu);
                unlink($fileColor);
                unlink($fileMask);
665
666
667
668
669
670
671
672
            }
        }
    }

    /**
     * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
     *
     * @param array $conf TypoScript array for the TEXT GIFBUILDER object
673
     * @param array $workArea Work area definition
674
675
     * @param array $BB Bounding box information, was set in \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
     * @return array [0]=x, [1]=y, [2]=w, [3]=h
676
     * @internal
677
678
679
680
     * @see makeText()
     */
    public function txtPosition($conf, $workArea, $BB)
    {
681
        $angle = (int)$conf['angle'] / 180 * M_PI;
682
683
684
685
        $conf['angle'] = 0;
        $straightBB = $this->calcBBox($conf);
        // offset, align, valign, workarea
        // [0]=x, [1]=y, [2]=w, [3]=h
686
        $result = [];
687
688
689
690
691
692
693
694
695
696
697
        $result[2] = $BB[0];
        $result[3] = $BB[1];
        $w = $workArea[2];
        switch ($conf['align']) {
            case 'right':

            case 'center':
                $factor = abs(cos($angle));
                $sign = cos($angle) < 0 ? -1 : 1;
                $len1 = $sign * $factor * $straightBB[0];
                $len2 = $sign * $BB[0];
698
                $result[0] = $w - ceil($len2 * $factor + (1 - $factor) * $len1);
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
                $factor = abs(sin($angle));
                $sign = sin($angle) < 0 ? -1 : 1;
                $len1 = $sign * $factor * $straightBB[0];
                $len2 = $sign * $BB[1];
                $result[1] = ceil($len2 * $factor + (1 - $factor) * $len1);
                break;
        }
        switch ($conf['align']) {
            case 'right':
                break;
            case 'center':
                $result[0] = round($result[0] / 2);
                $result[1] = round($result[1] / 2);
                break;
            default:
                $result[0] = 0;
                $result[1] = 0;
        }
        $result = $this->applyOffset($result, GeneralUtility::intExplode(',', $conf['offset']));
        $result = $this->applyOffset($result, $workArea);
        return $result;
    }

    /**
     * Calculates bounding box information for the TEXT GIFBUILDER object.
     *
     * @param array $conf TypoScript array for the TEXT GIFBUILDER object
     * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
727
     * @internal
728
729
     * @see txtPosition()
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
730
731
732
733
     */
    public function calcBBox($conf)
    {
        $sF = $this->getTextScalFactor($conf);
734
        [$spacing, $wordSpacing] = $this->calcWordSpacing($conf, $sF);
735
        $theText = $conf['text'];
736
737
738
        $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'], $sF);
        $theBBoxInfo = $charInf;
        if ($conf['angle']) {
739
740
            $xArr = [$charInf[0], $charInf[2], $charInf[4], $charInf[6]];
            $yArr = [$charInf[1], $charInf[3], $charInf[5], $charInf[7]];
741
742
743
744
745
746
747
748
            $x = max($xArr) - min($xArr);
            $y = max($yArr) - min($yArr);
        } else {
            $x = $charInf[2] - $charInf[0];
            $y = $charInf[1] - $charInf[7];
        }
        // Set original lineHeight (used by line breaks):
        $theBBoxInfo['lineHeight'] = $y;
749
750
751
752
        if (!empty($conf['lineHeight'])) {
            $theBBoxInfo['lineHeight'] = (int)$conf['lineHeight'];
        }

753
754
755
756
757
758
759
760
761
762
763
764
        // If any kind of spacing applys, we use this function:
        if ($spacing || $wordSpacing) {
            $x = 0;
            if (!$spacing && $wordSpacing) {
                $bits = explode(' ', $theText);
                foreach ($bits as $word) {
                    $word .= ' ';
                    $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'], $sF);
                    $wordW = $wordInf[2] - $wordInf[0];
                    $x += $wordW + $wordSpacing;
                }
            } else {
765
                $utf8Chars = $this->csConvObj->utf8_to_numberarray($theText);
766
767
768
769
                // For each UTF-8 char, do:
                foreach ($utf8Chars as $char) {
                    $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'], $sF);
                    $charW = $charInf[2] - $charInf[0];
770
                    $x += $charW + ($char === ' ' ? $wordSpacing : $spacing);
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
                }
            }
        } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
            $maxWidth = 0;
            $currentWidth = 0;
            $breakWidth = $conf['breakWidth'];
            $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
            $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
            // Iterate through all word pairs:
            foreach ($wordPairs as $index => $wordPair) {
                $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
                if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
                    $currentWidth += $wordWidth;
                } else {
                    $maxWidth = max($maxWidth, $currentWidth);
                    $y += $breakSpace;
                    // Restart:
                    $currentWidth = $wordWidth;
                }
            }
            $x = max($maxWidth, $currentWidth) * $sF;
        }
        if ($sF > 1) {
            $x = ceil($x / $sF);
            $y = ceil($y / $sF);
            if (is_array($theBBoxInfo)) {
                foreach ($theBBoxInfo as &$value) {
                    $value = ceil($value / $sF);
                }
                unset($value);
            }
        }
803
        return [$x, $y, $theBBoxInfo];
804
805
806
807
808
809
810
    }

    /**
     * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
     *
     * @param array $cords Coordinates for a polygon image map as created by ->calcTextCordsForMap()
     * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
811
     * @internal
812
813
     * @see makeText()
     * @see calcTextCordsForMap()
814
815
816
     */
    public function addToMap($cords, $conf)
    {
817
        $this->map .= '<area shape="poly" coords="' . implode(',', $cords) . '"'
818
819
820
821
822
823
824
825
826
827
828
829
830
            . ' href="' . htmlspecialchars($conf['url']) . '"'
            . ($conf['target'] ? ' target="' . htmlspecialchars($conf['target']) . '"' : '')
            . ((string)$conf['titleText'] !== '' ? ' title="' . htmlspecialchars($conf['titleText']) . '"' : '')
            . ' alt="' . htmlspecialchars($conf['altText']) . '" />';
    }

    /**
     * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
     *
     * @param array $cords Coordinates (from BBOX array)
     * @param array $offset Offset array
     * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
     * @return array
831
     * @internal
832
833
     * @see makeText()
     * @see calcTextCordsForMap()
834
835
836
     */
    public function calcTextCordsForMap($cords, $offset, $conf)
    {
837
        $newCords = [];
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
        $pars = GeneralUtility::intExplode(',', $conf['explode'] . ',');
        $newCords[0] = $cords[0] + $offset[0] - $pars[0];
        $newCords[1] = $cords[1] + $offset[1] + $pars[1];
        $newCords[2] = $cords[2] + $offset[0] + $pars[0];
        $newCords[3] = $cords[3] + $offset[1] + $pars[1];
        $newCords[4] = $cords[4] + $offset[0] + $pars[0];
        $newCords[5] = $cords[5] + $offset[1] - $pars[1];
        $newCords[6] = $cords[6] + $offset[0] - $pars[0];
        $newCords[7] = $cords[7] + $offset[1] - $pars[1];
        return $newCords;
    }

    /**
     * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
     * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
     * See
     *
     * @param resource $im (See argument for PHP function imageTTFtext())
     * @param int $fontSize (See argument for PHP function imageTTFtext())
     * @param int $angle (See argument for PHP function imageTTFtext())
     * @param int $x (See argument for PHP function imageTTFtext())
     * @param int $y (See argument for PHP function imageTTFtext())
     * @param int $Fcolor (See argument for PHP function imageTTFtext())
     * @param string $fontFile (See argument for PHP function imageTTFtext())
     * @param string $text (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
     * @param int $spacing The spacing of letters in pixels
     * @param int $wordSpacing The spacing of words in pixels
     * @param array $splitRenderingConf Array
     * @param int $sF Scale factor
867
     * @internal
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
     */
    public function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF = 1)
    {
        $spacing *= $sF;
        $wordSpacing *= $sF;
        if (!$spacing && $wordSpacing) {
            $bits = explode(' ', $text);
            foreach ($bits as $word) {
                $word .= ' ';
                $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf, $sF);
                $wordW = $wordInf[2] - $wordInf[0];
                $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
                $x += $wordW + $wordSpacing;
            }
        } else {
883
            $utf8Chars = $this->csConvObj->utf8_to_numberarray($text);
884
885
886
887
888
            // For each UTF-8 char, do:
            foreach ($utf8Chars as $char) {
                $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
                $charW = $charInf[2] - $charInf[0];
                $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
889
                $x += $charW + ($char === ' ' ? $wordSpacing : $spacing);
890
891
892
893
894
895
896
897
898
            }
        }
    }

    /**
     * Function that finds the right fontsize that will render the textstring within a certain width
     *
     * @param array $conf The TypoScript properties of the TEXT GIFBUILDER object
     * @return int The new fontSize
899
     * @internal
900
901
902
903
904
905
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
     */
    public function fontResize($conf)
    {
        // You have to use +calc options like [10.h] in 'offset' to get the right position of your text-image, if you use +calc in XY height!!!!
        $maxWidth = (int)$conf['maxWidth'];
906
        [$spacing, $wordSpacing] = $this->calcWordSpacing($conf);
907
908
909
910
911
        if ($maxWidth) {
            // If any kind of spacing applys, we use this function:
            if ($spacing || $wordSpacing) {
                return $conf['fontSize'];
            }
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
            do {
                // Determine bounding box.
                $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $conf['text'], $conf['splitRendering.']);
                if ($conf['angle'] < 0) {
                    $pixelWidth = abs($bounds[4] - $bounds[0]);
                } elseif ($conf['angle'] > 0) {
                    $pixelWidth = abs($bounds[2] - $bounds[6]);
                } else {
                    $pixelWidth = abs($bounds[4] - $bounds[6]);
                }
                // Size is fine, exit:
                if ($pixelWidth <= $maxWidth) {
                    break;
                }
                $conf['fontSize']--;
            } while ($conf['fontSize'] > 1);
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
        }
        return $conf['fontSize'];
    }

    /**
     * Wrapper for ImageTTFBBox
     *
     * @param int $fontSize (See argument for PHP function ImageTTFBBox())
     * @param int $angle (See argument for PHP function ImageTTFBBox())
     * @param string $fontFile (See argument for PHP function ImageTTFBBox())
     * @param string $string (See argument for PHP function ImageTTFBBox())
     * @param array $splitRendering Split-rendering configuration
     * @param int $sF Scale factor
     * @return array Information array.
     */
    public function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF = 1)
    {
        // Initialize:
946
        $offsetInfo = [];
947
948
949
        $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
        // Traverse string parts:
        foreach ($stringParts as $strCfg) {
950
            $fontFile = GeneralUtility::getFileAbsFileName($strCfg['fontFile']);
951
            if (is_readable($fontFile)) {
952
953
                // Calculate Bounding Box for part.
                $calc = imagettfbbox($this->compensateFontSizeiBasedOnFreetypeDpi($sF * $strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
954
955
956
957
958
959
960
961
962
963
964
                // Calculate offsets:
                if (empty($offsetInfo)) {
                    // First run, just copy over.
                    $offsetInfo = $calc;
                } else {
                    $offsetInfo[2] += $calc[2] - $calc[0] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceBefore'] + (int)$strCfg['xSpaceAfter'];
                    $offsetInfo[3] += $calc[3] - $calc[1] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceBefore'] - (int)$strCfg['ySpaceAfter'];
                    $offsetInfo[4] += $calc[4] - $calc[6] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceBefore'] + (int)$strCfg['xSpaceAfter'];
                    $offsetInfo[5] += $calc[5] - $calc[7] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceBefore'] - (int)$strCfg['ySpaceAfter'];
                }
            } else {
965
                debug('cannot read file: ' . $fontFile, self::class . '::ImageTTFBBoxWrapper()');
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
            }
        }
        return $offsetInfo;
    }

    /**
     * Wrapper for ImageTTFText
     *
     * @param resource $im (See argument for PHP function imageTTFtext())
     * @param int $fontSize (See argument for PHP function imageTTFtext())
     * @param int $angle (See argument for PHP function imageTTFtext())
     * @param int $x (See argument for PHP function imageTTFtext())
     * @param int $y (See argument for PHP function imageTTFtext())
     * @param int $color (See argument for PHP function imageTTFtext())
     * @param string $fontFile (See argument for PHP function imageTTFtext())
     * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
     * @param array $splitRendering Split-rendering configuration
     * @param int $sF Scale factor
     */
    public function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1)
    {
        // Initialize:
        $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
989
990
        $x = (int)ceil($sF * $x);
        $y = (int)ceil($sF * $y);
991
992
993
994
995
996
997
        // Traverse string parts:
        foreach ($stringParts as $i => $strCfg) {
            // Initialize:
            $colorIndex = $color;
            // Set custom color if any (only when niceText is off):
            if ($strCfg['color'] && $sF == 1) {
                $cols = $this->convertColor($strCfg['color']);
998
                $colorIndex = imagecolorallocate($im, $cols[0], $cols[1], $cols[2]);
999
1000
1001
1002
1003
1004
1005
                $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
            }
            // Setting xSpaceBefore
            if ($i) {
                $x += (int)$strCfg['xSpaceBefore'];
                $y -= (int)$strCfg['ySpaceBefore'];
            }
1006
            $fontFile = GeneralUtility::getFileAbsFileName($strCfg['fontFile']);
1007
1008
            if (is_readable($fontFile)) {
                // Render part:
1009
                imagettftext($im, $this->compensateFontSizeiBasedOnFreetypeDpi($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1010
                // Calculate offset to apply:
1011
                $wordInf = imagettfbbox($this->compensateFontSizeiBasedOnFreetypeDpi($sF * $strCfg['fontSize']), $angle, GeneralUtility::getFileAbsFileName($strCfg['fontFile']), $strCfg['str']);
1012
1013
1014
                $x += $wordInf[2] - $wordInf[0] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceAfter'];
                $y += $wordInf[5] - $wordInf[7] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceAfter'];
            } else {
1015
                debug('cannot read file: ' . $fontFile, self::class . '::ImageTTFTextWrapper()');
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
            }
        }
    }

    /**
     * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
     *
     * @param string $string UTF-8 string
     * @param array $splitRendering Split-rendering configuration from GIFBUILDER TEXT object.
     * @param int $fontSize Current fontsize
     * @param string $fontFile Current font file
     * @return array Array with input string splitted according to configuration
     */
    public function splitString($string, $splitRendering, $fontSize, $fontFile)
    {
        // Initialize by setting the whole string and default configuration as the first entry.
1032
1033
        $result = [];
        $result[] = [
1034
1035
1036
            'str' => $string,
            'fontSize' => $fontSize,
            'fontFile' => $fontFile
1037
        ];
1038
1039
1040
        // Traverse the split-rendering configuration:
        // Splitting will create more entries in $result with individual configurations.
        if (is_array($splitRendering)) {
1041
            $sKeyArray = ArrayUtility::filterAndSortByNumericKeys($splitRendering);
1042
1043
1044
1045
1046
1047
1048
            // Traverse configured options:
            foreach ($sKeyArray as $key) {
                $cfg = $splitRendering[$key . '.'];
                // Process each type of split rendering keyword:
                switch ((string)$splitRendering[$key]) {
                    case 'highlightWord':
                        if ((string)$cfg['value'] !== '') {
1049
                            $newResult = [];
1050
1051
1052
1053
1054
1055
                            // Traverse the current parts of the result array:
                            foreach ($result as $part) {
                                // Explode the string value by the word value to highlight:
                                $explodedParts = explode($cfg['value'], $part['str']);
                                foreach ($explodedParts as $c => $expValue) {
                                    if ((string)$expValue !== '') {
1056
                                        $newResult[] = array_merge($part, ['str' => $expValue]);
1057
1058
                                    }
                                    if ($c + 1 < count($explodedParts)) {
1059
                                        $newResult[] = [
1060
                                            'str' => $cfg['value'],
1061
1062
                                            'fontSize' => $cfg['fontSize'] ?: $part['fontSize'],
                                            'fontFile' => $cfg['fontFile'] ?: $part['fontFile'],
1063
1064
1065
1066
1067
                                            'color' => $cfg['color'],
                                            'xSpaceBefore' => $cfg['xSpaceBefore'],
                                            'xSpaceAfter' => $cfg['xSpaceAfter'],
                                            'ySpaceBefore' => $cfg['ySpaceBefore'],
                                            'ySpaceAfter' => $cfg['ySpaceAfter']
1068
                                        ];
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
                                    }
                                }
                            }
                            // Set the new result as result array:
                            if (!empty($newResult)) {
                                $result = $newResult;
                            }
                        }
                        break;
                    case 'charRange':
                        if ((string)$cfg['value'] !== '') {
                            // Initialize range:
                            $ranges = GeneralUtility::trimExplode(',', $cfg['value'], true);
                            foreach ($ranges as $i => $rangeDef) {
1083
                                $ranges[$i] = GeneralUtility::intExplode('-', (string)$ranges[$i]);
1084
1085
1086
1087
                                if (!isset($ranges[$i][1])) {
                                    $ranges[$i][1] = $ranges[$i][0];
                                }
                            }
1088
                            $newResult = [];
1089
1090
1091
1092
1093
1094
                            // Traverse the current parts of the result array:
                            foreach ($result as $part) {
                                // Initialize:
                                $currentState = -1;
                                $bankAccum = '';
                                // Explode the string value by the word value to highlight:
1095
                                $utf8Chars = $this->csConvObj->utf8_to_numberarray($part['str']);
1096
1097
                                foreach ($utf8Chars as $utfChar) {
                                    // Find number and evaluate position:
1098
                                    $uNumber = (int)$this->csConvObj->utf8CharToUnumber($utfChar);
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
                                    $inRange = 0;
                                    foreach ($ranges as $rangeDef) {
                                        if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
                                            $inRange = 1;
                                            break;
                                        }
                                    }
                                    if ($currentState == -1) {
                                        $currentState = $inRange;
                                    }
                                    // Initialize first char
                                    // Switch bank:
1111
                                    if ($inRange != $currentState && $uNumber !== 9 && $uNumber !== 10 && $uNumber !== 13 && $uNumber !== 32) {
1112
1113
                                        // Set result:
                                        if ($bankAccum !== '') {
1114
                                            $newResult[] = [
1115
1116
1117
1118
1119
1120
1121
1122
                                                'str' => $bankAccum,
                                                'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
                                                'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
                                                'color' => $currentState ? $cfg['color'] : '',
                                                'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
                                                'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
                                                'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
                                                'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : ''
1123
                                            ];
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
                                        }
                                        // Initialize new settings:
                                        $currentState = $inRange;
                                        $bankAccum = '';
                                    }
                                    // Add char to bank:
                                    $bankAccum .= $utfChar;
                                }
                                // Set result for FINAL part:
                                if ($bankAccum !== '') {
1134
                                    $newResult[] = [
1135
1136
1137
1138
1139
1140
1141
1142
                                        'str' => $bankAccum,
                                        'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
                                        'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
                                        'color' => $currentState ? $cfg['color'] : '',
                                        'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
                                        'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
                                        'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
                                        'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : ''
1143
                                    ];
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
                                }
                            }
                            // Set the new result as result array:
                            if (!empty($newResult)) {
                                $result = $newResult;
                            }
                        }
                        break;
                }
            }
        }
        return $result;
    }

    /**
     * Calculates the spacing and wordSpacing values
     *
     * @param array $conf TypoScript array for the TEXT GIFBUILDER object
     * @param int $scaleFactor TypoScript value from eg $conf['niceText.']['scaleFactor']
     * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1164
     * @internal
1165
1166
1167
1168
1169
1170
1171
1172
1173
     * @see calcBBox()
     */
    public function calcWordSpacing($conf, $scaleFactor = 1)
    {
        $spacing = (int)$conf['spacing'];
        $wordSpacing = (int)$conf['wordSpacing'];
        $wordSpacing = $wordSpacing ?: $spacing * 2;
        $spacing *= $scaleFactor;
        $wordSpacing *= $scaleFactor;
1174
        return [$spacing, $wordSpacing];
1175
1176
1177
1178
1179
1180
1181
    }

    /**
     * Calculates and returns the niceText.scaleFactor
     *
     * @param array $conf TypoScript array for the TEXT GIFBUILDER object
     * @return int TypoScript value from eg $conf['niceText.']['scaleFactor']
1182
     * @internal
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
     */
    public function getTextScalFactor($conf)
    {
        if (!$conf['niceText']) {
            $sF = 1;
        } else {
            // NICETEXT::
            $sF = MathUtility::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
        }
        return $sF;
    }

    /**
     * Renders a regular text and takes care of a possible line break automatically.
     *
     * @param resource $im (See argument for PHP function imageTTFtext())
     * @param int $fontSize (See argument for PHP function imageTTFtext())
     * @param int $angle (See argument for PHP function imageTTFtext())
     * @param int $x (See argument for PHP function imageTTFtext())
     * @param int $y (See argument for PHP function imageTTFtext())
     * @param int $color (See argument for PHP function imageTTFtext())
     * @param string $fontFile (See argument for PHP function imageTTFtext())
     * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
     * @param array $splitRendering Split-rendering configuration
     * @param array $conf The configuration
     * @param int $sF Scale factor
     */
    protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1)
    {
        if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
            $phrase = '';
            $currentWidth = 0;
            $breakWidth = $conf['breakWidth'];
            $breakSpace = $this->getBreakSpace($conf);
            $wordPairs = $this->getWordPairsForLineBreak($string);
            // Iterate through all word pairs:
            foreach ($wordPairs as $index => $wordPair) {
                $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
                if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
                    $currentWidth += $wordWidth;
                    $phrase .= $wordPair;
                } else {
                    // Render the current phrase that is below breakWidth:
                    $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
                    // Calculate the news height offset:
                    $y += $breakSpace;
                    // Restart the phrase:
                    $currentWidth = $wordWidth;
                    $phrase = $wordPair;
                }
            }
            // Render the remaining phrase:
            if ($currentWidth) {
                $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
            }
        } else {
            $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
        }
    }

    /**
     * Gets the word pairs used for automatic line breaks.
     *
     * @param string $string
     * @return array
     */
    protected function getWordPairsForLineBreak($string)
    {
1251
        $wordPairs = [];
1252
        $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
1253
        $wordsArray = is_array($wordsArray) ? $wordsArray : [];
1254
1255
        $wordsCount = count($wordsArray);
        for ($index = 0; $index < $wordsCount; $index += 2) {
1256
            $wordPairs[] = $wordsArray[$index] . $wordsArray[$index + 1];
1257
1258
1259
1260
1261
        }
        return $wordPairs;
    }

    /**
1262
     * Gets the rendered text width
1263
1264
1265
     *
     * @param string $text
     * @param array $conf
1266
     * @return int
1267
1268
1269
     */
    protected function getRenderedTextWidth($text, $conf)
    {
1270
        $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $text, $conf['splitRendering.']);
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
        if ($conf['angle'] < 0) {
            $pixelWidth = abs($bounds[4] - $bounds[0]);
        } elseif ($conf['angle'] > 0) {
            $pixelWidth = abs($bounds[2] - $bounds[6]);
        } else {
            $pixelWidth = abs($bounds[4] - $bounds[6]);
        }
        return $pixelWidth;
    }

    /**
     * Gets the break space for each new line.
     *
     * @param array $conf TypoScript configuration for the currently rendered object
     * @param array $boundingBox The bounding box the the currently rendered object
     * @return int The break space
     */
    protected function getBreakSpace($conf, array $boundingBox = null)
    {
        if (!isset($boundingBox)) {
            $boundingBox = $this->calcBBox($conf);
            $boundingBox = $boundingBox[2];
        }
        if (isset($conf['breakSpace']) && $conf['breakSpace']) {
            $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
        } else {
            $breakSpace = $boundingBox['lineHeight'];
        }
        return $breakSpace;
    }

    /*********************************************
     *
     * Other GIFBUILDER objects related to TEXT
     *
     *********************************************/
    /**
     * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
     *
     * @param resource $im GDlib image pointer
     * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
     * @param array $workArea The current working area coordinates.
     * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1314
1315
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
     * @see makeText()
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
     */
    public function makeOutline(&$im, $conf, $workArea, $txtConf)
    {
        $thickness = (int)$conf['thickness'];
        if ($thickness) {
            $txtConf['fontColor'] = $conf['color'];
            $outLineDist = MathUtility::forceIntegerInRange($thickness, 1, 2);
            for ($b = 1; $b <= $outLineDist; $b++) {
                if ($b == 1) {
                    $it = 8;
                } else {
                    $it = 16;
                }
                $outL = $this->circleOffset($b, $it);
                for ($a = 0; $a < $it; $a++) {
                    $this->makeText($im, $txtConf, $this->applyOffset($workArea, $outL[$a]));
                }
            }
        }
    }

    /**
     * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
     *
     * access private
     *
     * @param int $distance Distance
     * @param int $iterations Iterations.
     * @return array
     * @see makeOutline()
     */
    public function circleOffset($distance, $iterations)
    {
1349
        $res = [];
1350
1351
        if ($distance && $iterations) {
            for ($a = 0; $a < $iterations; $a++) {
1352
                $yOff = round(sin(2 * M_PI / $iterations * ($a + 1)) * 100 * $distance);
1353
                if ($yOff) {
1354
                    $yOff = (int)(ceil(abs($yOff / 100)) * ($yOff / abs($yOff)));
1355
                }
1356
                $xOff = round(cos(2 * M_PI / $iterations * ($a + 1)) * 100 * $distance);
1357
                if ($xOff) {
1358
                    $xOff = (int)(ceil(abs($xOff / 100)) * ($xOff / abs($xOff)));
1359
                }
1360
                $res[$a] = [$xOff, $yOff];
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
            }
        }
        return $res;
    }

    /**
     * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
     *
     * @param resource $im GDlib image pointer
     * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
     * @param array $workArea The current working area coordinates.
     * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1373
1374
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
     * @see makeShadow()
TYPO3 Release Team's avatar