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