[BUGFIX] Add more entropy to uniqid
[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 boolean
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 integer $dstX Destination x-coordinate
553 * @param integer $dstY Destination y-coordinate
554 * @param integer $srcX Source x-coordinate
555 * @param integer $srcY Source y-coordinate
556 * @param integer $dstWidth Destination width
557 * @param integer $dstHeight Destination height
558 * @param integer $srcWidth Source width
559 * @param integer $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 integer $fontSize (See argument for PHP function imageTTFtext())
860 * @param integer $angle (See argument for PHP function imageTTFtext())
861 * @param integer $x (See argument for PHP function imageTTFtext())
862 * @param integer $y (See argument for PHP function imageTTFtext())
863 * @param integer $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 integer $spacing The spacing of letters in pixels
867 * @param integer $wordSpacing The spacing of words in pixels
868 * @param array $splitRenderingConf Array
869 * @param integer $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 integer 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 integer $fontSize (See argument for PHP function ImageTTFBBox())
940 * @param integer $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 integer $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 integer $fontSize (See argument for PHP function imageTTFtext())
988 * @param integer $angle (See argument for PHP function imageTTFtext())
989 * @param integer $x (See argument for PHP function imageTTFtext())
990 * @param integer $y (See argument for PHP function imageTTFtext())
991 * @param integer $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 integer $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 integer $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 integer $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 integer 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 integer $fontSize (See argument for PHP function imageTTFtext())
1209 * @param integer $angle (See argument for PHP function imageTTFtext())
1210 * @param integer $x (See argument for PHP function imageTTFtext())
1211 * @param integer $y (See argument for PHP function imageTTFtext())
1212 * @param integer $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 integer $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 integer
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 integer 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 integer $distance Distance
1347 * @param integer $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 integer $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 integer $im GDlib Image Pointer
1828 * @param integer $low The "low" value (close to 0)
1829 * @param integer $high The "high" value (close to 255)
1830 * @param boolean $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 integer $im GDlib Image Pointer
1858 * @param integer $low The "low" value (close to 0)
1859 * @param integer $high The "high" value (close to 255)
1860 * @param boolean $swap @deprecated since 6.2, unused and obsolete parameter, was used for older image magick versions
1861 * @return void
1862 */
1863 public function inputLevels(&$im, $low, $high, $swap = '') {
1864 if ($low < $high) {
1865 $low = MathUtility::forceIntegerInRange($low, 0, 255);
1866 $high = MathUtility::forceIntegerInRange($high, 0, 255);
1867 $delta = $high - $low;
1868 $totalCols = ImageColorsTotal($im);
1869 for ($c = 0; $c < $totalCols; $c++) {
1870 $cols = ImageColorsForIndex($im, $c);
1871 $cols['red'] = MathUtility::forceIntegerInRange(($cols['red'] - $low) / $delta * 255, 0, 255);
1872 $cols['green'] = MathUtility::forceIntegerInRange(($cols['green'] - $low) / $delta * 255, 0, 255);
1873 $cols['blue'] = MathUtility::forceIntegerInRange(($cols['blue'] - $low) / $delta * 255, 0, 255);
1874 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1875 }
1876 }
1877 }
1878
1879 /**
1880 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1881 *
1882 * @param string $file Image file to reduce
1883 * @param integer $cols Number of colors to reduce the image to.
1884 * @return string Reduced file
1885 */
1886 public function IMreduceColors($file, $cols) {
1887 $fI = GeneralUtility::split_fileref($file);
1888 $ext = strtolower($fI['fileext']);
1889 $result = $this->randomName() . '.' . $ext;
1890 if (($reduce = MathUtility::forceIntegerInRange($cols, 0, $ext == 'gif' ? 256 : $this->truecolorColors, 0)) > 0) {
1891 $params = ' -colors ' . $reduce;
1892 if ($reduce <= 256) {
1893 $params .= ' -type Palette';
1894 }
1895 if ($ext == 'png' && $reduce <= 256) {
1896 $prefix = 'png8:';
1897 }
1898 $this->imageMagickExec($file, $prefix . $result, $params);
1899 if ($result) {
1900 return $result;
1901 }
1902 }
1903 return '';
1904 }
1905
1906 /*********************************
1907 *
1908 * GIFBUILDER Helper functions
1909 *
1910 *********************************/
1911 /**
1912 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1913 * Use PATH_site unless we are in the backend.
1914 * Call it by \TYPO3\CMS\Core\Imaging\GraphicalFunctions::prependAbsolutePath()
1915 *
1916 * @param string $fontFile The font file
1917 * @return string The font file with absolute path.
1918 */
1919 public function prependAbsolutePath($fontFile) {
1920 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript) . '/' : PATH_site;
1921 $fontFile = GeneralUtility::isAbsPath($fontFile) ? $fontFile : GeneralUtility::resolveBackPath($absPath . $fontFile);
1922 return $fontFile;
1923 }
1924
1925 /**
1926 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1927 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1928 *
1929 * @param integer $factor The sharpening factor, 0-100 (effectively in 10 steps)
1930 * @return string The sharpening command, eg. " -sharpen 3x4
1931 * @see makeText(), IMparams(), v5_blur()
1932 */
1933 public function v5_sharpen($factor) {
1934 $factor = MathUtility::forceIntegerInRange(ceil($factor / 10), 0, 10);
1935 $sharpenArr = explode(',', ',' . $this->im5fx_sharpenSteps);
1936 $sharpenF = trim($sharpenArr[$factor]);
1937 if ($sharpenF) {
1938 $cmd = ' -sharpen ' . $sharpenF;
1939 return $cmd;
1940 }
1941 }
1942
1943 /**
1944 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
1945 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
1946 *
1947 * @param integer $factor The blurring factor, 0-100 (effectively in 10 steps)
1948 * @return string The blurring command, eg. " -blur 3x4
1949 * @see makeText(), IMparams(), v5_sharpen()
1950 */
1951 public function v5_blur($factor) {
1952 $factor = MathUtility::forceIntegerInRange(ceil($factor / 10), 0, 10);
1953 $blurArr = explode(',', ',' . $this->im5fx_blurSteps);
1954 $blurF = trim($blurArr[$factor]);
1955 if ($blurF) {
1956 $cmd = ' -blur ' . $blurF;
1957 return $cmd;
1958 }
1959 }
1960
1961 /**
1962 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
1963 * 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.
1964 *
1965 * @return string
1966 */
1967 public function randomName() {
1968 $this->createTempSubDir('temp/');
1969 return $this->tempPath . 'temp/' . md5(uniqid('', TRUE));
1970 }
1971
1972 /**
1973 * Applies offset value to coordinated in $cords.
1974 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
1975 *
1976 * @param array $cords Integer coordinates in key 0/1
1977 * @param array $OFFSET Offset values in key 0/1
1978 * @return array Modified $cords array
1979 */
1980 public function applyOffset($cords, $OFFSET) {
1981 $cords[0] = (int)$cords[0] + (int)$OFFSET[0];
1982 $cords[1] = (int)$cords[1] + (int)$OFFSET[1];
1983 return $cords;
1984 }
1985
1986 /**
1987 * Converts a "HTML-color" TypoScript datatype to RGB-values.
1988 * Default is 0,0,0
1989 *
1990 * @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
1991 * @return array RGB values in key 0/1/2 of the array
1992 */
1993 public function convertColor($string) {
1994 $col = array();
1995 $cParts = explode(':', $string, 2);
1996 // Finding the RGB definitions of the color:
1997 $string = $cParts[0];
1998 if (strstr($string, '#')) {
1999 $string = preg_replace('/[^A-Fa-f0-9]*/', '', $string);
2000 $col[] = HexDec(substr($string, 0, 2));
2001 $col[] = HexDec(substr($string, 2, 2));
2002 $col[] = HexDec(substr($string, 4, 2));
2003 } elseif (strstr($string, ',')) {
2004 $string = preg_replace('/[^,0-9]*/', '', $string);
2005 $strArr = explode(',', $string);
2006 $col[] = (int)$strArr[0];
2007 $col[] = (int)$strArr[1];
2008 $col[] = (int)$strArr[2];
2009 } else {
2010 $string = strtolower(trim($string));
2011 if ($this->colMap[$string]) {
2012 $col = $this->colMap[$string];
2013 } else {
2014 $col = array(0, 0, 0);
2015 }
2016 }
2017 // ... and possibly recalculating the value
2018 if (trim($cParts[1])) {
2019 $cParts[1] = trim($cParts[1]);
2020 if ($cParts[1][0] === '*') {
2021 $val = doubleval(substr($cParts[1], 1));
2022 $col[0] = MathUtility::forceIntegerInRange($col[0] * $val, 0, 255);
2023 $col[1] = MathUtility::forceIntegerInRange($col[1] * $val, 0, 255);
2024 $col[2] = MathUtility::forceIntegerInRange($col[2] * $val, 0, 255);
2025 } else {
2026 $val = (int)$cParts[1];
2027 $col[0] = MathUtility::forceIntegerInRange($col[0] + $val, 0, 255);
2028 $col[1] = MathUtility::forceIntegerInRange($col[1] + $val, 0, 255);
2029 $col[2] = MathUtility::forceIntegerInRange($col[2] + $val, 0, 255);
2030 }
2031 }
2032 return $col;
2033 }
2034
2035 /**
2036 * Recode string
2037 * Used with text strings for fonts when languages has other character sets.
2038 *
2039 * @param string The text to recode
2040 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
2041 */
2042 public function recodeString($string) {
2043 // Recode string to UTF-8 from $this->nativeCharset:
2044 if ($this->nativeCharset && $this->nativeCharset != 'utf-8') {
2045 // Convert to UTF-8
2046 $string = $this->csConvObj->utf8_encode($string, $this->nativeCharset);
2047 }
2048 return $string;
2049 }
2050
2051 /**
2052 * Split a string into an array of individual characters
2053 * 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.
2054 *
2055 * @param string $theText The text string to split
2056 * @param boolean $returnUnicodeNumber Return Unicode numbers instead of chars.
2057 * @return array Numerical array with a char as each value.
2058 */
2059 public function singleChars($theText, $returnUnicodeNumber = FALSE) {
2060 if ($this->nativeCharset) {
2061 // Get an array of separated UTF-8 chars
2062 return $this->csConvObj->utf8_to_numberarray($theText, 1, $returnUnicodeNumber ? 0 : 1);
2063 } else {
2064 $output = array();
2065 $c = strlen($theText);
2066 for ($a = 0; $a < $c; $a++) {
2067 $output[] = substr($theText, $a, 1);
2068 }
2069 return $output;
2070 }
2071 }
2072
2073 /**
2074 * 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
2075 *
2076 * @param array $conf TypoScript configuration for a GIFBUILDER object
2077 * @param array makeBox Workarea definition
2078 * @param array $BB BB (Bounding box) array. Not just used for TEXT objects but also for others
2079 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2080 * @access private
2081 * @see copyGifOntoGif(), makeBox(), crop()
2082 */
2083 public function objPosition($conf, $workArea, $BB) {
2084 // offset, align, valign, workarea
2085 $result = array();
2086 $result[2] = $BB[0];
2087 $result[3] = $BB[1];
2088 $w = $workArea[2];
2089 $h = $workArea[3];
2090 $align = explode(',', $conf['align']);
2091 $align[0] = strtolower(substr(trim($align[0]), 0, 1));
2092 $align[1] = strtolower(substr(trim($align[1]), 0, 1));
2093 switch ($align[0]) {
2094 case 'r':
2095 $result[0] = $w - $result[2];
2096 break;
2097 case 'c':
2098 $result[0] = round(($w - $result[2]) / 2);
2099 break;
2100 default:
2101 $result[0] = 0;
2102 }
2103 switch ($align[1]) {
2104 case 'b':
2105 // y pos
2106 $result[1] = $h - $result[3];
2107 break;
2108 case 'c':
2109 $result[1] = round(($h - $result[3]) / 2);
2110 break;
2111 default:
2112 $result[1] = 0;
2113 }
2114 $result = $this->applyOffset($result, GeneralUtility::intExplode(',', $conf['offset']));
2115 $result = $this->applyOffset($result, $workArea);
2116 return $result;
2117 }
2118
2119 /***********************************
2120 *
2121 * Scaling, Dimensions of images
2122 *
2123 ***********************************/
2124 /**
2125 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2126 *
2127 * @param string $imagefile The image filepath
2128 * @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.
2129 * @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
2130 * @param string $h Height. See $w
2131 * @param string $params Additional ImageMagick parameters.
2132 * @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...
2133 * @param array $options An array with options passed to getImageScale (see this function).
2134 * @param boolean $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.
2135 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2136 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2137 */
2138 public function imageMagickConvert($imagefile, $newExt = '', $w = '', $h = '', $params = '', $frame = '', $options = array(), $mustCreate = FALSE) {
2139 if ($this->NO_IMAGE_MAGICK) {
2140 // Returning file info right away
2141 return $this->getImageDimensions($imagefile);
2142 }
2143 if ($info = $this->getImageDimensions($imagefile)) {
2144 $newExt = strtolower(trim($newExt));
2145 // If no extension is given the original extension is used
2146 if (!$newExt) {
2147 $newExt = $info[2];
2148 }
2149 if ($newExt == 'web') {
2150 if (GeneralUtility::inList($this->webImageExt, $info[2])) {
2151 $newExt = $info[2];
2152 } else {
2153 $newExt = $this->gif_or_jpg($info[2], $info[0], $info[1]);
2154 if (!$params) {
2155 $params = $this->cmds[$newExt];
2156 }
2157 }
2158 }
2159 if (GeneralUtility::inList($this->imageFileExt, $newExt)) {
2160 if (strstr($w . $h, 'm')) {
2161 $max = 1;
2162 } else {
2163 $max = 0;
2164 }
2165 $data = $this->getImageScale($info, $w, $h, $options);
2166 $w = $data['origW'];
2167 $h = $data['origH'];
2168 // If no conversion should be performed
2169 // this flag is TRUE if the width / height does NOT dictate
2170 // the image to be scaled!! (that is if no width / height is
2171 // given or if the destination w/h matches the original image
2172 // dimensions or if the option to not scale the image is set)
2173 $noScale = !$w && !$h || $data[0] == $info[0] && $data[1] == $info[1] || $options['noScale'];
2174 if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
2175 // Set the new width and height before returning,
2176 // if the noScale option is set
2177 if (!empty($options['noScale'])) {
2178 $info[0] = $data[0];
2179 $info[1] = $data[1];
2180 }
2181 $info[3] = $imagefile;
2182 return $info;
2183 }
2184 $info[0] = $data[0];
2185 $info[1] = $data[1];
2186 $frame = $this->noFramePrepended ? '' : (int)$frame;
2187 if (!$params) {
2188 $params = $this->cmds[$newExt];
2189 }
2190 // Cropscaling:
2191 if ($data['crs']) {
2192 if (!$data['origW']) {
2193 $data['origW'] = $data[0];
2194 }
2195 if (!$data['origH']) {
2196 $data['origH'] = $data[1];
2197 }
2198 $offsetX = (int)(($data[0] - $data['origW']) * ($data['cropH'] + 100) / 200);
2199 $offsetY = (int)(($data[1] - $data['origH']) * ($data['cropV'] + 100) / 200);
2200 $params .= ' -crop ' . $data['origW'] . 'x' . $data['origH'] . '+' . $offsetX . '+' . $offsetY . '! ';
2201 }
2202 $command = $this->scalecmd . ' ' . $info[0] . 'x' . $info[1] . '! ' . $params . ' ';
2203 $cropscale = $data['crs'] ? 'crs-V' . $data['cropV'] . 'H' . $data['cropH'] : '';
2204 if ($this->alternativeOutputKey) {
2205 $theOutputName = GeneralUtility::shortMD5($command . $cropscale . basename($imagefile) . $this->alternativeOutputKey . '[' . $frame . ']');
2206 } else {
2207 $theOutputName = GeneralUtility::shortMD5($command . $cropscale . $imagefile . filemtime($imagefile) . '[' . $frame . ']');
2208 }
2209 if ($this->imageMagickConvert_forceFileNameBody) {
2210 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
2211 $this->imageMagickConvert_forceFileNameBody = '';
2212 }
2213 // Making the temporary filename:
2214 $this->createTempSubDir('pics/');
2215 $output = $this->absPrefix . $this->tempPath . 'pics/' . $this->filenamePrefix . $theOutputName . '.' . $newExt;
2216 // Register temporary filename:
2217 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2218 if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
2219 $this->imageMagickExec($imagefile, $output, $command, $frame);
2220 }
2221 if (file_exists($output)) {
2222 $info[3] = $output;
2223 $info[2] = $newExt;
2224 // params could realisticly change some imagedata!
2225 if ($params) {
2226 $info = $this->getImageDimensions($info[3]);
2227 }
2228 if ($info[2] == $this->gifExtension && !$this->dontCompress) {
2229 // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2230 GeneralUtility::gif_compress($info[3], '');
2231 }
2232 return $info;
2233 }
2234 }
2235 }
2236 }
2237
2238 /**
2239 * Gets the input image dimensions.
2240 *
2241 * @param string $imageFile The image filepath
2242 * @return array|NULL Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2243 * @see imageMagickConvert(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getImgResource()
2244 */
2245 public function getImageDimensions($imageFile) {
2246 preg_match('/([^\\.]*)$/', $imageFile, $reg);
2247 if (file_exists($imageFile) && GeneralUtility::inList($this->imageFileExt, strtolower($reg[0]))) {
2248 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2249 return $returnArr;
2250 } else {
2251 if ($temp = @getImageSize($imageFile)) {
2252 $returnArr = array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2253 } else {
2254 $returnArr = $this->imageMagickIdentify($imageFile);
2255 }
2256 if ($returnArr) {
2257 $this->cacheImageDimensions($returnArr);
2258 return $returnArr;
2259 }
2260 }
2261 }
2262 return NULL;
2263 }
2264
2265 /**
2266 * Cache the result of the getImageDimensions function into the database. Does not check if the
2267 * file exists!
2268 *
2269 * @param array $identifyResult Result of the getImageDimensions function
2270 * @return boolean TRUE if operation was successful
2271 */
2272 public function cacheImageDimensions($identifyResult) {
2273 // Create md5 hash of filemtime and filesize
2274 $fileStatus = stat($identifyResult[3]);
2275 $md5Hash = md5($fileStatus['mtime'] . $fileStatus['size']);
2276 $result = FALSE;
2277 if ($md5Hash) {
2278 $fieldArray = array(
2279 'md5hash' => $md5Hash,
2280 'md5filename' => md5($identifyResult[3]),
2281 'tstamp' => $GLOBALS['EXEC_TIME'],
2282 'filename' => $identifyResult[3],
2283 'imagewidth' => $identifyResult[0],
2284 'imageheight' => $identifyResult[1]
2285 );
2286 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_imagesizes', $fieldArray);
2287 if (!($err = $GLOBALS['TYPO3_DB']->sql_error())) {
2288 $result = TRUE;
2289 }
2290 }
2291 return $result;
2292 }
2293
2294 /**
2295 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2296 *
2297 * @param string $imageFile The image filepath
2298 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2299 */
2300 public function getCachedImageDimensions($imageFile) {
2301 // Create md5 hash of filemtime and filesize
2302 $fileStatus = stat($imageFile);
2303 $md5Hash = md5($fileStatus['mtime'] . $fileStatus['size']);
2304 $cachedImageDimensions = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('md5hash, md5filename, imagewidth, imageheight', 'cache_imagesizes', 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(md5($imageFile), 'cache_imagesizes'));
2305 $result = FALSE;
2306 if (is_array($cachedImageDimensions)) {
2307 if ($cachedImageDimensions['md5hash'] != $md5Hash) {
2308 // File has changed, delete the row
2309 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_imagesizes', 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($cachedImageDimensions['md5filename'], 'cache_imagesizes'));
2310 } else {
2311 preg_match('/([^\\.]*)$/', $imageFile, $imageExtension);
2312 $result = array(
2313 (int)$cachedImageDimensions['imagewidth'],
2314 (int)$cachedImageDimensions['imageheight'],
2315 strtolower($imageExtension[0]),
2316 $imageFile
2317 );
2318 }
2319 }
2320 return $result;
2321 }
2322
2323 /**
2324 * Get numbers for scaling the image based on input
2325 *
2326 * @param array $info Current image information: Width, Height etc.
2327 * @param integer $w "required" width
2328 * @param integer $h "required" height
2329 * @param array $options Options: Keys are like "maxW", "maxH", "minW", "minH
2330 * @return array
2331 * @access private
2332 * @see imageMagickConvert()
2333 */
2334 public function getImageScale($info, $w, $h, $options) {
2335 if (strstr($w . $h, 'm')) {
2336 $max = 1;
2337 } else {
2338 $max = 0;
2339 }
2340 if (strstr($w . $h, 'c')) {
2341 $out['cropH'] = (int)substr(strstr($w, 'c'), 1);
2342 $out['cropV'] = (int)substr(strstr($h, 'c'), 1);
2343 $crs = TRUE;
2344 } else {
2345 $crs = FALSE;
2346 }
2347 $out['crs'] = $crs;
2348 $w = (int)$w;
2349 $h = (int)$h;
2350 // If there are max-values...
2351 if (!empty($options['maxW'])) {
2352 // If width is given...
2353 if ($w) {
2354 if ($w > $options['maxW']) {
2355 $w = $options['maxW'];
2356 // Height should follow
2357 $max = 1;
2358 }
2359 } else {
2360 if ($info[0] > $options['maxW']) {
2361 $w = $options['maxW'];
2362 // Height should follow
2363 $max = 1;
2364 }
2365 }
2366 }
2367 if (!empty($options['maxH'])) {
2368 // If height is given...
2369 if ($h) {
2370 if ($h > $options['maxH']) {
2371 $h = $options['maxH'];
2372 // Height should follow
2373 $max = 1;
2374 }
2375 } else {
2376 // Changed [0] to [1] 290801
2377 if ($info[1] > $options['maxH']) {
2378 $h = $options['maxH'];
2379 // Height should follow
2380 $max = 1;
2381 }
2382 }
2383 }
2384 $out['origW'] = $w;
2385 $out['origH'] = $h;
2386 $out['max'] = $max;
2387 if (!$this->mayScaleUp) {
2388 if ($w > $info[0]) {
2389 $w = $info[0];
2390 }
2391 if ($h > $info[1]) {
2392 $h = $info[1];
2393 }
2394 }
2395 // If scaling should be performed
2396 if ($w || $h) {
2397 if ($w && !$h) {
2398 $info[1] = ceil($info[1] * ($w / $info[0]));
2399 $info[0] = $w;
2400 }
2401 if (!$w && $h) {
2402 $info[0] = ceil($info[0] * ($h / $info[1]));
2403 $info[1] = $h;
2404 }
2405 if ($w && $h) {
2406 if ($max) {
2407 $ratio = $info[0] / $info[1];
2408 if ($h * $ratio > $w) {
2409 $h = round($w / $ratio);
2410 } else {
2411 $w = round($h * $ratio);
2412 }
2413 }
2414 if ($crs) {
2415 $ratio = $info[0] / $info[1];
2416 if ($h * $ratio < $w) {
2417 $h = round($w / $ratio);
2418 } else {
2419 $w = round($h * $ratio);
2420 }
2421 }
2422 $info[0] = $w;
2423 $info[1] = $h;
2424 }
2425 }
2426 $out[0] = $info[0];
2427 $out[1] = $info[1];
2428 // Set minimum-measures!
2429 if (isset($options['minW']) && $out[0] < $options['minW']) {
2430 if (($max || $crs) && $out[0]) {
2431 $out[1] = round($out[1] * $options['minW'] / $out[0]);
2432 }
2433 $out[0] = $options['minW'];
2434 }
2435 if (isset($options['minH']) && $out[1] < $options['minH']) {
2436 if (($max || $crs) && $out[1]) {
2437 $out[0] = round($out[0] * $options['minH'] / $out[1]);
2438 }
2439 $out[1] = $options['minH'];
2440 }
2441 return $out;
2442 }
2443
2444 /**
2445 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2446 *
2447 * @param string $output Output imagefile
2448 * @param string $orig Original basis file
2449 * @return boolean Returns TRUE if the file is already being made; thus "TRUE" means "Don't render the image again
2450 * @access private
2451 */
2452 public function file_exists_typo3temp_file($output, $orig = '') {
2453 if ($this->enable_typo3temp_db_tracking) {
2454 // If file exists, then we return immediately
2455 if (file_exists($output)) {
2456 return 1;
2457 } else {
2458 // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2459 $md5Hash = md5($output);
2460 $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));
2461 // If there was a record, the image is being generated by another process (we assume)
2462 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2463 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2464 if (is_object($GLOBALS['TSFE'])) {
2465 $GLOBALS['TSFE']->set_no_cache('Another process renders this file now: ' . $output);
2466 }
2467 // ...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...)
2468 if (is_object($GLOBALS['TT'])) {
2469 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: ' . $output);
2470 }
2471 // Return 'success - 2'
2472 return 2;
2473 } else {
2474 // 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.
2475 $insertFields = array(
2476 'md5hash' => $md5Hash,
2477 'tstamp' => $GLOBALS['EXEC_TIME'],
2478 'filename' => $output,
2479 'orig_filename' => $orig
2480 );
2481 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2482 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2483 if (is_object($GLOBALS['TT'])) {
2484 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: ' . $output);
2485 }
2486 return 0;
2487 }
2488 }
2489 } else {
2490 return file_exists($output);
2491 }
2492 }
2493
2494 /***********************************
2495 *
2496 * ImageMagick API functions
2497 *
2498 ***********************************/
2499 /**
2500 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2501 * Using ImageMagick
2502 *
2503 * @param string $imagefile The relative (to PATH_site) image filepath
2504 * @return array
2505 */
2506 public function imageMagickIdentify($imagefile) {
2507 if (!$this->NO_IMAGE_MAGICK) {
2508 $frame = $this->noFramePrepended ? '' : '[0]';
2509 $cmd = GeneralUtility::imageMagickCommand('identify', $this->wrapFileName($imagefile) . $frame);
2510 $returnVal = array();
2511 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd, $returnVal);
2512 $splitstring = array_pop($returnVal);
2513 $this->IM_commands[] = array('identify', $cmd, $splitstring);
2514 if ($splitstring) {
2515 preg_match('/([^\\.]*)$/', $imagefile, $reg);
2516 $splitinfo = explode(' ', $splitstring);
2517 foreach ($splitinfo as $key => $val) {
2518 $temp = '';
2519 if ($val) {
2520 $temp = explode('x', $val);
2521 }
2522 if ((int)$temp[0] && (int)$temp[1]) {
2523 $dim = $temp;
2524 break;
2525 }
2526 }
2527 if ($dim[0] && $dim[1]) {
2528 return array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2529 }
2530 }
2531 }
2532 }
2533
2534 /**
2535 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2536 * Can be used for many things, mostly scaling and effects.
2537 *
2538 * @param string $input The relative (to PATH_site) image filepath, input file (read from)
2539 * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
2540 * @param string $params ImageMagick parameters
2541 * @param integer $frame Optional, refers to which frame-number to select in the image. '' or 0
2542 * @return string The result of a call to PHP function "exec()
2543 */
2544 public function imageMagickExec($input, $output, $params, $frame = 0) {
2545 if (!$this->NO_IMAGE_MAGICK) {
2546 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2547 // select a specific page of the image (by default this will be the first page)
2548 if (!$this->noFramePrepended) {
2549 $frame = '[' . (int)$frame . ']';
2550 } else {
2551 $frame = '';
2552 }
2553 $cmd = GeneralUtility::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input . $frame) . ' ' . $this->wrapFileName($output));
2554 $this->IM_commands[] = array($output, $cmd);
2555 $ret = \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
2556 // Change the permissions of the file
2557 GeneralUtility::fixPermissions($output);
2558 return $ret;
2559 }
2560 }
2561
2562 /**
2563 * 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)
2564 * Can be used for many things, mostly scaling and effects.
2565 *
2566 * @param string $input The relative (to PATH_site) image filepath, bottom file
2567 * @param string $overlay The relative (to PATH_site) image filepath, overlay file (top)
2568 * @param string $mask The relative (to PATH_site) image filepath, the mask file (grayscale)
2569 * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
2570 * @param boolean $handleNegation
2571 * @return void
2572 */
2573 public function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) {
2574 if (!$this->NO_IMAGE_MAGICK) {
2575 $params = '-colorspace GRAY +matte';
2576 $theMask = $this->randomName() . '.' . $this->gifExtension;
2577 $this->imageMagickExec($mask, $theMask, $params);
2578 $cmd = GeneralUtility::imageMagickCommand('combine', '-compose over +matte ' . $this->wrapFileName($input) . ' ' . $this->wrapFileName($overlay) . ' ' . $this->wrapFileName($theMask) . ' ' . $this->wrapFileName($output));
2579 // +matte = no alpha layer in output
2580 $this->IM_commands[] = array($output, $cmd);
2581 $ret = \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
2582 // Change the permissions of the file
2583 GeneralUtility::fixPermissions($output);
2584 if (is_file($theMask)) {
2585 @unlink($theMask);
2586 }
2587 return $ret;
2588 }
2589 }
2590
2591 /**
2592 * Escapes a file name so it can safely be used on the command line.
2593 *
2594 * @param string $inputName filename to safeguard, must not be empty
2595 * @return string $inputName escaped as needed
2596 */
2597 protected function wrapFileName($inputName) {
2598 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2599 $currentLocale = setlocale(LC_CTYPE, 0);
2600 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
2601 }
2602 $escapedInputName = escapeshellarg($inputName);
2603 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2604 setlocale(LC_CTYPE, $currentLocale);
2605 }
2606 return $escapedInputName;
2607 }
2608
2609 /***********************************
2610 *
2611 * Various IO functions
2612 *
2613 ***********************************/
2614 /**
2615 * Returns TRUE if the input file existed
2616 *
2617 * @param string $file Input file to check
2618 * @return string Returns the filename if the file existed, otherwise empty.
2619 */
2620 public function checkFile($file) {
2621 if (@is_file($file)) {
2622 return $file;
2623 } else {
2624 return '';
2625 }
2626 }
2627
2628 /**
2629 * Creates subdirectory in typo3temp/ if not already found.
2630 *
2631 * @param string $dirName Name of sub directory
2632 * @return boolean Result of \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir(), TRUE if it went well.
2633 */
2634 public function createTempSubDir($dirName) {
2635 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2636 if (GeneralUtility::isFirstPartOfStr($this->tempPath, PATH_site)) {
2637 $tmpPath = $this->tempPath;
2638 } else {
2639 $tmpPath = PATH_site . $this->tempPath;
2640 }
2641 // Making the temporary filename:
2642 if (!@is_dir(($tmpPath . $dirName))) {
2643 return GeneralUtility::mkdir($tmpPath . $dirName);
2644 }
2645 }
2646
2647 /**
2648 * 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.
2649 *
2650 * @param pointer $im The image pointer (reference)
2651 * @param string $command The ImageMagick parameters. Like effects, scaling etc.
2652 * @return void
2653 */
2654 public function applyImageMagickToPHPGif(&$im, $command) {
2655 $tmpStr = $this->randomName();
2656 $theFile = $tmpStr . '.' . $this->gifExtension;
2657 $this->ImageWrite($im, $theFile);
2658 $this->imageMagickExec($theFile, $theFile, $command);
2659 $tmpImg = $this->imageCreateFromFile($theFile);
2660 if ($tmpImg) {
2661 ImageDestroy($im);
2662 $im = $tmpImg;
2663 $this->w = imagesx($im);
2664 $this->h = imagesy($im);
2665 }
2666 if (!$this->dontUnlinkTempFiles) {
2667 unlink($theFile);
2668 }
2669 }
2670
2671 /**
2672 * 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.
2673 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2674 *
2675 * @param string $type The file extension, lowercase.
2676 * @param integer $w The width of the output image.
2677 * @param integer $h The height of the output image.
2678 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2679 */
2680 public function gif_or_jpg($type, $w, $h) {
2681 if ($type == 'ai' || $w * $h < $this->pixelLimitGif) {
2682 return $this->gifExtension;
2683 } else {
2684 return 'jpg';
2685 }
2686 }
2687
2688 /**
2689 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2690 * Used in GIFBUILDER
2691 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.