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