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