PageRenderTime 76ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_stdgraphic.php

https://bitbucket.org/tritum_sw/typo3v4-core
PHP | 2999 lines | 1831 code | 235 blank | 933 comment | 413 complexity | 9bd815c852e86bc7b4d3a0640283f880 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, BSD-3-Clause, BSD-2-Clause, AGPL-1.0, LGPL-3.0, GPL-3.0, MIT, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
  6. * All rights reserved
  7. *
  8. * This script is part of the TYPO3 project. The TYPO3 project is
  9. * free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * The GNU General Public License can be found at
  15. * http://www.gnu.org/copyleft/gpl.html.
  16. * A copy is found in the textfile GPL.txt and important notices to the license
  17. * from the author is found in LICENSE.txt distributed with these scripts.
  18. *
  19. *
  20. * This script is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * This copyright notice MUST APPEAR in all copies of the script!
  26. ***************************************************************/
  27. /**
  28. * Standard graphical functions
  29. *
  30. * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
  31. *
  32. * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  33. */
  34. /**
  35. * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
  36. * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
  37. *
  38. * With TYPO3 4.4 GDlib 1.x support was dropped, also an option from $TYPO3_CONF_VARS
  39. * $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.
  40. *
  41. * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  42. * @package TYPO3
  43. * @subpackage t3lib
  44. * @see tslib_gifBuilder
  45. */
  46. class t3lib_stdGraphic {
  47. // Internal configuration, set in init()
  48. // The ImageMagick filename used for combining two images. This name changed during the versions.
  49. var $combineScript = 'combine';
  50. // If set, there is no frame pointer prepended to the filenames.
  51. var $noFramePrepended = 0;
  52. // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
  53. var $imagecopyresized_fix = 0;
  54. // This should be changed to 'png' if you want this class to read/make PNG-files instead!
  55. var $gifExtension = 'gif';
  56. // File formats supported by gdlib. This variable get's filled in "init" method
  57. var $gdlibExtensions = '';
  58. // Set to TRUE if generated png's should be truecolor by default
  59. var $png_truecolor = FALSE;
  60. // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
  61. var $truecolorColors = 0xffffff;
  62. // 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.
  63. var $enable_typo3temp_db_tracking = 0;
  64. // 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!
  65. var $imageFileExt = 'gif,jpg,jpeg,png,tif,bmp,tga,pcx,ai,pdf';
  66. // Commalist of web image extensions (can be shown by a webbrowser)
  67. var $webImageExt = 'gif,jpg,jpeg,png';
  68. // Will be ' -negate' if ImageMagick ver 5.2+. See init();
  69. var $maskNegate = '';
  70. var $NO_IM_EFFECTS = '';
  71. var $cmds = array(
  72. 'jpg' => '',
  73. 'jpeg' => '',
  74. 'gif' => '',
  75. 'png' => '-colors 64'
  76. );
  77. var $NO_IMAGE_MAGICK = '';
  78. var $V5_EFFECTS = 0;
  79. var $mayScaleUp = 1;
  80. // Variables for testing, alternative usage etc.
  81. // Filename prefix for images scaled in imageMagickConvert()
  82. var $filenamePrefix = '';
  83. // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
  84. var $imageMagickConvert_forceFileNameBody = '';
  85. // This flag should always be FALSE. If set TRUE, imageMagickConvert will always write a new file to the tempdir! Used for debugging.
  86. var $dontCheckForExistingTempFile = 0;
  87. // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
  88. var $dontCompress = 0;
  89. // For debugging ONLY!
  90. var $dontUnlinkTempFiles = 0;
  91. // 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...
  92. var $alternativeOutputKey = '';
  93. // Internal:
  94. // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
  95. var $IM_commands = array();
  96. var $workArea = array();
  97. /**
  98. * Preserve the alpha transparency layer of read PNG images
  99. *
  100. * @var boolean
  101. */
  102. protected $saveAlphaLayer = FALSE;
  103. // Constants:
  104. // 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.
  105. var $tempPath = 'typo3temp/';
  106. // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
  107. var $absPrefix = '';
  108. // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
  109. var $scalecmd = '-geometry';
  110. // Used by v5_blur() to simulate 10 continuous steps of blurring
  111. var $im5fx_blurSteps = '1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5';
  112. // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
  113. var $im5fx_sharpenSteps = '1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5';
  114. // This is the limit for the number of pixels in an image before it will be rendered as JPG instead of GIF/PNG
  115. var $pixelLimitGif = 10000;
  116. // Array mapping HTML color names to RGB values.
  117. var $colMap = array(
  118. 'aqua' => array(0, 255, 255),
  119. 'black' => array(0, 0, 0),
  120. 'blue' => array(0, 0, 255),
  121. 'fuchsia' => array(255, 0, 255),
  122. 'gray' => array(128, 128, 128),
  123. 'green' => array(0, 128, 0),
  124. 'lime' => array(0, 255, 0),
  125. 'maroon' => array(128, 0, 0),
  126. 'navy' => array(0, 0, 128),
  127. 'olive' => array(128, 128, 0),
  128. 'purple' => array(128, 0, 128),
  129. 'red' => array(255, 0, 0),
  130. 'silver' => array(192, 192, 192),
  131. 'teal' => array(0, 128, 128),
  132. 'yellow' => array(255, 255, 0),
  133. 'white' => array(255, 255, 255)
  134. );
  135. /**
  136. * Charset conversion object:
  137. *
  138. * @var t3lib_cs
  139. */
  140. var $csConvObj;
  141. // Is set to the native character set of the input strings.
  142. var $nativeCharset = '';
  143. /**
  144. * Init function. Must always call this when using the class.
  145. * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
  146. *
  147. * @return void
  148. */
  149. function init() {
  150. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  151. if (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
  152. $this->gdlibExtensions .= ',jpg,jpeg';
  153. }
  154. if (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
  155. $this->gdlibExtensions .= ',png';
  156. }
  157. if (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
  158. $this->gdlibExtensions .= ',gif';
  159. }
  160. if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
  161. $this->png_truecolor = TRUE;
  162. }
  163. if (!$gfxConf['im']) {
  164. $this->NO_IMAGE_MAGICK = 1;
  165. }
  166. if (!$this->NO_IMAGE_MAGICK && (!$gfxConf['im_version_5'] || $gfxConf['im_version_5'] === 'im4' || $gfxConf['im_version_5'] === 'im5')) {
  167. throw new RuntimeException(
  168. 'Your TYPO3 installation is configured to use an old version of ImageMagick, which is not supported anymore. ' .
  169. 'Please upgrade to ImageMagick version 6 or GraphicksMagick and set $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] appropriately.',
  170. 1305059666
  171. );
  172. }
  173. // When GIFBUILDER gets used in truecolor mode
  174. // No colors parameter if we generate truecolor images.
  175. if ($this->png_truecolor) {
  176. $this->cmds['png'] = '';
  177. }
  178. // Setting default JPG parameters:
  179. $this->jpegQuality = t3lib_utility_Math::forceIntegerInRange($gfxConf['jpg_quality'], 10, 100, 75);
  180. $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -sharpen 50 -quality ' . $this->jpegQuality;
  181. if ($gfxConf['im_combine_filename']) {
  182. $this->combineScript = $gfxConf['im_combine_filename'];
  183. }
  184. if ($gfxConf['im_noFramePrepended']) {
  185. $this->noFramePrepended = 1;
  186. }
  187. // Kept for backwards compatibility, can be turned on manually through localconf.php,
  188. // but not through the installer anymore
  189. $this->imagecopyresized_fix = ($gfxConf['gdlib_2'] === 'no_imagecopyresized_fix' ? 0 : 1);
  190. if ($gfxConf['gdlib_png']) {
  191. $this->gifExtension = 'png';
  192. }
  193. if ($gfxConf['enable_typo3temp_db_tracking']) {
  194. $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
  195. }
  196. $this->imageFileExt = $gfxConf['imagefile_ext'];
  197. // This should be set if ImageMagick ver. 5+ is used.
  198. if ($gfxConf['im_negate_mask']) {
  199. // Boolean. Indicates if the mask images should be inverted first.
  200. // This depends of the ImageMagick version. Below ver. 5.1 this should be FALSE.
  201. // Above ImageMagick version 5.2+ it should be TRUE.
  202. // Just set the flag if the masks works opposite the intension!
  203. $this->maskNegate = ' -negate';
  204. }
  205. if ($gfxConf['im_no_effects']) {
  206. // Boolean. This is necessary if using ImageMagick 5+.
  207. // Effects in Imagemagick 5+ tends to render very slowly!!
  208. // - therefore must be disabled in order not to perform sharpen, blurring and such.
  209. $this->NO_IM_EFFECTS = 1;
  210. $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality ' . $this->jpegQuality;
  211. }
  212. // ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
  213. if ($gfxConf['im_v5effects']) {
  214. $this->NO_IM_EFFECTS = 0;
  215. $this->V5_EFFECTS = 1;
  216. if ($gfxConf['im_v5effects'] > 0) {
  217. $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality ' . intval($gfxConf['jpg_quality']) . $this->v5_sharpen(10);
  218. }
  219. }
  220. // Secures that images are not scaled up.
  221. if ($gfxConf['im_noScaleUp']) {
  222. $this->mayScaleUp = 0;
  223. }
  224. if (TYPO3_MODE == 'FE') {
  225. $this->csConvObj = $GLOBALS['TSFE']->csConvObj;
  226. } elseif (is_object($GLOBALS['LANG'])) { // BE assumed:
  227. $this->csConvObj = $GLOBALS['LANG']->csConvObj;
  228. } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
  229. $this->csConvObj = t3lib_div::makeInstance('t3lib_cs');
  230. }
  231. $this->nativeCharset = 'utf-8';
  232. }
  233. /*************************************************
  234. *
  235. * Layering images / "IMAGE" GIFBUILDER object
  236. *
  237. *************************************************/
  238. /**
  239. * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is TRUE.
  240. * 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
  241. * The operation involves ImageMagick for combining.
  242. *
  243. * @param pointer $im GDlib image pointer
  244. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  245. * @param array $workArea The current working area coordinates.
  246. * @return void
  247. * @see tslib_gifBuilder::make()
  248. */
  249. function maskImageOntoImage(&$im, $conf, $workArea) {
  250. if ($conf['file'] && $conf['mask']) {
  251. $imgInf = pathinfo($conf['file']);
  252. $imgExt = strtolower($imgInf['extension']);
  253. if (!t3lib_div::inList($this->gdlibExtensions, $imgExt)) {
  254. $BBimage = $this->imageMagickConvert($conf['file'], $this->gifExtension, '', '', '', '', '');
  255. } else {
  256. $BBimage = $this->getImageDimensions($conf['file']);
  257. }
  258. $maskInf = pathinfo($conf['mask']);
  259. $maskExt = strtolower($maskInf['extension']);
  260. if (!t3lib_div::inList($this->gdlibExtensions, $maskExt)) {
  261. $BBmask = $this->imageMagickConvert($conf['mask'], $this->gifExtension, '', '', '', '', '');
  262. } else {
  263. $BBmask = $this->getImageDimensions($conf['mask']);
  264. }
  265. if ($BBimage && $BBmask) {
  266. $w = imagesx($im);
  267. $h = imagesy($im);
  268. $tmpStr = $this->randomName();
  269. $theImage = $tmpStr . '_img.' . $this->gifExtension;
  270. $theDest = $tmpStr . '_dest.' . $this->gifExtension;
  271. $theMask = $tmpStr . '_mask.' . $this->gifExtension;
  272. // Prepare overlay image
  273. $cpImg = $this->imageCreateFromFile($BBimage[3]);
  274. $destImg = imagecreatetruecolor($w, $h);
  275. // Preserve alpha transparency
  276. if ($this->saveAlphaLayer) {
  277. imagealphablending($destImg, FALSE);
  278. imagesavealpha($destImg, TRUE);
  279. $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
  280. imagefill($destImg, 0, 0, $Bcolor);
  281. } else {
  282. $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
  283. ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
  284. }
  285. $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
  286. $this->ImageWrite($destImg, $theImage);
  287. imageDestroy($cpImg);
  288. imageDestroy($destImg);
  289. // Prepare mask image
  290. $cpImg = $this->imageCreateFromFile($BBmask[3]);
  291. $destImg = imagecreatetruecolor($w, $h);
  292. if ($this->saveAlphaLayer) {
  293. imagealphablending($destImg, FALSE);
  294. imagesavealpha($destImg, TRUE);
  295. $Bcolor = imagecolorallocatealpha($destImg, 0, 0, 0, 127);
  296. imagefill($destImg, 0, 0, $Bcolor);
  297. } else {
  298. $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
  299. ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
  300. }
  301. $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
  302. $this->ImageWrite($destImg, $theMask);
  303. imageDestroy($cpImg);
  304. imageDestroy($destImg);
  305. // Mask the images
  306. $this->ImageWrite($im, $theDest);
  307. // Let combineExec handle maskNegation
  308. $this->combineExec($theDest, $theImage, $theMask, $theDest, TRUE);
  309. // The main image is loaded again...
  310. $backIm = $this->imageCreateFromFile($theDest);
  311. // ... and if nothing went wrong we load it onto the old one.
  312. if ($backIm) {
  313. if (!$this->saveAlphaLayer) {
  314. ImageColorTransparent($backIm, -1);
  315. }
  316. $im = $backIm;
  317. }
  318. // Unlink files from process
  319. if (!$this->dontUnlinkTempFiles) {
  320. unlink($theDest);
  321. unlink($theImage);
  322. unlink($theMask);
  323. }
  324. }
  325. }
  326. }
  327. /**
  328. * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is FALSE (using only $conf['file'])
  329. *
  330. * @param pointer $im GDlib image pointer
  331. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  332. * @param array $workArea The current working area coordinates.
  333. * @return void
  334. * @see tslib_gifBuilder::make(), maskImageOntoImage()
  335. */
  336. function copyImageOntoImage(&$im, $conf, $workArea) {
  337. if ($conf['file']) {
  338. if (!t3lib_div::inList($this->gdlibExtensions, $conf['BBOX'][2])) {
  339. $conf['BBOX'] = $this->imageMagickConvert($conf['BBOX'][3], $this->gifExtension, '', '', '', '', '');
  340. $conf['file'] = $conf['BBOX'][3];
  341. }
  342. $cpImg = $this->imageCreateFromFile($conf['file']);
  343. $this->copyGifOntoGif($im, $cpImg, $conf, $workArea);
  344. imageDestroy($cpImg);
  345. }
  346. }
  347. /**
  348. * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
  349. *
  350. * @param pointer $im GDlib image pointer, destination (bottom image)
  351. * @param pointer $cpImg GDlib image pointer, source (top image)
  352. * @param array $conf TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
  353. * @param array $workArea Work area
  354. * @return void Works on the $im image pointer
  355. * @access private
  356. */
  357. function copyGifOntoGif(&$im, $cpImg, $conf, $workArea) {
  358. $cpW = imagesx($cpImg);
  359. $cpH = imagesy($cpImg);
  360. $tile = t3lib_div::intExplode(',', $conf['tile']);
  361. $tile[0] = t3lib_utility_Math::forceIntegerInRange($tile[0], 1, 20);
  362. $tile[1] = t3lib_utility_Math::forceIntegerInRange($tile[1], 1, 20);
  363. $cpOff = $this->objPosition($conf, $workArea, array($cpW * $tile[0], $cpH * $tile[1]));
  364. for ($xt = 0; $xt < $tile[0]; $xt++) {
  365. $Xstart = $cpOff[0] + $cpW * $xt;
  366. // If this image is inside of the workArea, then go on
  367. if ($Xstart + $cpW > $workArea[0]) {
  368. // X:
  369. if ($Xstart < $workArea[0]) {
  370. $cpImgCutX = $workArea[0] - $Xstart;
  371. $Xstart = $workArea[0];
  372. } else {
  373. $cpImgCutX = 0;
  374. }
  375. $w = $cpW - $cpImgCutX;
  376. if ($Xstart > $workArea[0] + $workArea[2] - $w) {
  377. $w = $workArea[0] + $workArea[2] - $Xstart;
  378. }
  379. // If this image is inside of the workArea, then go on
  380. if ($Xstart < $workArea[0] + $workArea[2]) {
  381. // Y:
  382. for ($yt = 0; $yt < $tile[1]; $yt++) {
  383. $Ystart = $cpOff[1] + $cpH * $yt;
  384. // If this image is inside of the workArea, then go on
  385. if ($Ystart + $cpH > $workArea[1]) {
  386. if ($Ystart < $workArea[1]) {
  387. $cpImgCutY = $workArea[1] - $Ystart;
  388. $Ystart = $workArea[1];
  389. } else {
  390. $cpImgCutY = 0;
  391. }
  392. $h = $cpH - $cpImgCutY;
  393. if ($Ystart > $workArea[1] + $workArea[3] - $h) {
  394. $h = $workArea[1] + $workArea[3] - $Ystart;
  395. }
  396. // If this image is inside of the workArea, then go on
  397. if ($Ystart < $workArea[1] + $workArea[3]) {
  398. $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
  399. }
  400. }
  401. } // Y:
  402. }
  403. }
  404. }
  405. }
  406. /**
  407. * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
  408. *
  409. * OK, the reason for this stupid fix is the following story:
  410. * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
  411. * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
  412. * copy a color-ful image onto the destination.
  413. * The GD2-fix is to
  414. * 1) Create a blank TRUE-COLOR image
  415. * 2) Copy the destination image onto that one
  416. * 3) Then do the actual operation; Copying the source (top image) onto that
  417. * 4) ... and return the result pointer.
  418. * 5) Reduce colors (if we do not, the result may become strange!)
  419. * It works, but the resulting images is now a true-color PNG which may be very large.
  420. * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
  421. *
  422. * @param resource $dstImg Destination image
  423. * @param resource $srcImg Source image
  424. * @param integer $dstX Destination x-coordinate
  425. * @param integer $dstY Destination y-coordinate
  426. * @param integer $srcX Source x-coordinate
  427. * @param integer $srcY Source y-coordinate
  428. * @param integer $dstWidth Destination width
  429. * @param integer $dstHeight Destination height
  430. * @param integer $srcWidth Source width
  431. * @param integer $srcHeight Source height
  432. * @return void
  433. * @access private
  434. * @see t3lib_iconWorks::imagecopyresized()
  435. */
  436. function imagecopyresized(&$dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight) {
  437. if ($this->imagecopyresized_fix) {
  438. // Make true color image
  439. $tmpImg = imagecreatetruecolor(imagesx($dstImg), imagesy($dstImg));
  440. // Copy the source image onto that
  441. imagecopyresized($tmpImg, $dstImg, 0, 0, 0, 0, imagesx($dstImg), imagesy($dstImg), imagesx($dstImg), imagesy($dstImg));
  442. // Then copy the source image onto that (the actual operation!)
  443. imagecopyresized($tmpImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
  444. // Set the destination image
  445. $dstImg = $tmpImg;
  446. } else {
  447. imagecopyresized($dstImg, $srcImg, $dstX, $dstY, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
  448. }
  449. }
  450. /********************************
  451. *
  452. * Text / "TEXT" GIFBUILDER object
  453. *
  454. ********************************/
  455. /**
  456. * Implements the "TEXT" GIFBUILDER object
  457. *
  458. * @param pointer $im GDlib image pointer
  459. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  460. * @param array $workArea The current working area coordinates.
  461. * @return void
  462. * @see tslib_gifBuilder::make()
  463. */
  464. function makeText(&$im, $conf, $workArea) {
  465. // Spacing
  466. list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
  467. // Position
  468. $txtPos = $this->txtPosition($conf, $workArea, $conf['BBOX']);
  469. $theText = $this->recodeString($conf['text']);
  470. if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
  471. $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2], $txtPos, $conf['imgMap.']), $conf['imgMap.']);
  472. }
  473. if (!$conf['hideButCreateMap']) {
  474. // Font Color:
  475. $cols = $this->convertColor($conf['fontColor']);
  476. // NiceText is calculated
  477. if (!$conf['niceText']) {
  478. $Fcolor = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
  479. // antiAliasing is setup:
  480. $Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;
  481. for ($a = 0; $a < $conf['iterations']; $a++) {
  482. // If any kind of spacing applys, we use this function:
  483. if ($spacing || $wordSpacing) {
  484. $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, self::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
  485. } else {
  486. $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
  487. }
  488. }
  489. } else { // NICETEXT::
  490. // options anti_aliased and iterations is NOT available when doing this!!
  491. $w = imagesx($im);
  492. $h = imagesy($im);
  493. $tmpStr = $this->randomName();
  494. $fileMenu = $tmpStr . '_menuNT.' . $this->gifExtension;
  495. $fileColor = $tmpStr . '_colorNT.' . $this->gifExtension;
  496. $fileMask = $tmpStr . '_maskNT.' . $this->gifExtension;
  497. // Scalefactor
  498. $sF = t3lib_utility_Math::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
  499. $newW = ceil($sF * imagesx($im));
  500. $newH = ceil($sF * imagesy($im));
  501. // Make mask
  502. $maskImg = imagecreatetruecolor($newW, $newH);
  503. $Bcolor = ImageColorAllocate($maskImg, 255, 255, 255);
  504. ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
  505. $Fcolor = ImageColorAllocate($maskImg, 0, 0, 0);
  506. // If any kind of spacing applys, we use this function:
  507. if ($spacing || $wordSpacing) {
  508. $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, self::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'], $sF);
  509. } else {
  510. $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
  511. }
  512. $this->ImageWrite($maskImg, $fileMask);
  513. ImageDestroy($maskImg);
  514. // Downscales the mask
  515. if ($this->NO_IM_EFFECTS) {
  516. if ($this->maskNegate) {
  517. // Negate 2 times makes no negate...
  518. $command = trim($this->scalecmd . ' ' . $w . 'x' . $h . '!');
  519. } else {
  520. $command = trim($this->scalecmd . ' ' . $w . 'x' . $h . '! -negate');
  521. }
  522. } else {
  523. if ($this->maskNegate) {
  524. $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd . ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after']);
  525. } else {
  526. $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd . ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after'] . ' -negate');
  527. }
  528. if ($conf['niceText.']['sharpen']) {
  529. if ($this->V5_EFFECTS) {
  530. $command .= $this->v5_sharpen($conf['niceText.']['sharpen']);
  531. } else {
  532. $command .= ' -sharpen ' . t3lib_utility_Math::forceIntegerInRange($conf['niceText.']['sharpen'], 1, 99);
  533. }
  534. }
  535. }
  536. $this->imageMagickExec($fileMask, $fileMask, $command);
  537. // Make the color-file
  538. $colorImg = imagecreatetruecolor($w, $h);
  539. $Ccolor = ImageColorAllocate($colorImg, $cols[0], $cols[1], $cols[2]);
  540. ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
  541. $this->ImageWrite($colorImg, $fileColor);
  542. ImageDestroy($colorImg);
  543. // The mask is applied
  544. // The main pictures is saved temporarily
  545. $this->ImageWrite($im, $fileMenu);
  546. $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
  547. // The main image is loaded again...
  548. $backIm = $this->imageCreateFromFile($fileMenu);
  549. // ... and if nothing went wrong we load it onto the old one.
  550. if ($backIm) {
  551. if (!$this->saveAlphaLayer) {
  552. ImageColorTransparent($backIm, -1);
  553. }
  554. $im = $backIm;
  555. }
  556. // Deleting temporary files;
  557. if (!$this->dontUnlinkTempFiles) {
  558. unlink($fileMenu);
  559. unlink($fileColor);
  560. unlink($fileMask);
  561. }
  562. }
  563. }
  564. }
  565. /**
  566. * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
  567. *
  568. * @param array $conf TypoScript array for the TEXT GIFBUILDER object
  569. * @param array $workArea Workarea definition
  570. * @param array $BB Bounding box information, was set in tslib_gifBuilder::start()
  571. * @return array [0]=x, [1]=y, [2]=w, [3]=h
  572. * @access private
  573. * @see makeText()
  574. */
  575. function txtPosition($conf, $workArea, $BB) {
  576. $bbox = $BB[2];
  577. $angle = intval($conf['angle']) / 180 * pi();
  578. $conf['angle'] = 0;
  579. $straightBB = $this->calcBBox($conf);
  580. // offset, align, valign, workarea
  581. // [0]=x, [1]=y, [2]=w, [3]=h
  582. $result = array();
  583. $result[2] = $BB[0];
  584. $result[3] = $BB[1];
  585. $w = $workArea[2];
  586. $h = $workArea[3];
  587. switch ($conf['align']) {
  588. case 'right':
  589. case 'center':
  590. $factor = abs(cos($angle));
  591. $sign = (cos($angle) < 0) ? -1 : 1;
  592. $len1 = $sign * $factor * $straightBB[0];
  593. $len2 = $sign * $BB[0];
  594. $result[0] = $w - ceil($len2 * $factor + (1 - $factor) * $len1);
  595. $factor = abs(sin($angle));
  596. $sign = (sin($angle) < 0) ? -1 : 1;
  597. $len1 = $sign * $factor * $straightBB[0];
  598. $len2 = $sign * $BB[1];
  599. $result[1] = ceil($len2 * $factor + (1 - $factor) * $len1);
  600. break;
  601. }
  602. switch ($conf['align']) {
  603. case 'right':
  604. break;
  605. case 'center':
  606. $result[0] = round(($result[0]) / 2);
  607. $result[1] = round(($result[1]) / 2);
  608. break;
  609. default:
  610. $result[0] = 0;
  611. $result[1] = 0;
  612. break;
  613. }
  614. $result = $this->applyOffset($result, t3lib_div::intExplode(',', $conf['offset']));
  615. $result = $this->applyOffset($result, $workArea);
  616. return $result;
  617. }
  618. /**
  619. * Calculates bounding box information for the TEXT GIFBUILDER object.
  620. *
  621. * @param array $conf TypoScript array for the TEXT GIFBUILDER object
  622. * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
  623. * @access private
  624. * @see txtPosition(), tslib_gifBuilder::start()
  625. */
  626. function calcBBox($conf) {
  627. $sF = $this->getTextScalFactor($conf);
  628. list($spacing, $wordSpacing) = $this->calcWordSpacing($conf, $sF);
  629. $theText = $this->recodeString($conf['text']);
  630. $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'], $sF);
  631. $theBBoxInfo = $charInf;
  632. if ($conf['angle']) {
  633. $xArr = array($charInf[0], $charInf[2], $charInf[4], $charInf[6]);
  634. $yArr = array($charInf[1], $charInf[3], $charInf[5], $charInf[7]);
  635. $x = max($xArr) - min($xArr);
  636. $y = max($yArr) - min($yArr);
  637. } else {
  638. $x = ($charInf[2] - $charInf[0]);
  639. $y = ($charInf[1] - $charInf[7]);
  640. }
  641. // Set original lineHeight (used by line breaks):
  642. $theBBoxInfo['lineHeight'] = $y;
  643. // If any kind of spacing applys, we use this function:
  644. if ($spacing || $wordSpacing) {
  645. $x = 0;
  646. if (!$spacing && $wordSpacing) {
  647. $bits = explode(' ', $theText);
  648. foreach ($bits as $word) {
  649. $word .= ' ';
  650. $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'], $sF);
  651. $wordW = ($wordInf[2] - $wordInf[0]);
  652. $x += $wordW + $wordSpacing;
  653. }
  654. } else {
  655. $utf8Chars = $this->singleChars($theText);
  656. // For each UTF-8 char, do:
  657. foreach ($utf8Chars as $char) {
  658. $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'], $sF);
  659. $charW = ($charInf[2] - $charInf[0]);
  660. $x += $charW + (($char == ' ') ? $wordSpacing : $spacing);
  661. }
  662. }
  663. } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
  664. $maxWidth = 0;
  665. $currentWidth = 0;
  666. $breakWidth = $conf['breakWidth'];
  667. $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
  668. $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
  669. // Iterate through all word pairs:
  670. foreach ($wordPairs as $index => $wordPair) {
  671. $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
  672. if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
  673. $currentWidth += $wordWidth;
  674. } else {
  675. $maxWidth = max($maxWidth, $currentWidth);
  676. $y += $breakSpace;
  677. // Restart:
  678. $currentWidth = $wordWidth;
  679. }
  680. }
  681. $x = max($maxWidth, $currentWidth) * $sF;
  682. }
  683. if ($sF > 1) {
  684. $x = ceil($x / $sF);
  685. $y = ceil($y / $sF);
  686. if (is_array($theBBoxInfo)) {
  687. foreach ($theBBoxInfo as &$value) {
  688. $value = ceil($value / $sF);
  689. }
  690. unset($value);
  691. }
  692. }
  693. return array($x, $y, $theBBoxInfo);
  694. }
  695. /**
  696. * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
  697. *
  698. * @param array $cords Coordinates for a polygon image map as created by ->calcTextCordsForMap()
  699. * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
  700. * @return void
  701. * @access private
  702. * @see makeText(), calcTextCordsForMap()
  703. */
  704. function addToMap($cords, $conf) {
  705. $this->map .= '<area' .
  706. ' shape="poly"' .
  707. ' coords="' . implode(',', $cords) . '"' .
  708. ' href="' . htmlspecialchars($conf['url']) . '"' .
  709. ($conf['target'] ? ' target="' . htmlspecialchars($conf['target']) . '"' : '') .
  710. $JS .
  711. (strlen($conf['titleText']) ? ' title="' . htmlspecialchars($conf['titleText']) . '"' : '') .
  712. ' alt="' . htmlspecialchars($conf['altText']) . '" />';
  713. }
  714. /**
  715. * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
  716. *
  717. * @param array $cords Coordinates (from BBOX array)
  718. * @param array $offset Offset array
  719. * @param array $conf Configuration for "imgMap." property of a TEXT GIFBUILDER object.
  720. * @return array
  721. * @access private
  722. * @see makeText(), calcTextCordsForMap()
  723. */
  724. function calcTextCordsForMap($cords, $offset, $conf) {
  725. $pars = t3lib_div::intExplode(',', $conf['explode'] . ',');
  726. $newCords[0] = $cords[0] + $offset[0] - $pars[0];
  727. $newCords[1] = $cords[1] + $offset[1] + $pars[1];
  728. $newCords[2] = $cords[2] + $offset[0] + $pars[0];
  729. $newCords[3] = $cords[3] + $offset[1] + $pars[1];
  730. $newCords[4] = $cords[4] + $offset[0] + $pars[0];
  731. $newCords[5] = $cords[5] + $offset[1] - $pars[1];
  732. $newCords[6] = $cords[6] + $offset[0] - $pars[0];
  733. $newCords[7] = $cords[7] + $offset[1] - $pars[1];
  734. return $newCords;
  735. }
  736. /**
  737. * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
  738. * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
  739. * See
  740. *
  741. * @param pointer $im (See argument for PHP function imageTTFtext())
  742. * @param integer $fontSize (See argument for PHP function imageTTFtext())
  743. * @param integer $angle (See argument for PHP function imageTTFtext())
  744. * @param integer $x (See argument for PHP function imageTTFtext())
  745. * @param integer $y (See argument for PHP function imageTTFtext())
  746. * @param integer $Fcolor (See argument for PHP function imageTTFtext())
  747. * @param string $fontFile (See argument for PHP function imageTTFtext())
  748. * @param string $text (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
  749. * @param integer $spacing The spacing of letters in pixels
  750. * @param integer $wordSpacing The spacing of words in pixels
  751. * @param array $splitRenderingConf Array
  752. * @param integer $sF Scale factor
  753. * @return void
  754. * @access private
  755. */
  756. function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF = 1) {
  757. $spacing *= $sF;
  758. $wordSpacing *= $sF;
  759. if (!$spacing && $wordSpacing) {
  760. $bits = explode(' ', $text);
  761. foreach ($bits as $word) {
  762. $word .= ' ';
  763. $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf, $sF);
  764. $wordW = ($wordInf[2] - $wordInf[0]);
  765. $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
  766. $x += $wordW + $wordSpacing;
  767. }
  768. } else {
  769. $utf8Chars = $this->singleChars($text);
  770. // For each UTF-8 char, do:
  771. foreach ($utf8Chars as $char) {
  772. $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
  773. $charW = ($charInf[2] - $charInf[0]);
  774. $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
  775. $x += $charW + (($char == ' ') ? $wordSpacing : $spacing);
  776. }
  777. }
  778. }
  779. /**
  780. * Function that finds the right fontsize that will render the textstring within a certain width
  781. *
  782. * @param array $conf The TypoScript properties of the TEXT GIFBUILDER object
  783. * @return integer The new fontSize
  784. * @access private
  785. * @see tslib_gifBuilder::start()
  786. */
  787. function fontResize($conf) {
  788. // 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!!!!
  789. $maxWidth = intval($conf['maxWidth']);
  790. list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
  791. if ($maxWidth) {
  792. // If any kind of spacing applys, we use this function:
  793. if ($spacing || $wordSpacing) {
  794. return $conf['fontSize'];
  795. // ################ no calc for spacing yet !!!!!!
  796. } else {
  797. do {
  798. // Determine bounding box.
  799. $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
  800. if ($conf['angle'] < 0) {
  801. $pixelWidth = abs($bounds[4] - $bounds[0]);
  802. } elseif ($conf['angle'] > 0) {
  803. $pixelWidth = abs($bounds[2] - $bounds[6]);
  804. } else {
  805. $pixelWidth = abs($bounds[4] - $bounds[6]);
  806. }
  807. // Size is fine, exit:
  808. if ($pixelWidth <= $maxWidth) {
  809. break;
  810. } else {
  811. $conf['fontSize']--;
  812. }
  813. } while ($conf['fontSize'] > 1);
  814. }
  815. // If spacing
  816. }
  817. return $conf['fontSize'];
  818. }
  819. /**
  820. * Wrapper for ImageTTFBBox
  821. *
  822. * @param integer $fontSize (See argument for PHP function ImageTTFBBox())
  823. * @param integer $angle (See argument for PHP function ImageTTFBBox())
  824. * @param string $fontFile (See argument for PHP function ImageTTFBBox())
  825. * @param string $string (See argument for PHP function ImageTTFBBox())
  826. * @param array $splitRendering Split-rendering configuration
  827. * @param integer $sF Scale factor
  828. * @return array Information array.
  829. */
  830. function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF = 1) {
  831. // Initialize:
  832. $offsetInfo = array();
  833. $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
  834. // Traverse string parts:
  835. foreach ($stringParts as $strCfg) {
  836. $fontFile = self::prependAbsolutePath($strCfg['fontFile']);
  837. if (is_readable($fontFile)) {
  838. /**
  839. * Calculate Bounding Box for part.
  840. * Due to a PHP bug, we must retry if $calc[2] is negative.
  841. * @see https://bugs.php.net/bug.php?id=51315
  842. * @see https://bugs.php.net/bug.php?id=22513
  843. */
  844. $try = 0;
  845. do {
  846. $calc = ImageTTFBBox(
  847. t3lib_div::freetypeDpiComp($sF * $strCfg['fontSize']),
  848. $angle,
  849. $fontFile,
  850. $strCfg['str']
  851. );
  852. } while ($calc[2] < 0 && $try++ < 10);
  853. // Calculate offsets:
  854. if (!count($offsetInfo)) {
  855. // First run, just copy over.
  856. $offsetInfo = $calc;
  857. } else {
  858. $offsetInfo[2] += $calc[2] - $calc[0] + intval($splitRendering['compX']) + intval($strCfg['xSpaceBefore']) + intval($strCfg['xSpaceAfter']);
  859. $offsetInfo[3] += $calc[3] - $calc[1] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
  860. $offsetInfo[4] += $calc[4] - $calc[6] + intval($splitRendering['compX']) + intval($strCfg['xSpaceBefore']) + intval($strCfg['xSpaceAfter']);
  861. $offsetInfo[5] += $calc[5] - $calc[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
  862. }
  863. } else {
  864. debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
  865. }
  866. }
  867. return $offsetInfo;
  868. }
  869. /**
  870. * Wrapper for ImageTTFText
  871. *
  872. * @param pointer $im (See argument for PHP function imageTTFtext())
  873. * @param integer $fontSize (See argument for PHP function imageTTFtext())
  874. * @param integer $angle (See argument for PHP function imageTTFtext())
  875. * @param integer $x (See argument for PHP function imageTTFtext())
  876. * @param integer $y (See argument for PHP function imageTTFtext())
  877. * @param integer $color (See argument for PHP function imageTTFtext())
  878. * @param string $fontFile (See argument for PHP function imageTTFtext())
  879. * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
  880. * @param array $splitRendering Split-rendering configuration
  881. * @param integer $sF Scale factor
  882. * @return void
  883. */
  884. function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1) {
  885. // Initialize:
  886. $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
  887. $x = ceil($sF * $x);
  888. $y = ceil($sF * $y);
  889. // Traverse string parts:
  890. foreach ($stringParts as $i => $strCfg) {
  891. // Initialize:
  892. $colorIndex = $color;
  893. // Set custom color if any (only when niceText is off):
  894. if ($strCfg['color'] && $sF == 1) {
  895. $cols = $this->convertColor($strCfg['color']);
  896. $colorIndex = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
  897. $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
  898. }
  899. // Setting xSpaceBefore
  900. if ($i) {
  901. $x += intval($strCfg['xSpaceBefore']);
  902. $y -= intval($strCfg['ySpaceBefore']);
  903. }
  904. $fontFile = self::prependAbsolutePath($strCfg['fontFile']);
  905. if (is_readable($fontFile)) {
  906. // Render part:
  907. ImageTTFText($im, t3lib_div::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
  908. // Calculate offset to apply:
  909. $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, self::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
  910. $x += $wordInf[2] - $wordInf[0] + intval($splitRendering['compX']) + intval($strCfg['xSpaceAfter']);
  911. $y += $wordInf[5] - $wordInf[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceAfter']);
  912. } else {
  913. debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
  914. }
  915. }
  916. }
  917. /**
  918. * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
  919. *
  920. * @param string $string UTF-8 string
  921. * @param array $splitRendering Split-rendering configuration from GIFBUILDER TEXT object.
  922. * @param integer $fontSize Current fontsize
  923. * @param string $fontFile Current font file
  924. * @return array Array with input string splitted according to configuration
  925. */
  926. function splitString($string, $splitRendering, $fontSize, $fontFile) {
  927. // Initialize by setting the whole string and default configuration as the first entry.
  928. $result = array();
  929. $result[] = array(
  930. 'str' => $string,
  931. 'fontSize' => $fontSize,
  932. 'fontFile' => $fontFile
  933. );
  934. // Traverse the split-rendering configuration:
  935. // Splitting will create more entries in $result with individual configurations.
  936. if (is_array($splitRendering)) {
  937. $sKeyArray = t3lib_TStemplate::sortedKeyList($splitRendering);
  938. // Traverse configured options:
  939. foreach ($sKeyArray as $key) {
  940. $cfg = $splitRendering[$key . '.'];
  941. // Process each type of split rendering keyword:
  942. switch ((string) $splitRendering[$key]) {
  943. case 'highlightWord':
  944. if (strlen($cfg['value'])) {
  945. $newResult = array();
  946. // Traverse the current parts of the result array:
  947. foreach ($result as $part) {
  948. // Explode the string value by the word value to highlight:
  949. $explodedParts = explode($cfg['value'], $part['str']);
  950. foreach ($explodedParts as $c => $expValue) {
  951. if (strlen($expValue)) {
  952. $newResult[] = array_merge($part, array('str' => $expValue));
  953. }
  954. if ($c + 1 < count($explodedParts)) {
  955. $newResult[] = array(
  956. 'str' => $cfg['value'],
  957. 'fontSize' => $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
  958. 'fontFile' => $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
  959. 'color' => $cfg['color'],
  960. 'xSpaceBefore' => $cfg['xSpaceBefore'],
  961. 'xSpaceAfter' => $cfg['xSpaceAfter'],
  962. 'ySpaceBefore' => $cfg['ySpaceBefore'],
  963. 'ySpaceAfter' => $cfg['ySpaceAfter'],
  964. );
  965. }
  966. }
  967. }
  968. // Set the new result as result array:
  969. if (count($newResult)) {
  970. $result = $newResult;
  971. }
  972. }
  973. break;
  974. case 'charRange':
  975. if (strlen($cfg['value'])) {
  976. // Initialize range:
  977. $ranges = t3lib_div::trimExplode(',', $cfg['value'], 1);
  978. foreach ($ranges as $i => $rangeDef) {
  979. $ranges[$i] = t3lib_div::intExplode('-', $ranges[$i]);
  980. if (!isset($ranges[$i][1])) {
  981. $ranges[$i][1] = $ranges[$i][0];
  982. }
  983. }
  984. $newResult = array();
  985. // Traverse the current parts of the result array:
  986. foreach ($result as $part) {
  987. // Initialize:
  988. $currentState = -1;
  989. $bankAccum = '';
  990. // Explode the string value by the word value to highlight:
  991. $utf8Chars = $this->singleChars($part['str']);
  992. foreach ($utf8Chars as $utfChar) {
  993. // Find number and evaluate position:
  994. $uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
  995. $inRange = 0;
  996. foreach ($ranges as $rangeDef) {
  997. if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
  998. $inRange = 1;
  999. break;
  1000. }
  1001. }
  1002. if ($currentState == -1) {
  1003. $currentState = $inRange;
  1004. } // Initialize first char
  1005. // Switch bank:
  1006. if ($inRange != $currentState && !t3lib_div::inList('32,10,13,9', $uNumber)) {
  1007. // Set result:
  1008. if (strlen($bankAccum)) {
  1009. $newResult[] = array(
  1010. 'str' => $bankAccum,
  1011. 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
  1012. 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
  1013. 'color' => $currentState ? $cfg['color'] : '',
  1014. 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
  1015. 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
  1016. 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
  1017. 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
  1018. );
  1019. }
  1020. // Initialize new settings:
  1021. $currentState = $inRange;
  1022. $bankAccum = '';
  1023. }
  1024. // Add char to bank:
  1025. $bankAccum .= $utfChar;
  1026. }
  1027. // Set result for FINAL part:
  1028. if (strlen($bankAccum)) {
  1029. $newResult[] = array(
  1030. 'str' => $bankAccum,
  1031. 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
  1032. 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
  1033. 'color' => $currentState ? $cfg['color'] : '',
  1034. 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
  1035. 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
  1036. 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
  1037. 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
  1038. );
  1039. }
  1040. }
  1041. // Set the new result as result array:
  1042. if (count($newResult)) {
  1043. $result = $newResult;
  1044. }
  1045. }
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. return $result;
  1051. }
  1052. /**
  1053. * Calculates the spacing and wordSpacing values
  1054. *
  1055. * @param array $conf TypoScript array for the TEXT GIFBUILDER object
  1056. * @param integer $scaleFactor TypoScript value from eg $conf['niceText.']['scaleFactor']
  1057. * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
  1058. * @access private
  1059. * @see calcBBox()
  1060. */
  1061. function calcWordSpacing($conf, $scaleFactor = 1) {
  1062. $spacing = intval($conf['spacing']);
  1063. $wordSpacing = intval($conf['wordSpacing']);
  1064. $wordSpacing = $wordSpacing ? $wordSpacing : $spacing * 2;
  1065. $spacing *= $scaleFactor;
  1066. $wordSpacing *= $scaleFactor;
  1067. return array($spacing, $wordSpacing);
  1068. }
  1069. /**
  1070. * Calculates and returns the niceText.scaleFactor
  1071. *
  1072. * @param array $conf TypoScript array for the TEXT GIFBUILDER object
  1073. * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
  1074. * @access private
  1075. */
  1076. function getTextScalFactor($conf) {
  1077. if (!$conf['niceText']) {
  1078. $sF = 1;
  1079. } else { // NICETEXT::
  1080. $sF = t3lib_utility_Math::forceIntegerInRange($conf['niceText.']['scaleFactor'], 2, 5);
  1081. }
  1082. return $sF;
  1083. }
  1084. /**
  1085. * Renders a regular text and takes care of a possible line break automatically.
  1086. *
  1087. * @param pointer $im (See argument for PHP function imageTTFtext())
  1088. * @param integer $fontSize (See argument for PHP function imageTTFtext())
  1089. * @param integer $angle (See argument for PHP function imageTTFtext())
  1090. * @param integer $x (See argument for PHP function imageTTFtext())
  1091. * @param integer $y (See argument for PHP function imageTTFtext())
  1092. * @param integer $color (See argument for PHP function imageTTFtext())
  1093. * @param string $fontFile (See argument for PHP function imageTTFtext())
  1094. * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
  1095. * @param array $splitRendering Split-rendering configuration
  1096. * @param array $conf The configuration
  1097. * @param integer $sF Scale factor
  1098. * @return void
  1099. */
  1100. protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
  1101. if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
  1102. $phrase = '';
  1103. $currentWidth = 0;
  1104. $breakWidth = $conf['breakWidth'];
  1105. $breakSpace = $this->getBreakSpace($conf);
  1106. $wordPairs = $this->getWordPairsForLineBreak($string);
  1107. // Iterate through all word pairs:
  1108. foreach ($wordPairs as $index => $wordPair) {
  1109. $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
  1110. if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
  1111. $currentWidth += $wordWidth;
  1112. $phrase .= $wordPair;
  1113. } else {
  1114. // Render the current phrase that is below breakWidth:
  1115. $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
  1116. // Calculate the news height offset:
  1117. $y += $breakSpace;
  1118. // Restart the phrase:
  1119. $currentWidth = $wordWidth;
  1120. $phrase = $wordPair;
  1121. }
  1122. }
  1123. // Render the remaining phrase:
  1124. if ($currentWidth) {
  1125. $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
  1126. }
  1127. } else {
  1128. $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
  1129. }
  1130. }
  1131. /**
  1132. * Gets the word pairs used for automatic line breaks.
  1133. *
  1134. * @param string $string
  1135. * @return array
  1136. */
  1137. protected function getWordPairsForLineBreak($string) {
  1138. $wordPairs = array();
  1139. $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  1140. $wordsCount = count($wordsArray);
  1141. for ($index = 0; $index < $wordsCount; $index += 2) {
  1142. $wordPairs[] = $wordsArray[$index] . $wordsArray[$index + 1];
  1143. }
  1144. return $wordPairs;
  1145. }
  1146. /**
  1147. * Gets the rendered text width.
  1148. *
  1149. * @param string $text
  1150. * @param array $conf
  1151. * @param integer
  1152. */
  1153. protected function getRenderedTextWidth($text, $conf) {
  1154. $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
  1155. if ($conf['angle'] < 0) {
  1156. $pixelWidth = abs($bounds[4] - $bounds[0]);
  1157. } elseif ($conf['angle'] > 0) {
  1158. $pixelWidth = abs($bounds[2] - $bounds[6]);
  1159. } else {
  1160. $pixelWidth = abs($bounds[4] - $bounds[6]);
  1161. }
  1162. return $pixelWidth;
  1163. }
  1164. /**
  1165. * Gets the break space for each new line.
  1166. *
  1167. * @param array $conf TypoScript configuration for the currently rendered object
  1168. * @param array $boundingBox The bounding box the the currently rendered object
  1169. * @return integer The break space
  1170. */
  1171. protected function getBreakSpace($conf, array $boundingBox = NULL) {
  1172. if (!isset($boundingBox)) {
  1173. $boundingBox = $this->calcBBox($conf);
  1174. $boundingBox = $boundingBox[2];
  1175. }
  1176. if (isset($conf['breakSpace']) && $conf['breakSpace']) {
  1177. $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
  1178. } else {
  1179. $breakSpace = $boundingBox['lineHeight'];
  1180. }
  1181. return $breakSpace;
  1182. }
  1183. /***************************…

Large files files are truncated, but you can click here to view the full file