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