[!!!][TASK] Remove deprecated code from sysext core
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Imaging / GraphicalFunctions.php
1 <?php
2 namespace TYPO3\CMS\Core\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 use TYPO3\CMS\Core\Utility\MathUtility;
19
20 /**
21 * Standard graphical functions
22 *
23 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick.
24 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
25 *
26 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
27 */
28 class GraphicalFunctions {
29
30 // Internal configuration, set in init()
31
32 // If set, there is no frame pointer prepended to the filenames.
33 /**
34 * @var bool
35 */
36 public $noFramePrepended = 0;
37
38 // This should be changed to 'png' if you want this class to read/make PNG-files instead!
39 /**
40 * @var string
41 */
42 public $gifExtension = 'gif';
43
44 // File formats supported by gdlib. This variable get's filled in "init" method
45 /**
46 * @var string
47 */
48 public $gdlibExtensions = '';
49
50 // Set to TRUE if generated png's should be truecolor by default
51 /**
52 * @var bool
53 */
54 public $png_truecolor = FALSE;
55
56 /**
57 * defines the RGB colorspace to use
58 *
59 * @var string
60 */
61 protected $colorspace = 'RGB';
62
63 /**
64 * colorspace names allowed
65 *
66 * @var array
67 */
68 protected $allowedColorSpaceNames = array(
69 'CMY',
70 'CMYK',
71 'Gray',
72 'HCL',
73 'HSB',
74 'HSL',
75 'HWB',
76 'Lab',
77 'LCH',
78 'LMS',
79 'Log',
80 'Luv',
81 'OHTA',
82 'Rec601Luma',
83 'Rec601YCbCr',
84 'Rec709Luma',
85 'Rec709YCbCr',
86 'RGB',
87 'sRGB',
88 'Transparent',
89 'XYZ',
90 'YCbCr',
91 'YCC',
92 'YIQ',
93 'YCbCr',
94 'YUV'
95 );
96
97 // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
98 /**
99 * @var int
100 */
101 public $truecolorColors = 16777215;
102
103 // If set, then all files in typo3temp will be logged in a database table. In addition to being a log of the files with original filenames, it also serves to secure that the same image is not rendered simultaneously by two different processes.
104 /**
105 * @var bool
106 */
107 public $enable_typo3temp_db_tracking = 0;
108
109 // Commalist of file extensions perceived as images by TYPO3. List should be set to 'gif,png,jpeg,jpg' if IM is not available. Lowercase and no spaces between!
110 /**
111 * @var string
112 */
113 public $imageFileExt = 'gif,jpg,jpeg,png,tif,bmp,tga,pcx,ai,pdf';
114
115 // Commalist of web image extensions (can be shown by a webbrowser)
116 /**
117 * @var string
118 */
119 public $webImageExt = 'gif,jpg,jpeg,png';
120
121 /**
122 * @var string
123 */
124 public $NO_IM_EFFECTS = '';
125
126 /**
127 * @var array
128 */
129 public $cmds = array(
130 'jpg' => '',
131 'jpeg' => '',
132 'gif' => '',
133 'png' => '-colors 64'
134 );
135
136 /**
137 * @var string
138 */
139 public $NO_IMAGE_MAGICK = '';
140
141 /**
142 * @var bool
143 */
144 public $V5_EFFECTS = 0;
145
146 /**
147 * @var bool
148 */
149 public $mayScaleUp = 1;
150
151 // Variables for testing, alternative usage etc.
152 // Filename prefix for images scaled in imageMagickConvert()
153 /**
154 * @var string
155 */
156 public $filenamePrefix = '';
157
158 // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
159 /**
160 * @var string
161 */
162 public $imageMagickConvert_forceFileNameBody = '';
163
164 // This flag should always be FALSE. If set TRUE, imageMagickConvert will always write a new file to the tempdir! Used for debugging.
165 /**
166 * @var bool
167 */
168 public $dontCheckForExistingTempFile = 0;
169
170 // Prevents imageMagickConvert() from compressing the gif-files with \TYPO3\CMS\Core\Utility\GeneralUtility::gif_compress()
171 /**
172 * @var bool
173 */
174 public $dontCompress = 0;
175
176 // For debugging ONLY!
177 /**
178 * @var bool
179 */
180 public $dontUnlinkTempFiles = 0;
181
182 // 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...
183 /**
184 * @var string
185 */
186 public $alternativeOutputKey = '';
187
188 // Internal:
189 // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
190 /**
191 * @var array
192 */
193 public $IM_commands = array();
194
195 /**
196 * @var array
197 */
198 public $workArea = array();
199
200 /**
201 * Preserve the alpha transparency layer of read PNG images
202 *
203 * @var bool
204 */
205 protected $saveAlphaLayer = FALSE;
206
207 // Constants:
208 // The temp-directory where to store the files. Normally relative to PATH_site but is allowed to be the absolute path AS LONG AS it is a subdir to PATH_site.
209 /**
210 * @var string
211 */
212 public $tempPath = 'typo3temp/';
213
214 // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
215 /**
216 * @var string
217 */
218 public $absPrefix = '';
219
220 // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
221 /**
222 * @var string
223 */
224 public $scalecmd = '-geometry';
225
226 // Used by v5_blur() to simulate 10 continuous steps of blurring
227 /**
228 * @var string
229 */
230 public $im5fx_blurSteps = '1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5';
231
232 // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
233 /**
234 * @var string
235 */
236 public $im5fx_sharpenSteps = '1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5';
237
238 // This is the limit for the number of pixels in an image before it will be rendered as JPG instead of GIF/PNG
239 /**
240 * @var int
241 */
242 public $pixelLimitGif = 10000;
243
244 // Array mapping HTML color names to RGB values.
245 /**
246 * @var array
247 */
248 public $colMap = array(
249 'aqua' => array(0, 255, 255),
250 'black' => array(0, 0, 0),
251 'blue' => array(0, 0, 255),
252 'fuchsia' => array(255, 0, 255),
253 'gray' => array(128, 128, 128),
254 'green' => array(0, 128, 0),
255 'lime' => array(0, 255, 0),
256 'maroon' => array(128, 0, 0),
257 'navy' => array(0, 0, 128),
258 'olive' => array(128, 128, 0),
259 'purple' => array(128, 0, 128),
260 'red' => array(255, 0, 0),
261 'silver' => array(192, 192, 192),
262 'teal' => array(0, 128, 128),
263 'yellow' => array(255, 255, 0),
264 'white' => array(255, 255, 255)
265 );
266
267 /**
268 * Charset conversion object:
269 *
270 * @var \TYPO3\CMS\Core\Charset\CharsetConverter
271 */
272 public $csConvObj;
273
274 // Is set to the native character set of the input strings.
275 /**
276 * @var string
277 */
278 public $nativeCharset = '';
279
280 /**
281 * Init function. Must always call this when using the class.
282 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
283 *
284 * @return void
285 */
286 public function init() {
287 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
288 if (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
289 $this->gdlibExtensions .= ',jpg,jpeg';
290 }
291 if (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
292 $this->gdlibExtensions .= ',png';
293 }
294 if (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
295 $this->gdlibExtensions .= ',gif';
296 }
297 if ($gfxConf['png_truecolor']) {
298 $this->png_truecolor = TRUE;
299 }
300
301 if ($gfxConf['colorspace'] && in_array($gfxConf['colorspace'], $this->allowedColorSpaceNames, TRUE)) {
302 $this->colorspace = $gfxConf['colorspace'];
303 }
304
305 if (!$gfxConf['im']) {
306 $this->NO_IMAGE_MAGICK = 1;
307 }
308 if (!$this->NO_IMAGE_MAGICK && (!$gfxConf['im_version_5'] || $gfxConf['im_version_5'] === 'im4' || $gfxConf['im_version_5'] === 'im5')) {
309 throw new \RuntimeException('Your TYPO3 installation is configured to use an old version of ImageMagick, which is not supported anymore. ' . 'Please upgrade to ImageMagick version 6 or GraphicksMagick and set $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] appropriately.', 1305059666);
310 }
311 // When GIFBUILDER gets used in truecolor mode
312 // No colors parameter if we generate truecolor images.
313 if ($this->png_truecolor) {
314 $this->cmds['png'] = '';
315 }
316 // Setting default JPG parameters:
317 $this->jpegQuality = MathUtility::forceIntegerInRange($gfxConf['jpg_quality'], 10, 100, 75);
318 $this->cmds['jpg'] = ($this->cmds['jpeg'] = '-colorspace ' . $this->colorspace . ' -sharpen 50 -quality ' . $this->jpegQuality);
319 if ($gfxConf['im_noFramePrepended']) {
320 $this->noFramePrepended = 1;
321 }
322 if ($gfxConf['gdlib_png']) {
323 $this->gifExtension = 'png';
324 }
325 if ($gfxConf['enable_typo3temp_db_tracking']) {
326 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
327 }
328 $this->imageFileExt = $gfxConf['imagefile_ext'];
329
330 // Boolean. This is necessary if using ImageMagick 5+.
331 // Effects in Imagemagick 5+ tends to render very slowly!!
332 // - therefore must be disabled in order not to perform sharpen, blurring and such.
333 $this->NO_IM_EFFECTS = 1;
334 $this->cmds['jpg'] = ($this->cmds['jpeg'] = '-colorspace ' . $this->colorspace . ' -quality ' . $this->jpegQuality);
335
336 // ... but if 'im_v5effects' is set, enable effects
337 if ($gfxConf['im_v5effects']) {
338 $this->NO_IM_EFFECTS = 0;
339 $this->V5_EFFECTS = 1;
340 if ($gfxConf['im_v5effects'] > 0) {
341 $this->cmds['jpg'] = ($this->cmds['jpeg'] = '-colorspace ' . $this->colorspace . ' -quality ' . (int)$gfxConf['jpg_quality'] . $this->v5_sharpen(10));
342 }
343 }
344 // Secures that images are not scaled up.
345 if ($gfxConf['im_noScaleUp']) {
346 $this->mayScaleUp = 0;
347 }
348 if (TYPO3_MODE == 'FE') {
349 $this->csConvObj = $GLOBALS['TSFE']->csConvObj;
350 } elseif (is_object($GLOBALS['LANG'])) {
351 // BE assumed:
352 $this->csConvObj = $GLOBALS['LANG']->csConvObj;
353 } else {
354 // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
355 $this->csConvObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
356 }
357 $this->nativeCharset = 'utf-8';
358 }
359
360 /*************************************************
361 *
362 * Layering images / "IMAGE" GIFBUILDER object
363 *
364 *************************************************/
365 /**
366 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is TRUE.
367 * 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
368 * The operation involves ImageMagick for combining.
369 *
370 * @param pointer $im GDlib image pointer
371 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
372 * @param array $workArea The current working area coordinates.
373 * @return void
374 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
375 */
376 public function maskImageOntoImage(&$im, $conf, $workArea) {
377 if ($conf['file'] && $conf['mask']) {
378 $imgInf = pathinfo($conf['file']);
379 $imgExt = strtolower($imgInf['extension']);
380 if (!GeneralUtility::inList($this->gdlibExtensions, $imgExt)) {
381 $BBimage = $this->imageMagickConvert($conf['file'], $this->gifExtension);
382 } else {
383 $BBimage = $this->getImageDimensions($conf['file']);
384 }
385 $maskInf = pathinfo($conf['mask']);
386 $maskExt = strtolower($maskInf['extension']);
387 if (!GeneralUtility::inList($this->gdlibExtensions, $maskExt)) {
388 $BBmask = $this->imageMagickConvert($conf['mask'], $this->gifExtension);
389 } else {
390 $BBmask = $this->getImageDimensions($conf['mask']);
391 }
392 if ($BBimage && $BBmask) {
393 $w = imagesx($im);
394 $h = imagesy($im);
395 $tmpStr = $this->randomName();
396 $theImage = $tmpStr . '_img.' . $this->gifExtension;
397 $theDest = $tmpStr . '_dest.' . $this->gifExtension;
398 $theMask = $tmpStr . '_mask.' . $this->gifExtension;
399 // Prepare overlay image
400 $cpImg = $this->imageCreateFromFile($BBimage[3]);
401 $destImg = imagecreatetruecolor($w, $h);
402 // Preserve alpha transparency
403 if ($this->saveAlphaLayer) {
404 imagesavealpha($destImg, TRUE);
405 $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
406 imagefill($destImg, 0, 0, $Bcolor);
407 } else {
408 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
409 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
410 }
411 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
412 $this->ImageWrite($destImg, $theImage);
413 imageDestroy($cpImg);
414 imageDestroy($destImg);
415 // Prepare mask image
416 $cpImg = $this->imageCreateFromFile($BBmask[3]);
417 $destImg = imagecreatetruecolor($w, $h);
418 if ($this->saveAlphaLayer) {
419 imagesavealpha($destImg, TRUE);
420 $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
421 imagefill($destImg, 0, 0, $Bcolor);
422 } else {
423 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
424 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
425 }
426 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
427 $this->ImageWrite($destImg, $theMask);
428 imageDestroy($cpImg);
429 imageDestroy($destImg);
430 // Mask the images
431 $this->ImageWrite($im, $theDest);
432 // Let combineExec handle maskNegation
433 $this->combineExec($theDest, $theImage, $theMask, $theDest, TRUE);
434 // The main image is loaded again...
435 $backIm = $this->imageCreateFromFile($theDest);
436 // ... and if nothing went wrong we load it onto the old one.
437 if ($backIm) {
438 if (!$this->saveAlphaLayer) {
439 ImageColorTransparent($backIm, -1);
440 }
441 $im = $backIm;
442 }
443 // Unlink files from process
444 if (!$this->dontUnlinkTempFiles) {
445 unlink($theDest);
446 unlink($theImage);
447 unlink($theMask);
448 }
449 }
450 }
451 }
452
453 /**
454 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is FALSE (using only $conf['file'])
455 *
456 * @param pointer $im GDlib image pointer
457 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
458 * @param array $workArea The current working area coordinates.
459 * @return void
460 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), maskImageOntoImage()
461 */
462 public function copyImageOntoImage(&$im, $conf, $workArea) {
463 if ($conf['file']) {
464 if (!GeneralUtility::inList($this->gdlibExtensions, $conf['BBOX'][2])) {
465 $conf['BBOX'] = $this->imageMagickConvert($conf['BBOX'][3], $this->gifExtension);
466 $conf['file'] = $conf['BBOX'][3];
467 }
468 $cpImg = $this->imageCreateFromFile($conf['file']);
469 $this->copyGifOntoGif($im, $cpImg, $conf, $workArea);
470 imageDestroy($cpImg);
471 }
472 }
473
474 /**
475 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
476 *
477 * @param pointer $im GDlib image pointer, destination (bottom image)
478 * @param pointer $cpImg GDlib image pointer, source (top image)
479 * @param array $conf TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
480 * @param array $workArea Work area
481 * @return void Works on the $im image pointer
482 * @access private
483 */
484 public function copyGifOntoGif(&$im, $cpImg, $conf, $workArea) {
485 $cpW = imagesx($cpImg);
486 $cpH = imagesy($cpImg);
487 $tile = GeneralUtility::intExplode(',', $conf['tile']);
488 $tile[0] = MathUtility::forceIntegerInRange($tile[0], 1, 20);
489 $tile[1] = MathUtility::forceIntegerInRange($tile[1], 1, 20);
490 $cpOff = $this->objPosition($conf, $workArea, array($cpW * $tile[0], $cpH * $tile[1]));
491 for ($xt = 0; $xt < $tile[0]; $xt++) {
492 $Xstart = $cpOff[0] + $cpW * $xt;
493 // If this image is inside of the workArea, then go on
494 if ($Xstart + $cpW > $workArea[0]) {
495 // X:
496 if ($Xstart < $workArea[0]) {
497 $cpImgCutX = $workArea[0] - $Xstart;
498 $Xstart = $workArea[0];
499 } else {
500 $cpImgCutX = 0;
501 }
502 $w = $cpW - $cpImgCutX;
503 if ($Xstart > $workArea[0] + $workArea[2] - $w) {
504 $w = $workArea[0] + $workArea[2] - $Xstart;
505 }
506 // If this image is inside of the workArea, then go on
507 if ($Xstart < $workArea[0] + $workArea[2]) {
508 // Y:
509 for ($yt = 0; $yt < $tile[1]; $yt++) {
510 $Ystart = $cpOff[1] + $cpH * $yt;
511 // If this image is inside of the workArea, then go on
512 if ($Ystart + $cpH > $workArea[1]) {
513 if ($Ystart < $workArea[1]) {
514 $cpImgCutY = $workArea[1] - $Ystart;
515 $Ystart = $workArea[1];
516 } else {
517 $cpImgCutY = 0;
518 }
519 $h = $cpH - $cpImgCutY;
520 if ($Ystart > $workArea[1] + $workArea[3] - $h) {
521 $h = $workArea[1] + $workArea[3] - $Ystart;
522 }
523 // If this image is inside of the workArea, then go on
524 if ($Ystart < $workArea[1] + $workArea[3]) {
525 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
526 }
527 }
528 }
529 }
530 }
531 }
532 }
533
534 /**
535 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
536 *
537 * OK, the reason for this stupid fix is the following story:
538 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
539 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
540 * copy a color-ful image onto the destination.
541 * The GD2-fix is to
542 * 1) Create a blank TRUE-COLOR image
543 * 2) Copy the destination image onto that one
544 * 3) Then do the actual operation; Copying the source (top image) onto that
545 * 4) ... and return the result pointer.
546 * 5) Reduce colors (if we do not, the result may become strange!)
547 * It works, but the resulting images is now a true-color PNG which may be very large.
548 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
549 *
550 * @param resource $dstImg Destination image
551 * @param resource $srcImg Source image
552 * @param int $dstX Destination x-coordinate
553 * @param int $dstY Destination y-coordinate
554 * @param int $srcX Source x-coordinate
555 * @param int $srcY Source y-coordinate
556 * @param int $dstWidth Destination width
557 * @param int $dstHeight Destination height
558 * @param int $srcWidth Source width
559 * @param int $srcHeight Source height
560 * @return void
561 * @access private
562 * @see \TYPO3\CMS\Backend\Utility\IconUtility::imagecopyresized()
563 */
564 public function imagecopyresized(&$dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight) {
565 if (!$this->saveAlphaLayer) {
566 // Make true color image
567 $tmpImg = imagecreatetruecolor(imagesx($dstImg), imagesy($dstImg));
568 // Copy the source image onto that
569 imagecopyresized($tmpImg, $dstImg, 0, 0, 0, 0, imagesx($dstImg), imagesy($dstImg), imagesx($dstImg), imagesy($dstImg));
570 // Then copy the source image onto that (the actual operation!)
571 imagecopyresized($tmpImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
572 // Set the destination image
573 $dstImg = $tmpImg;
574 } else {
575 imagecopyresized($dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
576 }
577 }
578
579 /********************************
580 *
581 * Text / "TEXT" GIFBUILDER object
582 *
583 ********************************/
584 /**
585 * Implements the "TEXT" GIFBUILDER object
586 *
587 * @param pointer $im GDlib image pointer
588 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
589 * @param array $workArea The current working area coordinates.
590 * @return void
591 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
592 */
593 public function makeText(&$im, $conf, $workArea) {
594 // Spacing
595 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
596 // Position
597 $txtPos = $this->txtPosition($conf, $workArea, $conf['BBOX']);
598 $theText = $this->recodeString($conf['text']);
599 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
600 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2], $txtPos, $conf['imgMap.']), $conf['imgMap.']);
601 }
602 if (!$conf['hideButCreateMap']) {
603 // Font Color:
604 $cols = $this->convertColor($conf['fontColor']);
605 // NiceText is calculated
606 if (!$conf['niceText']) {
607 $Fcolor = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
608 // antiAliasing is setup:
609 $Fcolor = $conf['antiAlias'] ? $Fcolor : -$Fcolor;
610 for ($a = 0; $a < $conf['iterations']; $a++) {
611 // If any kind of spacing applys, we use this function:
612 if ($spacing || $wordSpacing) {
613 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, self::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
614 } else {
615 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
616 }
617 }
618 } else {
619 // NICETEXT::
620 // options anti_aliased and iterations is NOT available when doing this!!
621 $w = imagesx($im);
622 $h = imagesy($im);
623 $tmpStr = $this->randomName();
624 $fileMenu = $tmpStr . '_menuNT.' . $this->gifExtension;
625 $fileColor = $tmpStr . '_colorNT.' . $this->gifExtension;
626 $fileMask = $tmpStr . '_maskNT.' . $this->gifExtension;
627 // Scalefactor
628 $sF = MathUtility::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
629 $newW = ceil($sF * imagesx($im));
630 $newH = ceil($sF * imagesy($im));
631 // Make mask
632 $maskImg = imagecreatetruecolor($newW, $newH);
633 $Bcolor = ImageColorAllocate($maskImg, 255, 255, 255);
634 ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
635 $Fcolor = ImageColorAllocate($maskImg, 0, 0, 0);
636 // If any kind of spacing applies, we use this function:
637 if ($spacing || $wordSpacing) {
638 $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, self::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'], $sF);
639 } else {
640 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
641 }
642 $this->ImageWrite($maskImg, $fileMask);
643 ImageDestroy($maskImg);
644 // Downscales the mask
645 if ($this->NO_IM_EFFECTS) {
646 $command = trim($this->scalecmd . ' ' . $w . 'x' . $h . '! -negate');
647 } else {
648 $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd . ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after'] . ' -negate');
649 if ($conf['niceText.']['sharpen']) {
650 if ($this->V5_EFFECTS) {
651 $command .= $this->v5_sharpen($conf['niceText.']['sharpen']);
652 } else {
653 $command .= ' -sharpen ' . MathUtility::forceIntegerInRange($conf['niceText.']['sharpen'], 1, 99);
654 }
655 }
656 }
657 $this->imageMagickExec($fileMask, $fileMask, $command);
658 // Make the color-file
659 $colorImg = imagecreatetruecolor($w, $h);
660 $Ccolor = ImageColorAllocate($colorImg, $cols[0], $cols[1], $cols[2]);
661 ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
662 $this->ImageWrite($colorImg, $fileColor);
663 ImageDestroy($colorImg);
664 // The mask is applied
665 // The main pictures is saved temporarily
666 $this->ImageWrite($im, $fileMenu);
667 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
668 // The main image is loaded again...
669 $backIm = $this->imageCreateFromFile($fileMenu);
670 // ... and if nothing went wrong we load it onto the old one.
671 if ($backIm) {
672 if (!$this->saveAlphaLayer) {
673 ImageColorTransparent($backIm, -1);
674 }
675 $im = $backIm;
676 }
677 // Deleting temporary files;
678 if (!$this->dontUnlinkTempFiles) {
679 unlink($fileMenu);
680 unlink($fileColor);
681 unlink($fileMask);
682 }
683 }
684 }
685 }
686
687 /**
688 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
689 *
690 * @param array $conf TypoScript array for the TEXT GIFBUILDER object
691 * @param array $workArea Workarea definition
692 * @param array $BB Bounding box information, was set in \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
693 * @return array [0]=x, [1]=y, [2]=w, [3]=h
694 * @access private
695 * @see makeText()
696 */
697 public function txtPosition($conf, $workArea, $BB) {
698 $angle = (int)$conf['angle'] / 180 * pi();
699 $conf['angle'] = 0;
700 $straightBB = $this->calcBBox($conf);
701 // offset, align, valign, workarea
702 // [0]=x, [1]=y, [2]=w, [3]=h
703 $result = array();
704 $result[2] = $BB[0];
705 $result[3] = $BB[1];
706 $w = $workArea[2];
707 switch ($conf['align']) {
708 case 'right':
709
710 case 'center':
711 $factor = abs(cos($angle));
712 $sign = cos($angle) < 0 ? -1 : 1;
713 $len1 = $sign * $factor * $straightBB[0];
714 $len2 = $sign * $BB[0];
715 $result[0] = $w - ceil(($len2 * $factor + (1 - $factor) * $len1));
716 $factor = abs(sin($angle));
717 $sign = sin($angle) < 0 ? -1 : 1;
718 $len1 = $sign * $factor * $straightBB[0];
719 $len2 = $sign * $BB[1];
720 $result[1] = ceil($len2 * $factor + (1 - $factor) * $len1);
721 break;
722 }
723 switch ($conf['align']) {
724 case 'right':
725 break;
726 case 'center':
727 $result[0] = round($result[0] / 2);
728 $result[1] = round($result[1] / 2);
729 break;
730 default:
731 $result[0] = 0;
732 $result[1] = 0;
733 }
734 $result = $this->applyOffset($result, GeneralUtility::intExplode(',', $conf['offset']));
735 $result = $this->applyOffset($result, $workArea);
736 return $result;
737 }
738
739 /**
740 * Calculates bounding box information for the TEXT GIFBUILDER object.
741 *
742 * @param array $conf TypoScript array for the TEXT GIFBUILDER object
743 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
744 * @access private
745 * @see txtPosition(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
746 */
747 public function calcBBox($conf) {
748 $sF = $this->getTextScalFactor($conf);
749 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf, $sF);
750 $theText = $this->recodeString($conf['text']);
751 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'], $sF);
752 $theBBoxInfo = $charInf;
753 if ($conf['angle']) {
754 $xArr = array($charInf[0], $charInf[2], $charInf[4], $charInf[6]);
755 $yArr = array($charInf[1], $charInf[3], $charInf[5], $charInf[7]);
756 $x = max($xArr) - min($xArr);
757 $y = max($yArr) - min($yArr);
758 } else {
759 $x = $charInf[2] - $charInf[0];
760 $y = $charInf[1] - $charInf[7];
761 }
762 // Set original lineHeight (used by line breaks):
763 $theBBoxInfo['lineHeight'] = $y;
764 // If any kind of spacing applys, we use this function:
765 if ($spacing || $wordSpacing) {
766 $x = 0;
767 if (!$spacing && $wordSpacing) {
768 $bits = explode(' ', $theText);
769 foreach ($bits as $word) {
770 $word .= ' ';
771 $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'], $sF);
772 $wordW = $wordInf[2] - $wordInf[0];
773 $x += $wordW + $wordSpacing;
774 }
775 } else {
776 $utf8Chars = $this->singleChars($theText);
777 // For each UTF-8 char, do:
778 foreach ($utf8Chars as $char) {
779 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'], $sF);
780 $charW = $charInf[2] - $charInf[0];
781 $x += $charW + ($char == ' ' ? $wordSpacing : $spacing);
782 }
783 }
784 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
785 $maxWidth = 0;
786 $currentWidth = 0;
787 $breakWidth = $conf['breakWidth'];
788 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
789 $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
790 // Iterate through all word pairs:
791 foreach ($wordPairs as $index => $wordPair) {
792 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
793 if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
794 $currentWidth += $wordWidth;
795 } else {
796 $maxWidth = max($maxWidth, $currentWidth);
797 $y += $breakSpace;
798 // Restart:
799 $currentWidth = $wordWidth;
800 }
801 }
802 $x = max($maxWidth, $currentWidth) * $sF;
803 }
804 if ($sF > 1) {
805 $x = ceil($x / $sF);
806 $y = ceil($y / $sF);
807 if (is_array($theBBoxInfo)) {
808 foreach ($theBBoxInfo as &$value) {
809 $value = ceil($value / $sF);
810 }
811 unset($value);
812 }
813 }
814 return array($x, $y, $theBBoxInfo);
815 }
816
817 /**
818 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
819 *
820 * @param array $cords Coordinates for a polygon image map as created by ->calcTextCordsForMap()
821 * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
822 * @return void
823 * @access private
824 * @see makeText(), calcTextCordsForMap()
825 */
826 public function addToMap($cords, $conf) {
827 $this->map .= '<area' . ' shape="poly"' . ' coords="' . implode(',', $cords) . '"' . ' href="' . htmlspecialchars($conf['url']) . '"' . ($conf['target'] ? ' target="' . htmlspecialchars($conf['target']) . '"' : '') . $JS . (strlen($conf['titleText']) ? ' title="' . htmlspecialchars($conf['titleText']) . '"' : '') . ' alt="' . htmlspecialchars($conf['altText']) . '" />';
828 }
829
830 /**
831 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
832 *
833 * @param array $cords Coordinates (from BBOX array)
834 * @param array $offset Offset array
835 * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
836 * @return array
837 * @access private
838 * @see makeText(), calcTextCordsForMap()
839 */
840 public function calcTextCordsForMap($cords, $offset, $conf) {
841 $pars = GeneralUtility::intExplode(',', $conf['explode'] . ',');
842 $newCords[0] = $cords[0] + $offset[0] - $pars[0];
843 $newCords[1] = $cords[1] + $offset[1] + $pars[1];
844 $newCords[2] = $cords[2] + $offset[0] + $pars[0];
845 $newCords[3] = $cords[3] + $offset[1] + $pars[1];
846 $newCords[4] = $cords[4] + $offset[0] + $pars[0];
847 $newCords[5] = $cords[5] + $offset[1] - $pars[1];
848 $newCords[6] = $cords[6] + $offset[0] - $pars[0];
849 $newCords[7] = $cords[7] + $offset[1] - $pars[1];
850 return $newCords;
851 }
852
853 /**
854 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
855 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
856 * See
857 *
858 * @param pointer $im (See argument for PHP function imageTTFtext())
859 * @param int $fontSize (See argument for PHP function imageTTFtext())
860 * @param int $angle (See argument for PHP function imageTTFtext())
861 * @param int $x (See argument for PHP function imageTTFtext())
862 * @param int $y (See argument for PHP function imageTTFtext())
863 * @param int $Fcolor (See argument for PHP function imageTTFtext())
864 * @param string $fontFile (See argument for PHP function imageTTFtext())
865 * @param string $text (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
866 * @param int $spacing The spacing of letters in pixels
867 * @param int $wordSpacing The spacing of words in pixels
868 * @param array $splitRenderingConf Array
869 * @param int $sF Scale factor
870 * @return void
871 * @access private
872 */
873 public function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF = 1) {
874 $spacing *= $sF;
875 $wordSpacing *= $sF;
876 if (!$spacing && $wordSpacing) {
877 $bits = explode(' ', $text);
878 foreach ($bits as $word) {
879 $word .= ' ';
880 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf, $sF);
881 $wordW = $wordInf[2] - $wordInf[0];
882 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
883 $x += $wordW + $wordSpacing;
884 }
885 } else {
886 $utf8Chars = $this->singleChars($text);
887 // For each UTF-8 char, do:
888 foreach ($utf8Chars as $char) {
889 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
890 $charW = $charInf[2] - $charInf[0];
891 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
892 $x += $charW + ($char == ' ' ? $wordSpacing : $spacing);
893 }
894 }
895 }
896
897 /**
898 * Function that finds the right fontsize that will render the textstring within a certain width
899 *
900 * @param array $conf The TypoScript properties of the TEXT GIFBUILDER object
901 * @return int The new fontSize
902 * @access private
903 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::start()
904 */
905 public function fontResize($conf) {
906 // 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!!!!
907 $maxWidth = (int)$conf['maxWidth'];
908 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
909 if ($maxWidth) {
910 // If any kind of spacing applys, we use this function:
911 if ($spacing || $wordSpacing) {
912 return $conf['fontSize'];
913 } else {
914 do {
915 // Determine bounding box.
916 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
917 if ($conf['angle'] < 0) {
918 $pixelWidth = abs($bounds[4] - $bounds[0]);
919 } elseif ($conf['angle'] > 0) {
920 $pixelWidth = abs($bounds[2] - $bounds[6]);
921 } else {
922 $pixelWidth = abs($bounds[4] - $bounds[6]);
923 }
924 // Size is fine, exit:
925 if ($pixelWidth <= $maxWidth) {
926 break;
927 } else {
928 $conf['fontSize']--;
929 }
930 } while ($conf['fontSize'] > 1);
931 }
932 }
933 return $conf['fontSize'];
934 }
935
936 /**
937 * Wrapper for ImageTTFBBox
938 *
939 * @param int $fontSize (See argument for PHP function ImageTTFBBox())
940 * @param int $angle (See argument for PHP function ImageTTFBBox())
941 * @param string $fontFile (See argument for PHP function ImageTTFBBox())
942 * @param string $string (See argument for PHP function ImageTTFBBox())
943 * @param array $splitRendering Split-rendering configuration
944 * @param int $sF Scale factor
945 * @return array Information array.
946 */
947 public function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF = 1) {
948 // Initialize:
949 $offsetInfo = array();
950 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
951 // Traverse string parts:
952 foreach ($stringParts as $strCfg) {
953 $fontFile = self::prependAbsolutePath($strCfg['fontFile']);
954 if (is_readable($fontFile)) {
955 /**
956 * Calculate Bounding Box for part.
957 * Due to a PHP bug, we must retry if $calc[2] is negative.
958 *
959 * @see https://bugs.php.net/bug.php?id=51315
960 * @see https://bugs.php.net/bug.php?id=22513
961 */
962 $try = 0;
963 do {
964 $calc = ImageTTFBBox(GeneralUtility::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
965 } while ($calc[2] < 0 && $try++ < 10);
966 // Calculate offsets:
967 if (!count($offsetInfo)) {
968 // First run, just copy over.
969 $offsetInfo = $calc;
970 } else {
971 $offsetInfo[2] += $calc[2] - $calc[0] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceBefore'] + (int)$strCfg['xSpaceAfter'];
972 $offsetInfo[3] += $calc[3] - $calc[1] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceBefore'] - (int)$strCfg['ySpaceAfter'];
973 $offsetInfo[4] += $calc[4] - $calc[6] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceBefore'] + (int)$strCfg['xSpaceAfter'];
974 $offsetInfo[5] += $calc[5] - $calc[7] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceBefore'] - (int)$strCfg['ySpaceAfter'];
975 }
976 } else {
977 debug('cannot read file: ' . $fontFile, 'TYPO3\\CMS\\Core\\Imaging\\GraphicalFunctions::ImageTTFBBoxWrapper()');
978 }
979 }
980 return $offsetInfo;
981 }
982
983 /**
984 * Wrapper for ImageTTFText
985 *
986 * @param pointer $im (See argument for PHP function imageTTFtext())
987 * @param int $fontSize (See argument for PHP function imageTTFtext())
988 * @param int $angle (See argument for PHP function imageTTFtext())
989 * @param int $x (See argument for PHP function imageTTFtext())
990 * @param int $y (See argument for PHP function imageTTFtext())
991 * @param int $color (See argument for PHP function imageTTFtext())
992 * @param string $fontFile (See argument for PHP function imageTTFtext())
993 * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
994 * @param array $splitRendering Split-rendering configuration
995 * @param int $sF Scale factor
996 * @return void
997 */
998 public function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1) {
999 // Initialize:
1000 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
1001 $x = ceil($sF * $x);
1002 $y = ceil($sF * $y);
1003 // Traverse string parts:
1004 foreach ($stringParts as $i => $strCfg) {
1005 // Initialize:
1006 $colorIndex = $color;
1007 // Set custom color if any (only when niceText is off):
1008 if ($strCfg['color'] && $sF == 1) {
1009 $cols = $this->convertColor($strCfg['color']);
1010 $colorIndex = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
1011 $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
1012 }
1013 // Setting xSpaceBefore
1014 if ($i) {
1015 $x += (int)$strCfg['xSpaceBefore'];
1016 $y -= (int)$strCfg['ySpaceBefore'];
1017 }
1018 $fontFile = self::prependAbsolutePath($strCfg['fontFile']);
1019 if (is_readable($fontFile)) {
1020 // Render part:
1021 ImageTTFText($im, GeneralUtility::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1022 // Calculate offset to apply:
1023 $wordInf = ImageTTFBBox(GeneralUtility::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, self::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1024 $x += $wordInf[2] - $wordInf[0] + (int)$splitRendering['compX'] + (int)$strCfg['xSpaceAfter'];
1025 $y += $wordInf[5] - $wordInf[7] - (int)$splitRendering['compY'] - (int)$strCfg['ySpaceAfter'];
1026 } else {
1027 debug('cannot read file: ' . $fontFile, 'TYPO3\\CMS\\Core\\Imaging\\GraphicalFunctions::ImageTTFTextWrapper()');
1028 }
1029 }
1030 }
1031
1032 /**
1033 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1034 *
1035 * @param string $string UTF-8 string
1036 * @param array $splitRendering Split-rendering configuration from GIFBUILDER TEXT object.
1037 * @param int $fontSize Current fontsize
1038 * @param string $fontFile Current font file
1039 * @return array Array with input string splitted according to configuration
1040 */
1041 public function splitString($string, $splitRendering, $fontSize, $fontFile) {
1042 // Initialize by setting the whole string and default configuration as the first entry.
1043 $result = array();
1044 $result[] = array(
1045 'str' => $string,
1046 'fontSize' => $fontSize,
1047 'fontFile' => $fontFile
1048 );
1049 // Traverse the split-rendering configuration:
1050 // Splitting will create more entries in $result with individual configurations.
1051 if (is_array($splitRendering)) {
1052 $sKeyArray = \TYPO3\CMS\Core\TypoScript\TemplateService::sortedKeyList($splitRendering);
1053 // Traverse configured options:
1054 foreach ($sKeyArray as $key) {
1055 $cfg = $splitRendering[$key . '.'];
1056 // Process each type of split rendering keyword:
1057 switch ((string) $splitRendering[$key]) {
1058 case 'highlightWord':
1059 if (strlen($cfg['value'])) {
1060 $newResult = array();
1061 // Traverse the current parts of the result array:
1062 foreach ($result as $part) {
1063 // Explode the string value by the word value to highlight:
1064 $explodedParts = explode($cfg['value'], $part['str']);
1065 foreach ($explodedParts as $c => $expValue) {
1066 if (strlen($expValue)) {
1067 $newResult[] = array_merge($part, array('str' => $expValue));
1068 }
1069 if ($c + 1 < count($explodedParts)) {
1070 $newResult[] = array(
1071 'str' => $cfg['value'],
1072 'fontSize' => $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1073 'fontFile' => $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1074 'color' => $cfg['color'],
1075 'xSpaceBefore' => $cfg['xSpaceBefore'],
1076 'xSpaceAfter' => $cfg['xSpaceAfter'],
1077 'ySpaceBefore' => $cfg['ySpaceBefore'],
1078 'ySpaceAfter' => $cfg['ySpaceAfter']
1079 );
1080 }
1081 }
1082 }
1083 // Set the new result as result array:
1084 if (count($newResult)) {
1085 $result = $newResult;
1086 }
1087 }
1088 break;
1089 case 'charRange':
1090 if (strlen($cfg['value'])) {
1091 // Initialize range:
1092 $ranges = GeneralUtility::trimExplode(',', $cfg['value'], TRUE);
1093 foreach ($ranges as $i => $rangeDef) {
1094 $ranges[$i] = GeneralUtility::intExplode('-', $ranges[$i]);
1095 if (!isset($ranges[$i][1])) {
1096 $ranges[$i][1] = $ranges[$i][0];
1097 }
1098 }
1099 $newResult = array();
1100 // Traverse the current parts of the result array:
1101 foreach ($result as $part) {
1102 // Initialize:
1103 $currentState = -1;
1104 $bankAccum = '';
1105 // Explode the string value by the word value to highlight:
1106 $utf8Chars = $this->singleChars($part['str']);
1107 foreach ($utf8Chars as $utfChar) {
1108 // Find number and evaluate position:
1109 $uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
1110 $inRange = 0;
1111 foreach ($ranges as $rangeDef) {
1112 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
1113 $inRange = 1;
1114 break;
1115 }
1116 }
1117 if ($currentState == -1) {
1118 $currentState = $inRange;
1119 }
1120 // Initialize first char
1121 // Switch bank:
1122 if ($inRange != $currentState && !GeneralUtility::inList('32,10,13,9', $uNumber)) {
1123 // Set result:
1124 if (strlen($bankAccum)) {
1125 $newResult[] = array(
1126 'str' => $bankAccum,
1127 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1128 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1129 'color' => $currentState ? $cfg['color'] : '',
1130 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1131 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1132 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1133 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : ''
1134 );
1135 }
1136 // Initialize new settings:
1137 $currentState = $inRange;
1138 $bankAccum = '';
1139 }
1140 // Add char to bank:
1141 $bankAccum .= $utfChar;
1142 }
1143 // Set result for FINAL part:
1144 if (strlen($bankAccum)) {
1145 $newResult[] = array(
1146 'str' => $bankAccum,
1147 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1148 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1149 'color' => $currentState ? $cfg['color'] : '',
1150 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1151 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1152 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1153 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : ''
1154 );
1155 }
1156 }
1157 // Set the new result as result array:
1158 if (count($newResult)) {
1159 $result = $newResult;
1160 }
1161 }
1162 break;
1163 }
1164 }
1165 }
1166 return $result;
1167 }
1168
1169 /**
1170 * Calculates the spacing and wordSpacing values
1171 *
1172 * @param array $conf TypoScript array for the TEXT GIFBUILDER object
1173 * @param int $scaleFactor TypoScript value from eg $conf['niceText.']['scaleFactor']
1174 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1175 * @access private
1176 * @see calcBBox()
1177 */
1178 public function calcWordSpacing($conf, $scaleFactor = 1) {
1179 $spacing = (int)$conf['spacing'];
1180 $wordSpacing = (int)$conf['wordSpacing'];
1181 $wordSpacing = $wordSpacing ?: $spacing * 2;
1182 $spacing *= $scaleFactor;
1183 $wordSpacing *= $scaleFactor;
1184 return array($spacing, $wordSpacing);
1185 }
1186
1187 /**
1188 * Calculates and returns the niceText.scaleFactor
1189 *
1190 * @param array $conf TypoScript array for the TEXT GIFBUILDER object
1191 * @return int TypoScript value from eg $conf['niceText.']['scaleFactor']
1192 * @access private
1193 */
1194 public function getTextScalFactor($conf) {
1195 if (!$conf['niceText']) {
1196 $sF = 1;
1197 } else {
1198 // NICETEXT::
1199 $sF = MathUtility::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
1200 }
1201 return $sF;
1202 }
1203
1204 /**
1205 * Renders a regular text and takes care of a possible line break automatically.
1206 *
1207 * @param pointer $im (See argument for PHP function imageTTFtext())
1208 * @param int $fontSize (See argument for PHP function imageTTFtext())
1209 * @param int $angle (See argument for PHP function imageTTFtext())
1210 * @param int $x (See argument for PHP function imageTTFtext())
1211 * @param int $y (See argument for PHP function imageTTFtext())
1212 * @param int $color (See argument for PHP function imageTTFtext())
1213 * @param string $fontFile (See argument for PHP function imageTTFtext())
1214 * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1215 * @param array $splitRendering Split-rendering configuration
1216 * @param array $conf The configuration
1217 * @param int $sF Scale factor
1218 * @return void
1219 */
1220 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1221 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1222 $phrase = '';
1223 $currentWidth = 0;
1224 $breakWidth = $conf['breakWidth'];
1225 $breakSpace = $this->getBreakSpace($conf);
1226 $wordPairs = $this->getWordPairsForLineBreak($string);
1227 // Iterate through all word pairs:
1228 foreach ($wordPairs as $index => $wordPair) {
1229 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1230 if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
1231 $currentWidth += $wordWidth;
1232 $phrase .= $wordPair;
1233 } else {
1234 // Render the current phrase that is below breakWidth:
1235 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1236 // Calculate the news height offset:
1237 $y += $breakSpace;
1238 // Restart the phrase:
1239 $currentWidth = $wordWidth;
1240 $phrase = $wordPair;
1241 }
1242 }
1243 // Render the remaining phrase:
1244 if ($currentWidth) {
1245 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1246 }
1247 } else {
1248 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1249 }
1250 }
1251
1252 /**
1253 * Gets the word pairs used for automatic line breaks.
1254 *
1255 * @param string $string
1256 * @return array
1257 */
1258 protected function getWordPairsForLineBreak($string) {
1259 $wordPairs = array();
1260 $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
1261 $wordsCount = count($wordsArray);
1262 for ($index = 0; $index < $wordsCount; $index += 2) {
1263 $wordPairs[] = $wordsArray[$index] . $wordsArray[($index + 1)];
1264 }
1265 return $wordPairs;
1266 }
1267
1268 /**
1269 * Gets the rendered text width.
1270 *
1271 * @param string $text
1272 * @param array $conf
1273 * @param int
1274 */
1275 protected function getRenderedTextWidth($text, $conf) {
1276 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1277 if ($conf['angle'] < 0) {
1278 $pixelWidth = abs($bounds[4] - $bounds[0]);
1279 } elseif ($conf['angle'] > 0) {
1280 $pixelWidth = abs($bounds[2] - $bounds[6]);
1281 } else {
1282 $pixelWidth = abs($bounds[4] - $bounds[6]);
1283 }
1284 return $pixelWidth;
1285 }
1286
1287 /**
1288 * Gets the break space for each new line.
1289 *
1290 * @param array $conf TypoScript configuration for the currently rendered object
1291 * @param array $boundingBox The bounding box the the currently rendered object
1292 * @return int The break space
1293 */
1294 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1295 if (!isset($boundingBox)) {
1296 $boundingBox = $this->calcBBox($conf);
1297 $boundingBox = $boundingBox[2];
1298 }
1299 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1300 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1301 } else {
1302 $breakSpace = $boundingBox['lineHeight'];
1303 }
1304 return $breakSpace;
1305 }
1306
1307 /*********************************************
1308 *
1309 * Other GIFBUILDER objects related to TEXT
1310 *
1311 *********************************************/
1312 /**
1313 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1314 *
1315 * @param pointer $im GDlib image pointer
1316 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1317 * @param array $workArea The current working area coordinates.
1318 * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1319 * @return void
1320 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), makeText()
1321 */
1322 public function makeOutline(&$im, $conf, $workArea, $txtConf) {
1323 $thickness = (int)$conf['thickness'];
1324 if ($thickness) {
1325 $txtConf['fontColor'] = $conf['color'];
1326 $outLineDist = MathUtility::forceIntegerInRange($thickness, 1, 2);
1327 for ($b = 1; $b <= $outLineDist; $b++) {
1328 if ($b == 1) {
1329 $it = 8;
1330 } else {
1331 $it = 16;
1332 }
1333 $outL = $this->circleOffset($b, $it);
1334 for ($a = 0; $a < $it; $a++) {
1335 $this->makeText($im, $txtConf, $this->applyOffset($workArea, $outL[$a]));
1336 }
1337 }
1338 }
1339 }
1340
1341 /**
1342 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1343 *
1344 * access private
1345 *
1346 * @param int $distance Distance
1347 * @param int $iterations Iterations.
1348 * @return array
1349 * @see makeOutline()
1350 */
1351 public function circleOffset($distance, $iterations) {
1352 $res = array();
1353 if ($distance && $iterations) {
1354 for ($a = 0; $a < $iterations; $a++) {
1355 $yOff = round(sin((2 * pi() / $iterations * ($a + 1))) * 100 * $distance);
1356 if ($yOff) {
1357 $yOff = (int)(ceil(abs(($yOff / 100))) * ($yOff / abs($yOff)));
1358 }
1359 $xOff = round(cos((2 * pi() / $iterations * ($a + 1))) * 100 * $distance);
1360 if ($xOff) {
1361 $xOff = (int)(ceil(abs(($xOff / 100))) * ($xOff / abs($xOff)));
1362 }
1363 $res[$a] = array($xOff, $yOff);
1364 }
1365 }
1366 return $res;
1367 }
1368
1369 /**
1370 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1371 *
1372 * @param pointer $im GDlib image pointer
1373 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1374 * @param array $workArea The current working area coordinates.
1375 * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1376 * @return void
1377 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), makeShadow()
1378 */
1379 public function makeEmboss(&$im, $conf, $workArea, $txtConf) {
1380 $conf['color'] = $conf['highColor'];
1381 $this->makeShadow($im, $conf, $workArea, $txtConf);
1382 $newOffset = GeneralUtility::intExplode(',', $conf['offset']);
1383 $newOffset[0] *= -1;
1384 $newOffset[1] *= -1;
1385 $conf['offset'] = implode(',', $newOffset);
1386 $conf['color'] = $conf['lowColor'];
1387 $this->makeShadow($im, $conf, $workArea, $txtConf);
1388 }
1389
1390 /**
1391 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1392 * The operation involves ImageMagick for combining.
1393 *
1394 * @param pointer $im GDlib image pointer
1395 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1396 * @param array $workArea The current working area coordinates.
1397 * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1398 * @retur void
1399 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), makeText(), makeEmboss()
1400 */
1401 public function makeShadow(&$im, $conf, $workArea, $txtConf) {
1402 $workArea = $this->applyOffset($workArea, GeneralUtility::intExplode(',', $conf['offset']));
1403 $blurRate = MathUtility::forceIntegerInRange((int)$conf['blur'], 0, 99);
1404 // No effects if ImageMagick ver. 5+
1405 if (!$blurRate || $this->NO_IM_EFFECTS) {
1406 $txtConf['fontColor'] = $conf['color'];
1407 $this->makeText($im, $txtConf, $workArea);
1408 } else {
1409 $w = imagesx($im);
1410 $h = imagesy($im);
1411 // Area around the blur used for cropping something
1412 $blurBorder = 3;
1413 $tmpStr = $this->randomName();
1414 $fileMenu = $tmpStr . '_menu.' . $this->gifExtension;
1415 $fileColor = $tmpStr . '_color.' . $this->gifExtension;
1416 $fileMask = $tmpStr . '_mask.' . $this->gifExtension;
1417 // BlurColor Image laves
1418 $blurColImg = imagecreatetruecolor($w, $h);
1419 $bcols = $this->convertColor($conf['color']);
1420 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0], $bcols[1], $bcols[2]);
1421 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1422 $this->ImageWrite($blurColImg, $fileColor);
1423 ImageDestroy($blurColImg);
1424 // The mask is made: BlurTextImage
1425 $blurTextImg = imagecreatetruecolor($w + $blurBorder * 2, $h + $blurBorder * 2);
1426 // Black background
1427 $Bcolor = ImageColorAllocate($blurTextImg, 0, 0, 0);
1428 ImageFilledRectangle($blurTextImg, 0, 0, $w + $blurBorder * 2, $h + $blurBorder * 2, $Bcolor);
1429 $txtConf['fontColor'] = 'white';
1430 $blurBordArr = array($blurBorder, $blurBorder);
1431 $this->makeText($blurTextImg, $txtConf, $this->applyOffset($workArea, $blurBordArr));
1432 // Dump to temporary file
1433 $this->ImageWrite($blurTextImg, $fileMask);
1434 // Destroy
1435 ImageDestroy($blurTextImg);
1436 $command = '';
1437 if ($this->V5_EFFECTS) {
1438 $command .= $this->v5_blur($blurRate + 1);
1439 } else {
1440 // Blurring of the mask
1441 // How many blur-commands that is executed. Min = 1;
1442 $times = ceil($blurRate / 10);
1443 // Here I boost the blur-rate so that it is 100 already at 25. The rest is done by up to 99 iterations of the blur-command.
1444 $newBlurRate = $blurRate * 4;
1445 $newBlurRate = MathUtility::forceIntegerInRange($newBlurRate, 1, 99);
1446 // Building blur-command
1447 for ($a = 0; $a < $times; $a++) {
1448 $command .= ' -blur ' . $blurRate;
1449 }
1450 }
1451 $this->imageMagickExec($fileMask, $fileMask, $command . ' +matte');
1452 // The mask is loaded again
1453 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask);
1454 // If nothing went wrong we continue with the blurred mask
1455 if ($blurTextImg_tmp) {
1456 // Cropping the border from the mask
1457 $blurTextImg = imagecreatetruecolor($w, $h);
1458 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1459 // Destroy the temporary mask
1460 ImageDestroy($blurTextImg_tmp);
1461 // Adjust the mask
1462 $intensity = 40;
1463 if ($conf['intensity']) {
1464 $intensity = MathUtility::forceIntegerInRange($conf['intensity'], 0, 100);
1465 }
1466 $intensity = ceil(255 - $intensity / 100 * 255);
1467 $this->inputLevels($blurTextImg, 0, $intensity);
1468 $opacity = MathUtility::forceIntegerInRange((int)$conf['opacity'], 0, 100);
1469 if ($opacity && $opacity < 100) {
1470 $high = ceil(255 * $opacity / 100);
1471 // Reducing levels as the opacity demands
1472 $this->outputLevels($blurTextImg, 0, $high);
1473 }
1474 // Dump the mask again
1475 $this->ImageWrite($blurTextImg, $fileMask);
1476 // Destroy the mask
1477 ImageDestroy($blurTextImg);
1478 // The pictures are combined
1479 // The main pictures is saved temporarily
1480 $this->ImageWrite($im, $fileMenu);
1481 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
1482 // The main image is loaded again...
1483 $backIm = $this->imageCreateFromFile($fileMenu);
1484 // ... and if nothing went wrong we load it onto the old one.
1485 if ($backIm) {
1486 if (!$this->saveAlphaLayer) {
1487 ImageColorTransparent($backIm, -1);
1488 }
1489 $im = $backIm;
1490 }
1491 }
1492 // Deleting temporary files;
1493 if (!$this->dontUnlinkTempFiles) {
1494 unlink($fileMenu);
1495 unlink($fileColor);
1496 unlink($fileMask);
1497 }
1498 }
1499 }
1500
1501 /****************************
1502 *
1503 * Other GIFBUILDER objects
1504 *
1505 ****************************/
1506 /**
1507 * Implements the "BOX" GIFBUILDER object
1508 *
1509 * @param pointer $im GDlib image pointer
1510 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1511 * @param array $workArea The current working area coordinates.
1512 * @return void
1513 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
1514 */
1515 public function makeBox(&$im, $conf, $workArea) {
1516 $cords = GeneralUtility::intExplode(',', $conf['dimensions'] . ',,,');
1517 $conf['offset'] = $cords[0] . ',' . $cords[1];
1518 $cords = $this->objPosition($conf, $workArea, array($cords[2], $cords[3]));
1519 $cols = $this->convertColor($conf['color']);
1520 $opacity = 0;
1521 if (isset($conf['opacity'])) {
1522 // conversion:
1523 // PHP 0 = opaque, 127 = transparent
1524 // TYPO3 100 = opaque, 0 = transparent
1525 $opacity = MathUtility::forceIntegerInRange((int)$conf['opacity'], 1, 100, 1);
1526 $opacity = abs($opacity - 100);
1527 $opacity = round(127 * $opacity / 100);
1528 }
1529 $tmpColor = ImageColorAllocateAlpha($im, $cols[0], $cols[1], $cols[2], $opacity);
1530 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0] + $cords[2] - 1, $cords[1] + $cords[3] - 1, $tmpColor);
1531 }
1532
1533 /**
1534 * Implements the "Ellipse" GIFBUILDER object
1535 * Example Typoscript:
1536 * file = GIFBUILDER
1537 * file {
1538 * XY = 200,200
1539 * format = jpg
1540 * quality = 100
1541 * 10 = ELLIPSE
1542 * 10.dimensions = 100,100,50,50
1543 * 10.color = red
1544 *
1545 * $workArea = X,Y
1546 * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
1547 *
1548 * @param pointer $im GDlib image pointer
1549 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1550 * @param array $workArea The current working area coordinates.
1551 * @return void
1552 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
1553 */
1554 public function makeEllipse(&$im, array $conf, array $workArea) {
1555 $ellipseConfiguration = GeneralUtility::intExplode(',', $conf['dimensions'] . ',,,');
1556 // Ellipse offset inside workArea (x/y)
1557 $conf['offset'] = $ellipseConfiguration[0] . ',' . $ellipseConfiguration[1];
1558 // @see objPosition
1559 $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
1560 $color = $this->convertColor($conf['color']);
1561 $fillingColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
1562 imagefilledellipse($im, $imageCoordinates[0], $imageCoordinates[1], $imageCoordinates[2], $imageCoordinates[3], $fillingColor);
1563 }
1564
1565 /**
1566 * Implements the "EFFECT" GIFBUILDER object
1567 * The operation involves ImageMagick for applying effects
1568 *
1569 * @param pointer $im GDlib image pointer
1570 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1571 * @return void
1572 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), applyImageMagickToPHPGif()
1573 */
1574 public function makeEffect(&$im, $conf) {
1575 $commands = $this->IMparams($conf['value']);
1576 if ($commands) {
1577 $this->applyImageMagickToPHPGif($im, $commands);
1578 }
1579 }
1580
1581 /**
1582 * Creating ImageMagick parameters from TypoScript property
1583 *
1584 * @param string $setup A string with effect keywords=value pairs separated by "|
1585 * @return string ImageMagick prepared parameters.
1586 * @access private
1587 * @see makeEffect()
1588 */
1589 public function IMparams($setup) {
1590 if (!trim($setup)) {
1591 return '';
1592 }
1593 $effects = explode('|', $setup);
1594 $commands = '';
1595 foreach ($effects as $val) {
1596 $pairs = explode('=', $val, 2);
1597 $value = trim($pairs[1]);
1598 $effect = strtolower(trim($pairs[0]));
1599 switch ($effect) {
1600 case 'gamma':
1601 $commands .= ' -gamma ' . doubleval($value);
1602 break;
1603 case 'blur':
1604 if (!$this->NO_IM_EFFECTS) {
1605 if ($this->V5_EFFECTS) {
1606 $commands .= $this->v5_blur($value);
1607 } else {
1608 $commands .= ' -blur ' . MathUtility::forceIntegerInRange($value, 1, 99);
1609 }
1610 }
1611 break;
1612 case 'sharpen':
1613 if (!$this->NO_IM_EFFECTS) {
1614 if ($this->V5_EFFECTS) {
1615 $commands .= $this->v5_sharpen($value);
1616 } else {
1617 $commands .= ' -sharpen ' . MathUtility::forceIntegerInRange($value, 1, 99);
1618 }
1619 }
1620 break;
1621 case 'rotate':
1622 $commands .= ' -rotate ' . MathUtility::forceIntegerInRange($value, 0, 360);
1623 break;
1624 case 'solarize':
1625 $commands .= ' -solarize ' . MathUtility::forceIntegerInRange($value, 0, 99);
1626 break;
1627 case 'swirl':
1628 $commands .= ' -swirl ' . MathUtility::forceIntegerInRange($value, 0, 1000);
1629 break;
1630 case 'wave':
1631 $params = GeneralUtility::intExplode(',', $value);
1632 $commands .= ' -wave ' . MathUtility::forceIntegerInRange($params[0], 0, 99) . 'x' . MathUtility::forceIntegerInRange($params[1], 0, 99);
1633 break;
1634 case 'charcoal':
1635 $commands .= ' -charcoal ' . MathUtility::forceIntegerInRange($value, 0, 100);
1636 break;
1637 case 'gray':
1638 $commands .= ' -colorspace GRAY';
1639 break;
1640 case 'edge':
1641 $commands .= ' -edge ' . MathUtility::forceIntegerInRange($value, 0, 99);
1642 break;
1643 case 'emboss':
1644 $commands .= ' -emboss';
1645 break;
1646 case 'flip':
1647 $commands .= ' -flip';
1648 break;
1649 case 'flop':
1650 $commands .= ' -flop';
1651 break;
1652 case 'colors':
1653 $commands .= ' -colors ' . MathUtility::forceIntegerInRange($value, 2, 255);
1654 break;
1655 case 'shear':
1656 $commands .= ' -shear ' . MathUtility::forceIntegerInRange($value, -90, 90);
1657 break;
1658 case 'invert':
1659 $commands .= ' -negate';
1660 break;
1661 }
1662 }
1663 return $commands;
1664 }
1665
1666 /**
1667 * Implements the "ADJUST" GIFBUILDER object
1668 *
1669 * @param pointer $im GDlib image pointer
1670 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1671 * @return void
1672 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1673 */
1674 public function adjust(&$im, $conf) {
1675 $setup = $conf['value'];
1676 if (!trim($setup)) {
1677 return '';
1678 }
1679 $effects = explode('|', $setup);
1680 foreach ($effects as $val) {
1681 $pairs = explode('=', $val, 2);
1682 $value = trim($pairs[1]);
1683 $effect = strtolower(trim($pairs[0]));
1684 switch ($effect) {
1685 case 'inputlevels':
1686 // low,high
1687 $params = GeneralUtility::intExplode(',', $value);
1688 $this->inputLevels($im, $params[0], $params[1]);
1689 break;
1690 case 'outputlevels':
1691 $params = GeneralUtility::intExplode(',', $value);
1692 $this->outputLevels($im, $params[0], $params[1]);
1693 break;
1694 case 'autolevels':
1695 $this->autoLevels($im);
1696 break;
1697 }
1698 }
1699 }
1700
1701 /**
1702 * Implements the "CROP" GIFBUILDER object
1703 *
1704 * @param pointer $im GDlib image pointer
1705 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1706 * @return void
1707 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
1708 */
1709 public function crop(&$im, $conf) {
1710 // Clears workArea to total image
1711 $this->setWorkArea('');
1712 $cords = GeneralUtility::intExplode(',', $conf['crop'] . ',,,');
1713 $conf['offset'] = $cords[0] . ',' . $cords[1];
1714 $cords = $this->objPosition($conf, $this->workArea, array($cords[2], $cords[3]));
1715 $newIm = imagecreatetruecolor($cords[2], $cords[3]);
1716 $cols = $this->convertColor($conf['backColor'] ? $conf['backColor'] : $this->setup['backColor']);
1717 $Bcolor = ImageColorAllocate($newIm, $cols[0], $cols[1], $cols[2]);
1718 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1719 $newConf = array();
1720 $workArea = array(0, 0, $cords[2], $cords[3]);
1721 if ($cords[0] < 0) {
1722 $workArea[0] = abs($cords[0]);
1723 } else {
1724 $newConf['offset'] = -$cords[0];
1725 }
1726 if ($cords[1] < 0) {
1727 $workArea[1] = abs($cords[1]);
1728 } else {
1729 $newConf['offset'] .= ',' . -$cords[1];
1730 }
1731 $this->copyGifOntoGif($newIm, $im, $newConf, $workArea);
1732 $im = $newIm;
1733 $this->w = imagesx($im);
1734 $this->h = imagesy($im);
1735 // Clears workArea to total image
1736 $this->setWorkArea('');
1737 }
1738
1739 /**
1740 * Implements the "SCALE" GIFBUILDER object
1741 *
1742 * @param pointer $im GDlib image pointer
1743 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1744 * @return void
1745 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
1746 */
1747 public function scale(&$im, $conf) {
1748 if ($conf['width'] || $conf['height'] || $conf['params']) {
1749 $tmpStr = $this->randomName();
1750 $theFile = $tmpStr . '.' . $this->gifExtension;
1751 $this->ImageWrite($im, $theFile);
1752 $theNewFile = $this->imageMagickConvert($theFile, $this->gifExtension, $conf['width'], $conf['height'], $conf['params']);
1753 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1754 if ($tmpImg) {
1755 ImageDestroy($im);
1756 $im = $tmpImg;
1757 $this->w = imagesx($im);
1758 $this->h = imagesy($im);
1759 // Clears workArea to total image
1760 $this->setWorkArea('');
1761 }
1762 if (!$this->dontUnlinkTempFiles) {
1763 unlink($theFile);
1764 if ($theNewFile[3] && $theNewFile[3] != $theFile) {
1765 unlink($theNewFile[3]);
1766 }
1767 }
1768 }
1769 }
1770
1771 /**
1772 * Implements the "WORKAREA" GIFBUILDER object when setting it
1773 * Setting internal working area boundaries (->workArea)
1774 *
1775 * @param string $workArea Working area dimensions, comma separated
1776 * @return void
1777 * @access private
1778 * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::make()
1779 */
1780 public function setWorkArea($workArea) {
1781 $this->workArea = GeneralUtility::intExplode(',', $workArea);
1782 $this->workArea = $this->applyOffset($this->workArea, $this->OFFSET);
1783 if (!$this->workArea[2]) {
1784 $this->workArea[2] = $this->w;
1785 }
1786 if (!$this->workArea[3]) {
1787 $this->workArea[3] = $this->h;
1788 }
1789 }
1790
1791 /*************************
1792 *
1793 * Adjustment functions
1794 *
1795 ************************/
1796 /**
1797 * Apply auto-levels to input image pointer
1798 *
1799 * @param int $im GDlib Image Pointer
1800 * @return void
1801 */
1802 public function autolevels(&$im) {
1803 $totalCols = ImageColorsTotal($im);
1804 $min = 255;
1805 $max = 0;
1806 for ($c = 0; $c < $totalCols; $c++) {
1807 $cols = ImageColorsForIndex($im, $c);
1808 $grayArr[] = round(($cols['red'] + $cols['green'] + $cols['blue']) / 3);
1809 }
1810 $min = min($grayArr);
1811 $max = max($grayArr);
1812 $delta = $max - $min;
1813 if ($delta) {
1814 for ($c = 0; $c < $totalCols; $c++) {
1815 $cols = ImageColorsForIndex($im, $c);
1816 $cols['red'] = floor(($cols['red'] - $min) / $delta * 255);
1817 $cols['green'] = floor(($cols['green'] - $min) / $delta * 255);
1818 $cols['blue'] = floor(($cols['blue'] - $min) / $delta * 255);
1819 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1820 }
1821 }
1822 }
1823
1824 /**
1825 * Apply output levels to input image pointer (decreasing contrast)
1826 *
1827 * @param int $im GDlib Image Pointer
1828 * @param int $low The "low" value (close to 0)
1829 * @param int $high The "high" value (close to 255)
1830 * @param bool $swap If swap, then low and high are swapped. (Useful for negated masks...)
1831 * @return void
1832 */
1833 public function outputLevels(&$im, $low, $high, $swap = '') {
1834 if ($low < $high) {
1835 $low = MathUtility::forceIntegerInRange($low, 0, 255);
1836 $high = MathUtility::forceIntegerInRange($high, 0, 255);
1837 if ($swap) {
1838 $temp = $low;
1839 $low = 255 - $high;
1840 $high = 255 - $temp;
1841 }
1842 $delta = $high - $low;
1843 $totalCols = ImageColorsTotal($im);
1844 for ($c = 0; $c < $totalCols; $c++) {
1845 $cols = ImageColorsForIndex($im, $c);
1846 $cols['red'] = $low + floor($cols['red'] / 255 * $delta);
1847 $cols['green'] = $low + floor($cols['green'] / 255 * $delta);
1848 $cols['blue'] = $low + floor($cols['blue'] / 255 * $delta);
1849 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1850 }
1851 }
1852 }
1853
1854 /**
1855 * Apply input levels to input image pointer (increasing contrast)
1856 *
1857 * @param int $im GDlib Image Pointer
1858 * @param int $low The "low" value (close to 0)
1859 * @param int $high The "high" value (close to 255)
1860 * @return void
1861 */
1862 public function inputLevels(&$im, $low, $high) {
1863 if ($low < $high) {
1864 $low = MathUtility::forceIntegerInRange($low, 0, 255);
1865 $high = MathUtility::forceIntegerInRange($high, 0, 255);
1866 $delta = $high - $low;
1867 $totalCols = ImageColorsTotal($im);
1868 for ($c = 0; $c < $totalCols; $c++) {
1869 $cols = ImageColorsForIndex($im, $c);
1870 $cols['red'] = MathUtility::forceIntegerInRange(($cols['red'] - $low) / $delta * 255, 0, 255);
1871 $cols['green'] = MathUtility::forceIntegerInRange(($cols['green'] - $low) / $delta * 255, 0, 255);
1872 $cols['blue'] = MathUtility::forceIntegerInRange(($cols['blue'] - $low) / $delta * 255, 0, 255);
1873 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1874 }
1875 }
1876 }
1877
1878 /**
1879 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1880 *
1881 * @param string $file Image file to reduce
1882 * @param int $cols Number of colors to reduce the image to.
1883 * @return string Reduced file
1884 */
1885 public function IMreduceColors($file, $cols) {
1886 $fI = GeneralUtility::split_fileref($file);
1887 $ext = strtolower($fI['fileext']);
1888 $result = $this->randomName() . '.' . $ext;
1889 if (($reduce = MathUtility::forceIntegerInRange($cols, 0, $ext == 'gif' ? 256 : $this->truecolorColors, 0)) > 0) {
1890 $params = ' -colors ' . $reduce;
1891 if ($reduce <= 256) {
1892 $params .= ' -type Palette';
1893 }
1894 if ($ext == 'png' && $reduce <= 256) {
1895 $prefix = 'png8:';
1896 }
1897 $this->imageMagickExec($file, $prefix . $result, $params);
1898 if ($result) {
1899 return $result;
1900 }
1901 }
1902 return '';
1903 }
1904
1905 /*********************************
1906 *
1907 * GIFBUILDER Helper functions
1908 *
1909 *********************************/
1910 /**
1911 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1912 * Use PATH_site unless we are in the backend.
1913 * Call it by \TYPO3\CMS\Core\Imaging\GraphicalFunctions::prependAbsolutePath()
1914 *
1915 * @param string $fontFile The font file
1916 * @return string The font file with absolute path.
1917 */
1918 public function prependAbsolutePath($fontFile) {
1919 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript) . '/' : PATH_site;
1920 $fontFile = GeneralUtility::isAbsPath($fontFile) ? $fontFile : GeneralUtility::resolveBackPath($absPath . $fontFile);
1921 return $fontFile;
1922 }
1923
1924 /**
1925 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1926 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1927 *
1928 * @param int $factor The sharpening factor, 0-100 (effectively in 10 steps)
1929 * @return string The sharpening command, eg. " -sharpen 3x4
1930 * @see makeText(), IMparams(), v5_blur()
1931 */
1932 public function v5_sharpen($factor) {
1933 $factor = MathUtility::forceIntegerInRange(ceil($factor / 10), 0, 10);
1934 $sharpenArr = explode(',', ',' . $this->im5fx_sharpenSteps);
1935 $sharpenF = trim($sharpenArr[$factor]);
1936 if ($sharpenF) {
1937 $cmd = ' -sharpen ' . $sharpenF;
1938 return $cmd;
1939 }
1940 }
1941
1942 /**
1943 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
1944 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
1945 *
1946 * @param int $factor The blurring factor, 0-100 (effectively in 10 steps)
1947 * @return string The blurring command, eg. " -blur 3x4
1948 * @see makeText(), IMparams(), v5_sharpen()
1949 */
1950 public function v5_blur($factor) {
1951 $factor = MathUtility::forceIntegerInRange(ceil($factor / 10), 0, 10);
1952 $blurArr = explode(',', ',' . $this->im5fx_blurSteps);
1953 $blurF = trim($blurArr[$factor]);
1954 if ($blurF) {
1955 $cmd = ' -blur ' . $blurF;
1956 return $cmd;
1957 }
1958 }
1959
1960 /**
1961 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
1962 * Used by functions in this class to create truely temporary files for the on-the-fly processing. These files will most likely be deleted right away.
1963 *
1964 * @return string
1965 */
1966 public function randomName() {
1967 $this->createTempSubDir('temp/');
1968 return $this->tempPath . 'temp/' . md5(uniqid('', TRUE));
1969 }
1970
1971 /**
1972 * Applies offset value to coordinated in $cords.
1973 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
1974 *
1975 * @param array $cords Integer coordinates in key 0/1
1976 * @param array $OFFSET Offset values in key 0/1
1977 * @return array Modified $cords array
1978 */
1979 public function applyOffset($cords, $OFFSET) {
1980 $cords[0] = (int)$cords[0] + (int)$OFFSET[0];
1981 $cords[1] = (int)$cords[1] + (int)$OFFSET[1];
1982 return $cords;
1983 }
1984
1985 /**
1986 * Converts a "HTML-color" TypoScript datatype to RGB-values.
1987 * Default is 0,0,0
1988 *
1989 * @param string $string "HTML-color" data type string, eg. 'red', '#ffeedd' or '255,0,255'. You can also add a modifying operator afterwards. There are two options: "255,0,255 : 20" - will add 20 to values, result is "255,20,255". Or "255,0,255 : *1.23" which will multiply all RGB values with 1.23
1990 * @return array RGB values in key 0/1/2 of the array
1991 */
1992 public function convertColor($string) {
1993 $col = array();
1994 $cParts = explode(':', $string, 2);
1995 // Finding the RGB definitions of the color:
1996 $string = $cParts[0];
1997 if (strstr($string, '#')) {
1998 $string = preg_replace('/[^A-Fa-f0-9]*/', '', $string);
1999 $col[] = HexDec(substr($string, 0, 2));
2000 $col[] = HexDec(substr($string, 2, 2));
2001 $col[] = HexDec(substr($string, 4, 2));
2002 } elseif (strstr($string, ',')) {
2003 $string = preg_replace('/[^,0-9]*/', '', $string);
2004 $strArr = explode(',', $string);
2005 $col[] = (int)$strArr[0];
2006 $col[] = (int)$strArr[1];
2007 $col[] = (int)$strArr[2];
2008 } else {
2009 $string = strtolower(trim($string));
2010 if ($this->colMap[$string]) {
2011 $col = $this->colMap[$string];
2012 } else {
2013 $col = array(0, 0, 0);
2014 }
2015 }
2016 // ... and possibly recalculating the value
2017 if (trim($cParts[1])) {
2018 $cParts[1] = trim($cParts[1]);
2019 if ($cParts[1][0] === '*') {
2020 $val = doubleval(substr($cParts[1], 1));
2021 $col[0] = MathUtility::forceIntegerInRange($col[0] * $val, 0, 255);
2022 $col[1] = MathUtility::forceIntegerInRange($col[1] * $val, 0, 255);
2023 $col[2] = MathUtility::forceIntegerInRange($col[2] * $val, 0, 255);
2024 } else {
2025 $val = (int)$cParts[1];
2026 $col[0] = MathUtility::forceIntegerInRange($col[0] + $val, 0, 255);
2027 $col[1] = MathUtility::forceIntegerInRange($col[1] + $val, 0, 255);
2028 $col[2] = MathUtility::forceIntegerInRange($col[2] + $val, 0, 255);
2029 }
2030 }
2031 return $col;
2032 }
2033
2034 /**
2035 * Recode string
2036 * Used with text strings for fonts when languages has other character sets.
2037 *
2038 * @param string The text to recode
2039 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
2040 */
2041 public function recodeString($string) {
2042 // Recode string to UTF-8 from $this->nativeCharset:
2043 if ($this->nativeCharset && $this->nativeCharset != 'utf-8') {
2044 // Convert to UTF-8
2045 $string = $this->csConvObj->utf8_encode($string, $this->nativeCharset);
2046 }
2047 return $string;
2048 }
2049
2050 /**
2051 * Split a string into an array of individual characters
2052 * The function will look at $this->nativeCharset and if that is set, the input string is expected to be UTF-8 encoded, possibly with entities in it. Otherwise the string is supposed to be a single-byte charset which is just splitted by a for-loop.
2053 *
2054 * @param string $theText The text string to split
2055 * @param bool $returnUnicodeNumber Return Unicode numbers instead of chars.
2056 * @return array Numerical array with a char as each value.
2057 */
2058 public function singleChars($theText, $returnUnicodeNumber = FALSE) {
2059 if ($this->nativeCharset) {
2060 // Get an array of separated UTF-8 chars
2061 return $this->csConvObj->utf8_to_numberarray($theText, 1, $returnUnicodeNumber ? 0 : 1);
2062 } else {
2063 $output = array();
2064 $c = strlen($theText);
2065 for ($a = 0; $a < $c; $a++) {
2066 $output[] = substr($theText, $a, 1);
2067 }
2068 return $output;
2069 }
2070 }
2071
2072 /**
2073 * Create an array with object position/boundaries based on input TypoScript configuration (such as the "align" property is used), the work area definition and $BB array
2074 *
2075 * @param array $conf TypoScript configuration for a GIFBUILDER object
2076 * @param array makeBox Workarea definition
2077 * @param array $BB BB (Bounding box) array. Not just used for TEXT objects but also for others
2078 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2079 * @access private
2080 * @see copyGifOntoGif(), makeBox(), crop()
2081 */
2082 public function objPosition($conf, $workArea, $BB) {
2083 // offset, align, valign, workarea
2084 $result = array();
2085 $result[2] = $BB[0];
2086 $result[3] = $BB[1];
2087 $w = $workArea[2];
2088 $h = $workArea[3];
2089 $align = explode(',', $conf['align']);
2090 $align[0] = strtolower(substr(trim($align[0]), 0, 1));
2091 $align[1] = strtolower(substr(trim($align[1]), 0, 1));
2092 switch ($align[0]) {
2093 case 'r':
2094 $result[0] = $w - $result[2];
2095 break;
2096 case 'c':
2097 $result[0] = round(($w - $result[2]) / 2);
2098 break;
2099 default:
2100 $result[0] = 0;
2101 }
2102 switch ($align[1]) {
2103 case 'b':
2104 // y pos
2105 $result[1] = $h - $result[3];
2106 break;
2107 case 'c':
2108 $result[1] = round(($h - $result[3]) / 2);
2109 break;
2110 default:
2111 $result[1] = 0;
2112 }
2113 $result = $this->applyOffset($result, GeneralUtility::intExplode(',', $conf['offset']));
2114 $result = $this->applyOffset($result, $workArea);
2115 return $result;
2116 }
2117
2118 /***********************************
2119 *
2120 * Scaling, Dimensions of images
2121 *
2122 ***********************************/
2123 /**
2124 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2125 *
2126 * @param string $imagefile The image filepath
2127 * @param string $newExt New extension, eg. "gif", "png", "jpg", "tif". If $newExt is NOT set, the new imagefile will be of the original format. If newExt = 'WEB' then one of the web-formats is applied.
2128 * @param string $w Width. $w / $h is optional. If only one is given the image is scaled proportionally. If an 'm' exists in the $w or $h and if both are present the $w and $h is regarded as the Maximum w/h and the proportions will be kept
2129 * @param string $h Height. See $w
2130 * @param string $params Additional ImageMagick parameters.
2131 * @param string $frame Refers to which frame-number to select in the image. '' or 0 will select the first frame, 1 will select the next and so on...
2132 * @param array $options An array with options passed to getImageScale (see this function).
2133 * @param bool $mustCreate If set, then another image than the input imagefile MUST be returned. Otherwise you can risk that the input image is good enough regarding messures etc and is of course not rendered to a new, temporary file in typo3temp/. But this option will force it to.
2134 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2135 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2136 */
2137 public function imageMagickConvert($imagefile, $newExt = '', $w = '', $h = '', $params = '', $frame = '', $options = array(), $mustCreate = FALSE) {
2138 if ($this->NO_IMAGE_MAGICK) {
2139 // Returning file info right away
2140 return $this->getImageDimensions($imagefile);
2141 }
2142 if ($info = $this->getImageDimensions($imagefile)) {
2143 $newExt = strtolower(trim($newExt));
2144 // If no extension is given the original extension is used
2145 if (!$newExt) {
2146 $newExt = $info[2];
2147 }
2148 if ($newExt == 'web') {
2149 if (GeneralUtility::inList($this->webImageExt, $info[2])) {
2150 $newExt = $info[2];
2151 } else {
2152 $newExt = $this->gif_or_jpg($info[2], $info[0], $info[1]);
2153 if (!$params) {
2154 $params = $this->cmds[$newExt];
2155 }
2156 }
2157 }
2158 if (GeneralUtility::inList($this->imageFileExt, $newExt)) {
2159 if (strstr($w . $h, 'm')) {
2160 $max = 1;
2161 } else {
2162 $max = 0;
2163 }
2164 $data = $this->getImageScale($info, $w, $h, $options);
2165 $w = $data['origW'];
2166 $h = $data['origH'];
2167 // If no conversion should be performed
2168 // this flag is TRUE if the width / height does NOT dictate
2169 // the image to be scaled!! (that is if no width / height is
2170 // given or if the destination w/h matches the original image
2171 // dimensions or if the option to not scale the image is set)
2172 $noScale = !$w && !$h || $data[0] == $info[0] && $data[1] == $info[1] || $options['noScale'];
2173 if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
2174 // Set the new width and height before returning,
2175 // if the noScale option is set
2176 if (!empty($options['noScale'])) {
2177 $info[0] = $data[0];
2178 $info[1] = $data[1];
2179 }
2180 $info[3] = $imagefile;
2181 return $info;
2182 }
2183 $info[0] = $data[0];
2184 $info[1] = $data[1];
2185 $frame = $this->noFramePrepended ? '' : (int)$frame;
2186 if (!$params) {
2187 $params = $this->cmds[$newExt];
2188 }
2189 // Cropscaling:
2190 if ($data['crs']) {
2191 if (!$data['origW']) {
2192 $data['origW'] = $data[0];
2193 }
2194 if (!$data['origH']) {
2195 $data['origH'] = $data[1];
2196 }
2197 $offsetX = (int)(($data[0] - $data['origW']) * ($data['cropH'] + 100) / 200);
2198 $offsetY = (int)(($data[1] - $data['origH']) * ($data['cropV'] + 100) / 200);
2199 $params .= ' -crop ' . $data['origW'] . 'x' . $data['origH'] . '+' . $offsetX . '+' . $offsetY . '! ';
2200 }
2201 $command = $this->scalecmd . ' ' . $info[0] . 'x' . $info[1] . '! ' . $params . ' ';
2202 $cropscale = $data['crs'] ? 'crs-V' . $data['cropV'] . 'H' . $data['cropH'] : '';
2203 if ($this->alternativeOutputKey) {
2204 $theOutputName = GeneralUtility::shortMD5($command . $cropscale . basename($imagefile) . $this->alternativeOutputKey . '[' . $frame . ']');
2205 } else {
2206 $theOutputName = GeneralUtility::shortMD5($command . $cropscale . $imagefile . filemtime($imagefile) . '[' . $frame . ']');
2207 }
2208 if ($this->imageMagickConvert_forceFileNameBody) {
2209 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
2210 $this->imageMagickConvert_forceFileNameBody = '';
2211 }
2212 // Making the temporary filename:
2213 $this->createTempSubDir('pics/');
2214 $output = $this->absPrefix . $this->tempPath . 'pics/' . $this->filenamePrefix . $theOutputName . '.' . $newExt;
2215 // Register temporary filename:
2216 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2217 if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
2218 $this->imageMagickExec($imagefile, $output, $command, $frame);
2219 }
2220 if (file_exists($output)) {
2221 $info[3] = $output;
2222 $info[2] = $newExt;
2223 // params could realisticly change some imagedata!
2224 if ($params) {
2225 $info = $this->getImageDimensions($info[3]);
2226 }
2227 if ($info[2] == $this->gifExtension && !$this->dontCompress) {
2228 // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2229 GeneralUtility::gif_compress($info[3], '');
2230 }
2231 return $info;
2232 }
2233 }
2234 }
2235 }
2236
2237 /**
2238 * Gets the input image dimensions.
2239 *
2240 * @param string $imageFile The image filepath
2241 * @return array|NULL Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2242 * @see imageMagickConvert(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource()
2243 */
2244 public function getImageDimensions($imageFile) {
2245 preg_match('/([^\\.]*)$/', $imageFile, $reg);
2246 if (file_exists($imageFile) && GeneralUtility::inList($this->imageFileExt, strtolower($reg[0]))) {
2247 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2248 return $returnArr;
2249 } else {
2250 if ($temp = @getImageSize($imageFile)) {
2251 $returnArr = array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2252 } else {
2253 $returnArr = $this->imageMagickIdentify($imageFile);
2254 }
2255 if ($returnArr) {
2256 $this->cacheImageDimensions($returnArr);
2257 return $returnArr;
2258 }
2259 }
2260 }
2261 return NULL;
2262 }
2263
2264 /**
2265 * Cache the result of the getImageDimensions function into the database. Does not check if the
2266 * file exists!
2267 *
2268 * @param array $identifyResult Result of the getImageDimensions function
2269 * @return bool TRUE if operation was successful
2270 */
2271 public function cacheImageDimensions($identifyResult) {
2272 // Create md5 hash of filemtime and filesize
2273 $fileStatus = stat($identifyResult[3]);
2274 $md5Hash = md5($fileStatus['mtime'] . $fileStatus['size']);
2275 $result = FALSE;
2276 if ($md5Hash) {
2277 $fieldArray = array(
2278 'md5hash' => $md5Hash,
2279 'md5filename' => md5($identifyResult[3]),
2280 'tstamp' => $GLOBALS['EXEC_TIME'],
2281 'filename' => $identifyResult[3],
2282 'imagewidth' => $identifyResult[0],
2283 'imageheight' => $identifyResult[1]
2284 );
2285 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_imagesizes', $fieldArray);
2286 if (!($err = $GLOBALS['TYPO3_DB']->sql_error())) {
2287 $result = TRUE;
2288 }
2289 }
2290 return $result;
2291 }
2292
2293 /**
2294 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2295 *
2296 * @param string $imageFile The image filepath
2297 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2298 */
2299 public function getCachedImageDimensions($imageFile) {
2300 // Create md5 hash of filemtime and filesize
2301 $fileStatus = stat($imageFile);
2302 $md5Hash = md5($fileStatus['mtime'] . $fileStatus['size']);
2303 $cachedImageDimensions = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('md5hash, md5filename, imagewidth, imageheight', 'cache_imagesizes', 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(md5($imageFile), 'cache_imagesizes'));
2304 $result = FALSE;
2305 if (is_array($cachedImageDimensions)) {
2306 if ($cachedImageDimensions['md5hash'] != $md5Hash) {
2307 // File has changed, delete the row
2308 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_imagesizes', 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($cachedImageDimensions['md5filename'], 'cache_imagesizes'));
2309 } else {
2310 preg_match('/([^\\.]*)$/', $imageFile, $imageExtension);
2311 $result = array(
2312 (int)$cachedImageDimensions['imagewidth'],
2313 (int)$cachedImageDimensions['imageheight'],
2314 strtolower($imageExtension[0]),
2315 $imageFile
2316 );
2317 }
2318 }
2319 return $result;
2320 }
2321
2322 /**
2323 * Get numbers for scaling the image based on input
2324 *
2325 * @param array $info Current image information: Width, Height etc.
2326 * @param int $w "required" width
2327 * @param int $h "required" height
2328 * @param array $options Options: Keys are like "maxW", "maxH", "minW", "minH
2329 * @return array
2330 * @access private
2331 * @see imageMagickConvert()
2332 */
2333 public function getImageScale($info, $w, $h, $options) {
2334 if (strstr($w . $h, 'm')) {
2335 $max = 1;
2336 } else {
2337 $max = 0;
2338 }
2339 if (strstr($w . $h, 'c')) {
2340 $out['cropH'] = (int)substr(strstr($w, 'c'), 1);
2341 $out['cropV'] = (int)substr(strstr($h, 'c'), 1);
2342 $crs = TRUE;
2343 } else {
2344 $crs = FALSE;
2345 }
2346 $out['crs'] = $crs;
2347 $w = (int)$w;
2348 $h = (int)$h;
2349 // If there are max-values...
2350 if (!empty($options['maxW'])) {
2351 // If width is given...
2352 if ($w) {
2353 if ($w > $options['maxW']) {
2354 $w = $options['maxW'];
2355 // Height should follow
2356 $max = 1;
2357 }
2358 } else {
2359 if ($info[0] > $options['maxW']) {
2360 $w = $options['maxW'];
2361 // Height should follow
2362 $max = 1;
2363 }
2364 }
2365 }
2366 if (!empty($options['maxH'])) {
2367 // If height is given...
2368 if ($h) {
2369 if ($h > $options['maxH']) {
2370 $h = $options['maxH'];
2371 // Height should follow
2372 $max = 1;
2373 }
2374 } else {
2375 // Changed [0] to [1] 290801
2376 if ($info[1] > $options['maxH']) {
2377 $h = $options['maxH'];
2378 // Height should follow
2379 $max = 1;
2380 }
2381 }
2382 }
2383 $out['origW'] = $w;
2384 $out['origH'] = $h;
2385 $out['max'] = $max;
2386 if (!$this->mayScaleUp) {
2387 if ($w > $info[0]) {
2388 $w = $info[0];
2389 }
2390 if ($h > $info[1]) {
2391 $h = $info[1];
2392 }
2393 }
2394 // If scaling should be performed
2395 if ($w || $h) {
2396 if ($w && !$h) {
2397 $info[1] = ceil($info[1] * ($w / $info[0]));
2398 $info[0] = $w;
2399 }
2400 if (!$w && $h) {
2401 $info[0] = ceil($info[0] * ($h / $info[1]));
2402 $info[1] = $h;
2403 }
2404 if ($w && $h) {
2405 if ($max) {
2406 $ratio = $info[0] / $info[1];
2407 if ($h * $ratio > $w) {
2408 $h = round($w / $ratio);
2409 } else {
2410 $w = round($h * $ratio);
2411 }
2412 }
2413 if ($crs) {
2414 $ratio = $info[0] / $info[1];
2415 if ($h * $ratio < $w) {
2416 $h = round($w / $ratio);
2417 } else {
2418 $w = round($h * $ratio);
2419 }
2420 }
2421 $info[0] = $w;
2422 $info[1] = $h;
2423 }
2424 }
2425 $out[0] = $info[0];
2426 $out[1] = $info[1];
2427 // Set minimum-measures!
2428 if (isset($options['minW']) && $out[0] < $options['minW']) {
2429 if (($max || $crs) && $out[0]) {
2430 $out[1] = round($out[1] * $options['minW'] / $out[0]);
2431 }
2432 $out[0] = $options['minW'];
2433 }
2434 if (isset($options['minH']) && $out[1] < $options['minH']) {
2435 if (($max || $crs) && $out[1]) {
2436 $out[0] = round($out[0] * $options['minH'] / $out[1]);
2437 }
2438 $out[1] = $options['minH'];
2439 }
2440 return $out;
2441 }
2442
2443 /**
2444 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2445 *
2446 * @param string $output Output imagefile
2447 * @param string $orig Original basis file
2448 * @return bool Returns TRUE if the file is already being made; thus "TRUE" means "Don't render the image again
2449 * @access private
2450 */
2451 public function file_exists_typo3temp_file($output, $orig = '') {
2452 if ($this->enable_typo3temp_db_tracking) {
2453 // If file exists, then we return immediately
2454 if (file_exists($output)) {
2455 return 1;
2456 } else {
2457 // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2458 $md5Hash = md5($output);
2459 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30));
2460 // If there was a record, the image is being generated by another process (we assume)
2461 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2462 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2463 if (is_object($GLOBALS['TSFE'])) {
2464 $GLOBALS['TSFE']->set_no_cache('Another process renders this file now: ' . $output);
2465 }
2466 // ...so we set no_cache, because we dont want this page (which will NOT display an image...!) to be cached! (Only a page with the correct image on...)
2467 if (is_object($GLOBALS['TT'])) {
2468 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: ' . $output);
2469 }
2470 // Return 'success - 2'
2471 return 2;
2472 } else {
2473 // If the current time is more than 30 seconds since this record was written, we clear the record, write a new and render the image.
2474 $insertFields = array(
2475 'md5hash' => $md5Hash,
2476 'tstamp' => $GLOBALS['EXEC_TIME'],
2477 'filename' => $output,
2478 'orig_filename' => $orig
2479 );
2480 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2481 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2482 if (is_object($GLOBALS['TT'])) {
2483 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: ' . $output);
2484 }
2485 return 0;
2486 }
2487 }
2488 } else {
2489 return file_exists($output);
2490 }
2491 }
2492
2493 /***********************************
2494 *
2495 * ImageMagick API functions
2496 *
2497 ***********************************/
2498 /**
2499 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2500 * Using ImageMagick
2501 *
2502 * @param string $imagefile The relative (to PATH_site) image filepath
2503 * @return array
2504 */
2505 public function imageMagickIdentify($imagefile) {
2506 if (!$this->NO_IMAGE_MAGICK) {
2507 $frame = $this->noFramePrepended ? '' : '[0]';
2508 $cmd = GeneralUtility::imageMagickCommand('identify', $this->wrapFileName($imagefile) . $frame);
2509 $returnVal = array();
2510 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd, $returnVal);
2511 $splitstring = array_pop($returnVal);
2512 $this->IM_commands[] = array('identify', $cmd, $splitstring);
2513 if ($splitstring) {
2514 preg_match('/([^\\.]*)$/', $imagefile, $reg);
2515 $splitinfo = explode(' ', $splitstring);
2516 foreach ($splitinfo as $key => $val) {
2517 $temp = '';
2518 if ($val) {
2519 $temp = explode('x', $val);
2520 }
2521 if ((int)$temp[0] && (int)$temp[1]) {
2522 $dim = $temp;
2523 break;
2524 }
2525 }
2526 if ($dim[0] && $dim[1]) {
2527 return array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2528 }
2529 }
2530 }
2531 }
2532
2533 /**
2534 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2535 * Can be used for many things, mostly scaling and effects.
2536 *
2537 * @param string $input The relative (to PATH_site) image filepath, input file (read from)
2538 * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
2539 * @param string $params ImageMagick parameters
2540 * @param int $frame Optional, refers to which frame-number to select in the image. '' or 0
2541 * @return string The result of a call to PHP function "exec()
2542 */
2543 public function imageMagickExec($input, $output, $params, $frame = 0) {
2544 if (!$this->NO_IMAGE_MAGICK) {
2545 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2546 // select a specific page of the image (by default this will be the first page)
2547 if (!$this->noFramePrepended) {
2548 $frame = '[' . (int)$frame . ']';
2549 } else {
2550 $frame = '';
2551 }
2552 $cmd = GeneralUtility::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input . $frame) . ' ' . $this->wrapFileName($output));
2553 $this->IM_commands[] = array($output, $cmd);
2554 $ret = \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
2555 // Change the permissions of the file
2556 GeneralUtility::fixPermissions($output);
2557 return $ret;
2558 }
2559 }
2560
2561 /**
2562 * Executes a ImageMagick "combine" (or composite in newer times) on four filenames - $input, $overlay and $mask as input files and $output as the output filename (written to)
2563 * Can be used for many things, mostly scaling and effects.
2564 *
2565 * @param string $input The relative (to PATH_site) image filepath, bottom file
2566 * @param string $overlay The relative (to PATH_site) image filepath, overlay file (top)
2567 * @param string $mask The relative (to PATH_site) image filepath, the mask file (grayscale)
2568 * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
2569 * @param bool $handleNegation
2570 * @return void
2571 */
2572 public function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) {
2573 if (!$this->NO_IMAGE_MAGICK) {
2574 $params = '-colorspace GRAY +matte';
2575 $theMask = $this->randomName() . '.' . $this->gifExtension;
2576 $this->imageMagickExec($mask, $theMask, $params);
2577 $cmd = GeneralUtility::imageMagickCommand('combine', '-compose over +matte ' . $this->wrapFileName($input) . ' ' . $this->wrapFileName($overlay) . ' ' . $this->wrapFileName($theMask) . ' ' . $this->wrapFileName($output));
2578 // +matte = no alpha layer in output
2579 $this->IM_commands[] = array($output, $cmd);
2580 $ret = \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
2581 // Change the permissions of the file
2582 GeneralUtility::fixPermissions($output);
2583 if (is_file($theMask)) {
2584 @unlink($theMask);
2585 }
2586 return $ret;
2587 }
2588 }
2589
2590 /**
2591 * Escapes a file name so it can safely be used on the command line.
2592 *
2593 * @param string $inputName filename to safeguard, must not be empty
2594 * @return string $inputName escaped as needed
2595 */
2596 protected function wrapFileName($inputName) {
2597 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2598 $currentLocale = setlocale(LC_CTYPE, 0);
2599 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
2600 }
2601 $escapedInputName = escapeshellarg($inputName);
2602 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2603 setlocale(LC_CTYPE, $currentLocale);
2604 }
2605 return $escapedInputName;
2606 }
2607
2608 /***********************************
2609 *
2610 * Various IO functions
2611 *
2612 ***********************************/
2613 /**
2614 * Returns TRUE if the input file existed
2615 *
2616 * @param string $file Input file to check
2617 * @return string Returns the filename if the file existed, otherwise empty.
2618 */
2619 public function checkFile($file) {
2620 if (@is_file($file)) {
2621 return $file;
2622 } else {
2623 return '';
2624 }
2625 }
2626
2627 /**
2628 * Creates subdirectory in typo3temp/ if not already found.
2629 *
2630 * @param string $dirName Name of sub directory
2631 * @return bool Result of \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir(), TRUE if it went well.
2632 */
2633 public function createTempSubDir($dirName) {
2634 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2635 if (GeneralUtility::isFirstPartOfStr($this->tempPath, PATH_site)) {
2636 $tmpPath = $this->tempPath;
2637 } else {
2638 $tmpPath = PATH_site . $this->tempPath;
2639 }
2640 // Making the temporary filename:
2641 if (!@is_dir(($tmpPath . $dirName))) {
2642 return GeneralUtility::mkdir($tmpPath . $dirName);
2643 }
2644 }
2645
2646 /**
2647 * Applies an ImageMagick parameter to a GDlib image pointer resource by writing the resource to file, performing an IM operation upon it and reading back the result into the ImagePointer.
2648 *
2649 * @param pointer $im The image pointer (reference)
2650 * @param string $command The ImageMagick parameters. Like effects, scaling etc.
2651 * @return void
2652 */
2653 public function applyImageMagickToPHPGif(&$im, $command) {
2654 $tmpStr = $this->randomName();
2655 $theFile = $tmpStr . '.' . $this->gifExtension;
2656 $this->ImageWrite($im, $theFile);
2657 $this->imageMagickExec($theFile, $theFile, $command);
2658 $tmpImg = $this->imageCreateFromFile($theFile);
2659 if ($tmpImg) {
2660 ImageDestroy($im);
2661 $im = $tmpImg;
2662 $this->w = imagesx($im);
2663 $this->h = imagesy($im);
2664 }
2665 if (!$this->dontUnlinkTempFiles) {
2666 unlink($theFile);
2667 }
2668 }
2669
2670 /**
2671 * Returns an image extension for an output image based on the number of pixels of the output and the file extension of the original file.
2672 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2673 *
2674 * @param string $type The file extension, lowercase.
2675 * @param int $w The width of the output image.
2676 * @param int $h The height of the output image.
2677 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2678 */
2679 public function gif_or_jpg($type, $w, $h) {
2680 if ($type == 'ai' || $w * $h < $this->pixelLimitGif) {
2681 return $this->gifExtension;
2682 } else {
2683 return 'jpg';
2684 }
2685 }
2686
2687 /**
2688 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2689 * Used in GIFBUILDER
2690 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2691 *
2692 * @param string $file The filename to write to.
2693