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