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