PageRenderTime 44ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/t3lib/class.t3lib_stdgraphic.php

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