PageRenderTime 40ms 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
  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. /*********************************************
  1184. *
  1185. * Other GIFBUILDER objects related to TEXT
  1186. *
  1187. *********************************************/
  1188. /**
  1189. * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
  1190. *
  1191. * @param pointer $im GDlib image pointer
  1192. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1193. * @param array $workArea The current working area coordinates.
  1194. * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
  1195. * @return void
  1196. * @see tslib_gifBuilder::make(), makeText()
  1197. */
  1198. function makeOutline(&$im, $conf, $workArea, $txtConf) {
  1199. $thickness = intval($conf['thickness']);
  1200. if ($thickness) {
  1201. $txtConf['fontColor'] = $conf['color'];
  1202. $outLineDist = t3lib_utility_Math::forceIntegerInRange($thickness, 1, 2);
  1203. for ($b = 1; $b <= $outLineDist; $b++) {
  1204. if ($b == 1) {
  1205. $it = 8;
  1206. } else {
  1207. $it = 16;
  1208. }
  1209. $outL = $this->circleOffset($b, $it);
  1210. for ($a = 0; $a < $it; $a++) {
  1211. $this->makeText($im, $txtConf, $this->applyOffset($workArea, $outL[$a]));
  1212. }
  1213. }
  1214. }
  1215. }
  1216. /**
  1217. * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
  1218. *
  1219. * access private
  1220. *
  1221. * @param integer $distance Distance
  1222. * @param integer $iterations Iterations.
  1223. * @return array
  1224. * @see makeOutline()
  1225. */
  1226. function circleOffset($distance, $iterations) {
  1227. $res = array();
  1228. if ($distance && $iterations) {
  1229. for ($a = 0; $a < $iterations; $a++) {
  1230. $yOff = round(sin(2 * pi() / $iterations * ($a + 1)) * 100 * $distance);
  1231. if ($yOff) {
  1232. $yOff = intval(ceil(abs($yOff / 100)) * ($yOff / abs($yOff)));
  1233. }
  1234. $xOff = round(cos(2 * pi() / $iterations * ($a + 1)) * 100 * $distance);
  1235. if ($xOff) {
  1236. $xOff = intval(ceil(abs($xOff / 100)) * ($xOff / abs($xOff)));
  1237. }
  1238. $res[$a] = array($xOff, $yOff);
  1239. }
  1240. }
  1241. return $res;
  1242. }
  1243. /**
  1244. * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
  1245. *
  1246. * @param pointer $im GDlib image pointer
  1247. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1248. * @param array $workArea The current working area coordinates.
  1249. * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
  1250. * @return void
  1251. * @see tslib_gifBuilder::make(), makeShadow()
  1252. */
  1253. function makeEmboss(&$im, $conf, $workArea, $txtConf) {
  1254. $conf['color'] = $conf['highColor'];
  1255. $this->makeShadow($im, $conf, $workArea, $txtConf);
  1256. $newOffset = t3lib_div::intExplode(',', $conf['offset']);
  1257. $newOffset[0] *= -1;
  1258. $newOffset[1] *= -1;
  1259. $conf['offset'] = implode(',', $newOffset);
  1260. $conf['color'] = $conf['lowColor'];
  1261. $this->makeShadow($im, $conf, $workArea, $txtConf);
  1262. }
  1263. /**
  1264. * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
  1265. * The operation involves ImageMagick for combining.
  1266. *
  1267. * @param pointer $im GDlib image pointer
  1268. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1269. * @param array $workArea The current working area coordinates.
  1270. * @param array $txtConf TypoScript array with configuration for the associated TEXT GIFBUILDER object.
  1271. * @retur void
  1272. * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
  1273. */
  1274. function makeShadow(&$im, $conf, $workArea, $txtConf) {
  1275. $workArea = $this->applyOffset($workArea, t3lib_div::intExplode(',', $conf['offset']));
  1276. $blurRate = t3lib_utility_Math::forceIntegerInRange(intval($conf['blur']), 0, 99);
  1277. // No effects if ImageMagick ver. 5+
  1278. if (!$blurRate || $this->NO_IM_EFFECTS) {
  1279. $txtConf['fontColor'] = $conf['color'];
  1280. $this->makeText($im, $txtConf, $workArea);
  1281. } else {
  1282. $w = imagesx($im);
  1283. $h = imagesy($im);
  1284. // Area around the blur used for cropping something
  1285. $blurBorder = 3;
  1286. $tmpStr = $this->randomName();
  1287. $fileMenu = $tmpStr . '_menu.' . $this->gifExtension;
  1288. $fileColor = $tmpStr . '_color.' . $this->gifExtension;
  1289. $fileMask = $tmpStr . '_mask.' . $this->gifExtension;
  1290. // BlurColor Image laves
  1291. $blurColImg = imagecreatetruecolor($w, $h);
  1292. $bcols = $this->convertColor($conf['color']);
  1293. $Bcolor = ImageColorAllocate($blurColImg, $bcols[0], $bcols[1], $bcols[2]);
  1294. ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
  1295. $this->ImageWrite($blurColImg, $fileColor);
  1296. ImageDestroy($blurColImg);
  1297. // The mask is made: BlurTextImage
  1298. $blurTextImg = imagecreatetruecolor($w + $blurBorder * 2, $h + $blurBorder * 2);
  1299. // Black background
  1300. $Bcolor = ImageColorAllocate($blurTextImg, 0, 0, 0);
  1301. ImageFilledRectangle($blurTextImg, 0, 0, $w + $blurBorder * 2, $h + $blurBorder * 2, $Bcolor);
  1302. $txtConf['fontColor'] = 'white';
  1303. $blurBordArr = array($blurBorder, $blurBorder);
  1304. $this->makeText($blurTextImg, $txtConf, $this->applyOffset($workArea, $blurBordArr));
  1305. // Dump to temporary file
  1306. $this->ImageWrite($blurTextImg, $fileMask);
  1307. // Destroy
  1308. ImageDestroy($blurTextImg);
  1309. $command = '';
  1310. $command .= $this->maskNegate;
  1311. if ($this->V5_EFFECTS) {
  1312. $command .= $this->v5_blur($blurRate + 1);
  1313. } else {
  1314. // Blurring of the mask
  1315. // How many blur-commands that is executed. Min = 1;
  1316. $times = ceil($blurRate / 10);
  1317. // 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.
  1318. $newBlurRate = $blurRate * 4;
  1319. $newBlurRate = t3lib_utility_Math::forceIntegerInRange($newBlurRate, 1, 99);
  1320. // Building blur-command
  1321. for ($a = 0; $a < $times; $a++) {
  1322. $command .= ' -blur ' . $blurRate;
  1323. }
  1324. }
  1325. $this->imageMagickExec($fileMask, $fileMask, $command . ' +matte');
  1326. // The mask is loaded again
  1327. $blurTextImg_tmp = $this->imageCreateFromFile($fileMask);
  1328. // If nothing went wrong we continue with the blurred mask
  1329. if ($blurTextImg_tmp) {
  1330. // Cropping the border from the mask
  1331. $blurTextImg = imagecreatetruecolor($w, $h);
  1332. $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
  1333. // Destroy the temporary mask
  1334. ImageDestroy($blurTextImg_tmp);
  1335. // Adjust the mask
  1336. $intensity = 40;
  1337. if ($conf['intensity']) {
  1338. $intensity = t3lib_utility_Math::forceIntegerInRange($conf['intensity'], 0, 100);
  1339. }
  1340. $intensity = ceil(255 - ($intensity / 100 * 255));
  1341. $this->inputLevels($blurTextImg, 0, $intensity, $this->maskNegate);
  1342. $opacity = t3lib_utility_Math::forceIntegerInRange(intval($conf['opacity']), 0, 100);
  1343. if ($opacity && $opacity < 100) {
  1344. $high = ceil(255 * $opacity / 100);
  1345. // Reducing levels as the opacity demands
  1346. $this->outputLevels($blurTextImg, 0, $high, $this->maskNegate);
  1347. }
  1348. // Dump the mask again
  1349. $this->ImageWrite($blurTextImg, $fileMask);
  1350. // Destroy the mask
  1351. ImageDestroy($blurTextImg);
  1352. // The pictures are combined
  1353. // The main pictures is saved temporarily
  1354. $this->ImageWrite($im, $fileMenu);
  1355. $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
  1356. // The main image is loaded again...
  1357. $backIm = $this->imageCreateFromFile($fileMenu);
  1358. // ... and if nothing went wrong we load it onto the old one.
  1359. if ($backIm) {
  1360. if (!$this->saveAlphaLayer) {
  1361. ImageColorTransparent($backIm, -1);
  1362. }
  1363. $im = $backIm;
  1364. }
  1365. }
  1366. // Deleting temporary files;
  1367. if (!$this->dontUnlinkTempFiles) {
  1368. unlink($fileMenu);
  1369. unlink($fileColor);
  1370. unlink($fileMask);
  1371. }
  1372. }
  1373. }
  1374. /****************************
  1375. *
  1376. * Other GIFBUILDER objects
  1377. *
  1378. ****************************/
  1379. /**
  1380. * Implements the "BOX" GIFBUILDER object
  1381. *
  1382. * @param pointer $im GDlib image pointer
  1383. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1384. * @param array $workArea The current working area coordinates.
  1385. * @return void
  1386. * @see tslib_gifBuilder::make()
  1387. */
  1388. function makeBox(&$im, $conf, $workArea) {
  1389. $cords = t3lib_div::intExplode(',', $conf['dimensions'] . ',,,');
  1390. $conf['offset'] = $cords[0] . ',' . $cords[1];
  1391. $cords = $this->objPosition($conf, $workArea, array($cords[2], $cords[3]));
  1392. $cols = $this->convertColor($conf['color']);
  1393. $opacity = 0;
  1394. if (isset($conf['opacity'])) {
  1395. // conversion:
  1396. // PHP 0 = opaque, 127 = transparent
  1397. // TYPO3 100 = opaque, 0 = transparent
  1398. $opacity = t3lib_utility_Math::forceIntegerInRange(intval($conf['opacity']), 1, 100, 1);
  1399. $opacity = abs($opacity - 100);
  1400. $opacity = round((127 * $opacity) / 100);
  1401. }
  1402. $tmpColor = ImageColorAllocateAlpha($im, $cols[0], $cols[1], $cols[2], $opacity);
  1403. imagefilledrectangle($im, $cords[0], $cords[1], $cords[0] + $cords[2] - 1, $cords[1] + $cords[3] - 1, $tmpColor);
  1404. }
  1405. /**
  1406. * Implements the "Ellipse" GIFBUILDER object
  1407. * Example Typoscript:
  1408. * file = GIFBUILDER
  1409. * file {
  1410. * XY = 200,200
  1411. * format = jpg
  1412. * quality = 100
  1413. * 10 = ELLIPSE
  1414. * 10.dimensions = 100,100,50,50
  1415. * 10.color = red
  1416. *
  1417. * $workArea = X,Y
  1418. * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
  1419. *
  1420. * @param pointer $im GDlib image pointer
  1421. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1422. * @param array $workArea The current working area coordinates.
  1423. * @return void
  1424. * @see tslib_gifBuilder::make()
  1425. */
  1426. public function makeEllipse(&$im, array $conf, array $workArea) {
  1427. $ellipseConfiguration = t3lib_div::intExplode(',', $conf['dimensions'] . ',,,');
  1428. // Ellipse offset inside workArea (x/y)
  1429. $conf['offset'] = $ellipseConfiguration[0] . ',' . $ellipseConfiguration[1];
  1430. // @see objPosition
  1431. $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
  1432. $color = $this->convertColor($conf['color']);
  1433. $fillingColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
  1434. imagefilledellipse($im, $imageCoordinates[0], $imageCoordinates[1], $imageCoordinates[2], $imageCoordinates[3], $fillingColor);
  1435. }
  1436. /**
  1437. * Implements the "EFFECT" GIFBUILDER object
  1438. * The operation involves ImageMagick for applying effects
  1439. *
  1440. * @param pointer $im GDlib image pointer
  1441. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1442. * @return void
  1443. * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
  1444. */
  1445. function makeEffect(&$im, $conf) {
  1446. $commands = $this->IMparams($conf['value']);
  1447. if ($commands) {
  1448. $this->applyImageMagickToPHPGif($im, $commands);
  1449. }
  1450. }
  1451. /**
  1452. * Creating ImageMagick paramters from TypoScript property
  1453. *
  1454. * @param string $setup A string with effect keywords=value pairs separated by "|"
  1455. * @return string ImageMagick prepared parameters.
  1456. * @access private
  1457. * @see makeEffect()
  1458. */
  1459. function IMparams($setup) {
  1460. if (!trim($setup)) {
  1461. return '';
  1462. }
  1463. $effects = explode('|', $setup);
  1464. $commands = '';
  1465. foreach ($effects as $val) {
  1466. $pairs = explode('=', $val, 2);
  1467. $value = trim($pairs[1]);
  1468. $effect = strtolower(trim($pairs[0]));
  1469. switch ($effect) {
  1470. case 'gamma':
  1471. $commands .= ' -gamma ' . doubleval($value);
  1472. break;
  1473. case 'blur':
  1474. if (!$this->NO_IM_EFFECTS) {
  1475. if ($this->V5_EFFECTS) {
  1476. $commands .= $this->v5_blur($value);
  1477. } else {
  1478. $commands .= ' -blur ' . t3lib_utility_Math::forceIntegerInRange($value, 1, 99);
  1479. }
  1480. }
  1481. break;
  1482. case 'sharpen':
  1483. if (!$this->NO_IM_EFFECTS) {
  1484. if ($this->V5_EFFECTS) {
  1485. $commands .= $this->v5_sharpen($value);
  1486. } else {
  1487. $commands .= ' -sharpen ' . t3lib_utility_Math::forceIntegerInRange($value, 1, 99);
  1488. }
  1489. }
  1490. break;
  1491. case 'rotate':
  1492. $commands .= ' -rotate ' . t3lib_utility_Math::forceIntegerInRange($value, 0, 360);
  1493. break;
  1494. case 'solarize':
  1495. $commands .= ' -solarize ' . t3lib_utility_Math::forceIntegerInRange($value, 0, 99);
  1496. break;
  1497. case 'swirl':
  1498. $commands .= ' -swirl ' . t3lib_utility_Math::forceIntegerInRange($value, 0, 1000);
  1499. break;
  1500. case 'wave':
  1501. $params = t3lib_div::intExplode(',', $value);
  1502. $commands .= ' -wave ' . t3lib_utility_Math::forceIntegerInRange($params[0], 0, 99) . 'x' . t3lib_utility_Math::forceIntegerInRange($params[1], 0, 99);
  1503. break;
  1504. case 'charcoal':
  1505. $commands .= ' -charcoal ' . t3lib_utility_Math::forceIntegerInRange($value, 0, 100);
  1506. break;
  1507. case 'gray':
  1508. $commands .= ' -colorspace GRAY';
  1509. break;
  1510. case 'edge':
  1511. $commands .= ' -edge ' . t3lib_utility_Math::forceIntegerInRange($value, 0, 99);
  1512. break;
  1513. case 'emboss':
  1514. $commands .= ' -emboss';
  1515. break;
  1516. case 'flip':
  1517. $commands .= ' -flip';
  1518. break;
  1519. case 'flop':
  1520. $commands .= ' -flop';
  1521. break;
  1522. case 'colors':
  1523. $commands .= ' -colors ' . t3lib_utility_Math::forceIntegerInRange($value, 2, 255);
  1524. break;
  1525. case 'shear':
  1526. $commands .= ' -shear ' . t3lib_utility_Math::forceIntegerInRange($value, -90, 90);
  1527. break;
  1528. case 'invert':
  1529. $commands .= ' -negate';
  1530. break;
  1531. }
  1532. }
  1533. return $commands;
  1534. }
  1535. /**
  1536. * Implements the "ADJUST" GIFBUILDER object
  1537. *
  1538. * @param pointer $im GDlib image pointer
  1539. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1540. * @return void
  1541. * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
  1542. */
  1543. function adjust(&$im, $conf) {
  1544. $setup = $conf['value'];
  1545. if (!trim($setup)) {
  1546. return '';
  1547. }
  1548. $effects = explode('|', $setup);
  1549. foreach ($effects as $val) {
  1550. $pairs = explode('=', $val, 2);
  1551. $value = trim($pairs[1]);
  1552. $effect = strtolower(trim($pairs[0]));
  1553. switch ($effect) {
  1554. case 'inputlevels': // low,high
  1555. $params = t3lib_div::intExplode(',', $value);
  1556. $this->inputLevels($im, $params[0], $params[1]);
  1557. break;
  1558. case 'outputlevels':
  1559. $params = t3lib_div::intExplode(',', $value);
  1560. $this->outputLevels($im, $params[0], $params[1]);
  1561. break;
  1562. case 'autolevels':
  1563. $this->autoLevels($im);
  1564. break;
  1565. }
  1566. }
  1567. }
  1568. /**
  1569. * Implements the "CROP" GIFBUILDER object
  1570. *
  1571. * @param pointer $im GDlib image pointer
  1572. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1573. * @return void
  1574. * @see tslib_gifBuilder::make()
  1575. */
  1576. function crop(&$im, $conf) {
  1577. // Clears workArea to total image
  1578. $this->setWorkArea('');
  1579. $cords = t3lib_div::intExplode(',', $conf['crop'] . ',,,');
  1580. $conf['offset'] = $cords[0] . ',' . $cords[1];
  1581. $cords = $this->objPosition($conf, $this->workArea, array($cords[2], $cords[3]));
  1582. $newIm = imagecreatetruecolor($cords[2], $cords[3]);
  1583. $cols = $this->convertColor($conf['backColor'] ? $conf['backColor'] : $this->setup['backColor']);
  1584. $Bcolor = ImageColorAllocate($newIm, $cols[0], $cols[1], $cols[2]);
  1585. ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
  1586. $newConf = array();
  1587. $workArea = array(0, 0, $cords[2], $cords[3]);
  1588. if ($cords[0] < 0) {
  1589. $workArea[0] = abs($cords[0]);
  1590. } else {
  1591. $newConf['offset'] = -$cords[0];
  1592. }
  1593. if ($cords[1] < 0) {
  1594. $workArea[1] = abs($cords[1]);
  1595. } else {
  1596. $newConf['offset'] .= ',' . -$cords[1];
  1597. }
  1598. $this->copyGifOntoGif($newIm, $im, $newConf, $workArea);
  1599. $im = $newIm;
  1600. $this->w = imagesx($im);
  1601. $this->h = imagesy($im);
  1602. // Clears workArea to total image
  1603. $this->setWorkArea('');
  1604. }
  1605. /**
  1606. * Implements the "SCALE" GIFBUILDER object
  1607. *
  1608. * @param pointer $im GDlib image pointer
  1609. * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
  1610. * @return void
  1611. * @see tslib_gifBuilder::make()
  1612. */
  1613. function scale(&$im, $conf) {
  1614. if ($conf['width'] || $conf['height'] || $conf['params']) {
  1615. $tmpStr = $this->randomName();
  1616. $theFile = $tmpStr . '.' . $this->gifExtension;
  1617. $this->ImageWrite($im, $theFile);
  1618. $theNewFile = $this->imageMagickConvert($theFile, $this->gifExtension, $conf['width'], $conf['height'], $conf['params'], '', '');
  1619. $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
  1620. if ($tmpImg) {
  1621. ImageDestroy($im);
  1622. $im = $tmpImg;
  1623. $this->w = imagesx($im);
  1624. $this->h = imagesy($im);
  1625. // Clears workArea to total image
  1626. $this->setWorkArea('');
  1627. }
  1628. if (!$this->dontUnlinkTempFiles) {
  1629. unlink($theFile);
  1630. if ($theNewFile[3] && $theNewFile[3] != $theFile) {
  1631. unlink($theNewFile[3]);
  1632. }
  1633. }
  1634. }
  1635. }
  1636. /**
  1637. * Implements the "WORKAREA" GIFBUILDER object when setting it
  1638. * Setting internal working area boundaries (->workArea)
  1639. *
  1640. * @param string $workArea Working area dimensions, comma separated
  1641. * @return void
  1642. * @access private
  1643. * @see tslib_gifBuilder::make()
  1644. */
  1645. function setWorkArea($workArea) {
  1646. $this->workArea = t3lib_div::intExplode(',', $workArea);
  1647. $this->workArea = $this->applyOffset($this->workArea, $this->OFFSET);
  1648. if (!$this->workArea[2]) {
  1649. $this->workArea[2] = $this->w;
  1650. }
  1651. if (!$this->workArea[3]) {
  1652. $this->workArea[3] = $this->h;
  1653. }
  1654. }
  1655. /*************************
  1656. *
  1657. * Adjustment functions
  1658. *
  1659. ************************/
  1660. /**
  1661. * Apply auto-levels to input image pointer
  1662. *
  1663. * @param integer $im GDlib Image Pointer
  1664. * @return void
  1665. */
  1666. function autolevels(&$im) {
  1667. $totalCols = ImageColorsTotal($im);
  1668. $min = 255;
  1669. $max = 0;
  1670. for ($c = 0; $c < $totalCols; $c++) {
  1671. $cols = ImageColorsForIndex($im, $c);
  1672. $grayArr[] = round(($cols['red'] + $cols['green'] + $cols['blue']) / 3);
  1673. }
  1674. $min = min($grayArr);
  1675. $max = max($grayArr);
  1676. $delta = $max - $min;
  1677. if ($delta) {
  1678. for ($c = 0; $c < $totalCols; $c++) {
  1679. $cols = ImageColorsForIndex($im, $c);
  1680. $cols['red'] = floor(($cols['red'] - $min) / $delta * 255);
  1681. $cols['green'] = floor(($cols['green'] - $min) / $delta * 255);
  1682. $cols['blue'] = floor(($cols['blue'] - $min) / $delta * 255);
  1683. ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
  1684. }
  1685. }
  1686. }
  1687. /**
  1688. * Apply output levels to input image pointer (decreasing contrast)
  1689. *
  1690. * @param integer $im GDlib Image Pointer
  1691. * @param integer $low The "low" value (close to 0)
  1692. * @param integer $high The "high" value (close to 255)
  1693. * @param boolean $swap If swap, then low and high are swapped. (Useful for negated masks...)
  1694. * @return void
  1695. */
  1696. function outputLevels(&$im, $low, $high, $swap = '') {
  1697. if ($low < $high) {
  1698. $low = t3lib_utility_Math::forceIntegerInRange($low, 0, 255);
  1699. $high = t3lib_utility_Math::forceIntegerInRange($high, 0, 255);
  1700. if ($swap) {
  1701. $temp = $low;
  1702. $low = 255 - $high;
  1703. $high = 255 - $temp;
  1704. }
  1705. $delta = $high - $low;
  1706. $totalCols = ImageColorsTotal($im);
  1707. for ($c = 0; $c < $totalCols; $c++) {
  1708. $cols = ImageColorsForIndex($im, $c);
  1709. $cols['red'] = $low + floor($cols['red'] / 255 * $delta);
  1710. $cols['green'] = $low + floor($cols['green'] / 255 * $delta);
  1711. $cols['blue'] = $low + floor($cols['blue'] / 255 * $delta);
  1712. ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
  1713. }
  1714. }
  1715. }
  1716. /**
  1717. * Apply input levels to input image pointer (increasing contrast)
  1718. *
  1719. * @param integer $im GDlib Image Pointer
  1720. * @param integer $low The "low" value (close to 0)
  1721. * @param integer $high The "high" value (close to 255)
  1722. * @param boolean $swap If swap, then low and high are swapped. (Useful for negated masks...)
  1723. * @return void
  1724. */
  1725. function inputLevels(&$im, $low, $high, $swap = '') {
  1726. if ($low < $high) {
  1727. $low = t3lib_utility_Math::forceIntegerInRange($low, 0, 255);
  1728. $high = t3lib_utility_Math::forceIntegerInRange($high, 0, 255);
  1729. if ($swap) {
  1730. $temp = $low;
  1731. $low = 255 - $high;
  1732. $high = 255 - $temp;
  1733. }
  1734. $delta = $high - $low;
  1735. $totalCols = ImageColorsTotal($im);
  1736. for ($c = 0; $c < $totalCols; $c++) {
  1737. $cols = ImageColorsForIndex($im, $c);
  1738. $cols['red'] = t3lib_utility_Math::forceIntegerInRange(($cols['red'] - $low) / $delta * 255, 0, 255);
  1739. $cols['green'] = t3lib_utility_Math::forceIntegerInRange(($cols['green'] - $low) / $delta * 255, 0, 255);
  1740. $cols['blue'] = t3lib_utility_Math::forceIntegerInRange(($cols['blue'] - $low) / $delta * 255, 0, 255);
  1741. ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
  1742. }
  1743. }
  1744. }
  1745. /**
  1746. * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
  1747. *
  1748. * @param string $file Image file to reduce
  1749. * @param integer $cols Number of colors to reduce the image to.
  1750. * @return string Reduced file
  1751. */
  1752. function IMreduceColors($file, $cols) {
  1753. $fI = t3lib_div::split_fileref($file);
  1754. $ext = strtolower($fI['fileext']);
  1755. $result = $this->randomName() . '.' . $ext;
  1756. if (($reduce = t3lib_utility_Math::forceIntegerInRange($cols, 0, ($ext == 'gif' ? 256 : $this->truecolorColors), 0)) > 0) {
  1757. $params = ' -colors ' . $reduce;
  1758. if ($reduce <= 256) {
  1759. $params .= ' -type Palette';
  1760. }
  1761. if ($ext == 'png' && $reduce <= 256) {
  1762. $prefix = 'png8:';
  1763. }
  1764. $this->imageMagickExec($file, $prefix . $result, $params);
  1765. if ($result) {
  1766. return $result;
  1767. }
  1768. }
  1769. return '';
  1770. }
  1771. /*********************************
  1772. *
  1773. * GIFBUILDER Helper functions
  1774. *
  1775. *********************************/
  1776. /**
  1777. * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
  1778. * Use PATH_site unless we are in the backend.
  1779. * Call it by t3lib_stdGraphic::prependAbsolutePath()
  1780. *
  1781. * @param string $fontFile The font file
  1782. * @return string The font file with absolute path.
  1783. */
  1784. function prependAbsolutePath($fontFile) {
  1785. $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript) . '/' : PATH_site;
  1786. $fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : t3lib_div::resolveBackPath($absPath . $fontFile);
  1787. return $fontFile;
  1788. }
  1789. /**
  1790. * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
  1791. * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
  1792. *
  1793. * @param integer $factor The sharpening factor, 0-100 (effectively in 10 steps)
  1794. * @return string The sharpening command, eg. " -sharpen 3x4"
  1795. * @see makeText(), IMparams(), v5_blur()
  1796. */
  1797. function v5_sharpen($factor) {
  1798. $factor = t3lib_utility_Math::forceIntegerInRange(ceil($factor / 10), 0, 10);
  1799. $sharpenArr = explode(',', ',' . $this->im5fx_sharpenSteps);
  1800. $sharpenF = trim($sharpenArr[$factor]);
  1801. if ($sharpenF) {
  1802. $cmd = ' -sharpen ' . $sharpenF;
  1803. return $cmd;
  1804. }
  1805. }
  1806. /**
  1807. * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
  1808. * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
  1809. *
  1810. * @param integer $factor The blurring factor, 0-100 (effectively in 10 steps)
  1811. * @return string The blurring command, eg. " -blur 3x4"
  1812. * @see makeText(), IMparams(), v5_sharpen()
  1813. */
  1814. function v5_blur($factor) {
  1815. $factor = t3lib_utility_Math::forceIntegerInRange(ceil($factor / 10), 0, 10);
  1816. $blurArr = explode(',', ',' . $this->im5fx_blurSteps);
  1817. $blurF = trim($blurArr[$factor]);
  1818. if ($blurF) {
  1819. $cmd = ' -blur ' . $blurF;
  1820. return $cmd;
  1821. }
  1822. }
  1823. /**
  1824. * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
  1825. * 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.
  1826. *
  1827. * @return string
  1828. */
  1829. function randomName() {
  1830. $this->createTempSubDir('temp/');
  1831. return $this->tempPath . 'temp/' . md5(uniqid(''));
  1832. }
  1833. /**
  1834. * Applies offset value to coordinated in $cords.
  1835. * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
  1836. *
  1837. * @param array $cords Integer coordinates in key 0/1
  1838. * @param array $OFFSET Offset values in key 0/1
  1839. * @return array Modified $cords array
  1840. */
  1841. function applyOffset($cords, $OFFSET) {
  1842. $cords[0] = intval($cords[0]) + intval($OFFSET[0]);
  1843. $cords[1] = intval($cords[1]) + intval($OFFSET[1]);
  1844. return $cords;
  1845. }
  1846. /**
  1847. * Converts a "HTML-color" TypoScript datatype to RGB-values.
  1848. * Default is 0,0,0
  1849. *
  1850. * @param string $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
  1851. * @return array RGB values in key 0/1/2 of the array
  1852. */
  1853. function convertColor($string) {
  1854. $col = array();
  1855. $cParts = explode(':', $string, 2);
  1856. // Finding the RGB definitions of the color:
  1857. $string = $cParts[0];
  1858. if (strstr($string, '#')) {
  1859. $string = preg_replace('/[^A-Fa-f0-9]*/', '', $string);
  1860. $col[] = HexDec(substr($string, 0, 2));
  1861. $col[] = HexDec(substr($string, 2, 2));
  1862. $col[] = HexDec(substr($string, 4, 2));
  1863. } elseif (strstr($string, ',')) {
  1864. $string = preg_replace('/[^,0-9]*/', '', $string);
  1865. $strArr = explode(',', $string);
  1866. $col[] = intval($strArr[0]);
  1867. $col[] = intval($strArr[1]);
  1868. $col[] = intval($strArr[2]);
  1869. } else {
  1870. $string = strtolower(trim($string));
  1871. if ($this->colMap[$string]) {
  1872. $col = $this->colMap[$string];
  1873. } else {
  1874. $col = array(0, 0, 0);
  1875. }
  1876. }
  1877. // ... and possibly recalculating the value
  1878. if (trim($cParts[1])) {
  1879. $cParts[1] = trim($cParts[1]);
  1880. if (substr($cParts[1], 0, 1) == '*') {
  1881. $val = doubleval(substr($cParts[1], 1));
  1882. $col[0] = t3lib_utility_Math::forceIntegerInRange($col[0] * $val, 0, 255);
  1883. $col[1] = t3lib_utility_Math::forceIntegerInRange($col[1] * $val, 0, 255);
  1884. $col[2] = t3lib_utility_Math::forceIntegerInRange($col[2] * $val, 0, 255);
  1885. } else {
  1886. $val = intval($cParts[1]);
  1887. $col[0] = t3lib_utility_Math::forceIntegerInRange($col[0] + $val, 0, 255);
  1888. $col[1] = t3lib_utility_Math::forceIntegerInRange($col[1] + $val, 0, 255);
  1889. $col[2] = t3lib_utility_Math::forceIntegerInRange($col[2] + $val, 0, 255);
  1890. }
  1891. }
  1892. return $col;
  1893. }
  1894. /**
  1895. * Recode string
  1896. * Used with text strings for fonts when languages has other character sets.
  1897. *
  1898. * @param string The text to recode
  1899. * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
  1900. */
  1901. function recodeString($string) {
  1902. // Recode string to UTF-8 from $this->nativeCharset:
  1903. if ($this->nativeCharset && $this->nativeCharset != 'utf-8') {
  1904. // Convert to UTF-8
  1905. $string = $this->csConvObj->utf8_encode($string, $this->nativeCharset);
  1906. }
  1907. return $string;
  1908. }
  1909. /**
  1910. * Split a string into an array of individual characters
  1911. * 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.
  1912. *
  1913. * @param string $theText The text string to split
  1914. * @param boolean $returnUnicodeNumber Return Unicode numbers instead of chars.
  1915. * @return array Numerical array with a char as each value.
  1916. */
  1917. function singleChars($theText, $returnUnicodeNumber = FALSE) {
  1918. if ($this->nativeCharset) {
  1919. // Get an array of separated UTF-8 chars
  1920. return $this->csConvObj->utf8_to_numberarray($theText, 1, $returnUnicodeNumber ? 0 : 1);
  1921. } else {
  1922. $output = array();
  1923. $c = strlen($theText);
  1924. for ($a = 0; $a < $c; $a++) {
  1925. $output[] = substr($theText, $a, 1);
  1926. }
  1927. return $output;
  1928. }
  1929. }
  1930. /**
  1931. * 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
  1932. *
  1933. * @param array $conf TypoScript configuration for a GIFBUILDER object
  1934. * @param array makeBox Workarea definition
  1935. * @param array $BB BB (Bounding box) array. Not just used for TEXT objects but also for others
  1936. * @return array [0]=x, [1]=y, [2]=w, [3]=h
  1937. * @access private
  1938. * @see copyGifOntoGif(), makeBox(), crop()
  1939. */
  1940. function objPosition($conf, $workArea, $BB) {
  1941. // offset, align, valign, workarea
  1942. $result = array();
  1943. $result[2] = $BB[0];
  1944. $result[3] = $BB[1];
  1945. $w = $workArea[2];
  1946. $h = $workArea[3];
  1947. $align = explode(',', $conf['align']);
  1948. $align[0] = strtolower(substr(trim($align[0]), 0, 1));
  1949. $align[1] = strtolower(substr(trim($align[1]), 0, 1));
  1950. switch ($align[0]) {
  1951. case 'r':
  1952. $result[0] = $w - $result[2];
  1953. break;
  1954. case 'c':
  1955. $result[0] = round(($w - $result[2]) / 2);
  1956. break;
  1957. default:
  1958. $result[0] = 0;
  1959. break;
  1960. }
  1961. switch ($align[1]) {
  1962. case 'b':
  1963. // y pos
  1964. $result[1] = $h - $result[3];
  1965. break;
  1966. case 'c':
  1967. $result[1] = round(($h - $result[3]) / 2);
  1968. break;
  1969. default:
  1970. $result[1] = 0;
  1971. break;
  1972. }
  1973. $result = $this->applyOffset($result, t3lib_div::intExplode(',', $conf['offset']));
  1974. $result = $this->applyOffset($result, $workArea);
  1975. return $result;
  1976. }
  1977. /***********************************
  1978. *
  1979. * Scaling, Dimensions of images
  1980. *
  1981. ***********************************/
  1982. /**
  1983. * Converts $imagefile to another file in temp-dir of type $newExt (extension).
  1984. *
  1985. * @param string $imagefile The image filepath
  1986. * @param string $newExt 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.
  1987. * @param string $w 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
  1988. * @param string $h Height. See $w
  1989. * @param string $params Additional ImageMagick parameters.
  1990. * @param string $frame 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...
  1991. * @param array $options An array with options passed to getImageScale (see this function).
  1992. * @param boolean $mustCreate 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.
  1993. * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
  1994. * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
  1995. */
  1996. function imageMagickConvert($imagefile, $newExt = '', $w = '', $h = '', $params = '', $frame = '', $options = '', $mustCreate = 0) {
  1997. if ($this->NO_IMAGE_MAGICK) {
  1998. // Returning file info right away
  1999. return $this->getImageDimensions($imagefile);
  2000. }
  2001. if ($info = $this->getImageDimensions($imagefile)) {
  2002. $newExt = strtolower(trim($newExt));
  2003. // If no extension is given the original extension is used
  2004. if (!$newExt) {
  2005. $newExt = $info[2];
  2006. }
  2007. if ($newExt == 'web') {
  2008. if (t3lib_div::inList($this->webImageExt, $info[2])) {
  2009. $newExt = $info[2];
  2010. } else {
  2011. $newExt = $this->gif_or_jpg($info[2], $info[0], $info[1]);
  2012. if (!$params) {
  2013. $params = $this->cmds[$newExt];
  2014. }
  2015. }
  2016. }
  2017. if (t3lib_div::inList($this->imageFileExt, $newExt)) {
  2018. if (strstr($w . $h, 'm')) {
  2019. $max = 1;
  2020. } else {
  2021. $max = 0;
  2022. }
  2023. $data = $this->getImageScale($info, $w, $h, $options);
  2024. $w = $data['origW'];
  2025. $h = $data['origH'];
  2026. // If no conversion should be performed
  2027. // this flag is TRUE if the width / height does NOT dictate
  2028. // the image to be scaled!! (that is if no width / height is
  2029. // given or if the destination w/h matches the original image
  2030. // dimensions or if the option to not scale the image is set)
  2031. $noScale = (!$w && !$h) || ($data[0] == $info[0] && $data[1] == $info[1]) || $options['noScale'];
  2032. if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
  2033. // Set the new width and height before returning,
  2034. // if the noScale option is set
  2035. if ($options['noScale']) {
  2036. $info[0] = $data[0];
  2037. $info[1] = $data[1];
  2038. }
  2039. $info[3] = $imagefile;
  2040. return $info;
  2041. }
  2042. $info[0] = $data[0];
  2043. $info[1] = $data[1];
  2044. $frame = $this->noFramePrepended ? '' : intval($frame);
  2045. if (!$params) {
  2046. $params = $this->cmds[$newExt];
  2047. }
  2048. // Cropscaling:
  2049. if ($data['crs']) {
  2050. if (!$data['origW']) {
  2051. $data['origW'] = $data[0];
  2052. }
  2053. if (!$data['origH']) {
  2054. $data['origH'] = $data[1];
  2055. }
  2056. $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH'] + 100) / 200);
  2057. $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV'] + 100) / 200);
  2058. $params .= ' -crop ' . $data['origW'] . 'x' . $data['origH'] . '+' . $offsetX . '+' . $offsetY . ' ';
  2059. }
  2060. $command = $this->scalecmd . ' ' . $info[0] . 'x' . $info[1] . '! ' . $params . ' ';
  2061. $cropscale = ($data['crs'] ? 'crs-V' . $data['cropV'] . 'H' . $data['cropH'] : '');
  2062. if ($this->alternativeOutputKey) {
  2063. $theOutputName = t3lib_div::shortMD5($command . $cropscale . basename($imagefile) . $this->alternativeOutputKey . '[' . $frame . ']');
  2064. } else {
  2065. $theOutputName = t3lib_div::shortMD5($command . $cropscale . $imagefile . filemtime($imagefile) . '[' . $frame . ']');
  2066. }
  2067. if ($this->imageMagickConvert_forceFileNameBody) {
  2068. $theOutputName = $this->imageMagickConvert_forceFileNameBody;
  2069. $this->imageMagickConvert_forceFileNameBody = '';
  2070. }
  2071. // Making the temporary filename:
  2072. $this->createTempSubDir('pics/');
  2073. $output = $this->absPrefix . $this->tempPath . 'pics/' . $this->filenamePrefix . $theOutputName . '.' . $newExt;
  2074. // Register temporary filename:
  2075. $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
  2076. if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
  2077. $this->imageMagickExec($imagefile, $output, $command, $frame);
  2078. }
  2079. if (file_exists($output)) {
  2080. $info[3] = $output;
  2081. $info[2] = $newExt;
  2082. // params could realisticly change some imagedata!
  2083. if ($params) {
  2084. $info = $this->getImageDimensions($info[3]);
  2085. }
  2086. if ($info[2] == $this->gifExtension && !$this->dontCompress) {
  2087. // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
  2088. t3lib_div::gif_compress($info[3], '');
  2089. }
  2090. return $info;
  2091. }
  2092. }
  2093. }
  2094. }
  2095. /**
  2096. * Gets the input image dimensions.
  2097. *
  2098. * @param string $imageFile The image filepath
  2099. * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
  2100. * @see imageMagickConvert(), tslib_cObj::getImgResource()
  2101. */
  2102. function getImageDimensions($imageFile) {
  2103. preg_match('/([^\.]*)$/', $imageFile, $reg);
  2104. if (file_exists($imageFile) && t3lib_div::inList($this->imageFileExt, strtolower($reg[0]))) {
  2105. if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
  2106. return $returnArr;
  2107. } else {
  2108. if ($temp = @getImageSize($imageFile)) {
  2109. $returnArr = array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
  2110. } else {
  2111. $returnArr = $this->imageMagickIdentify($imageFile);
  2112. }
  2113. if ($returnArr) {
  2114. $this->cacheImageDimensions($returnArr);
  2115. return $returnArr;
  2116. }
  2117. }
  2118. }
  2119. return FALSE;
  2120. }
  2121. /**
  2122. * Cache the result of the getImageDimensions function into the database. Does not check if the
  2123. * file exists!
  2124. *
  2125. * @param array $identifyResult Result of the getImageDimensions function
  2126. * @return boolean TRUE if operation was successful
  2127. */
  2128. function cacheImageDimensions($identifyResult) {
  2129. // Create md5 hash of filemtime and filesize
  2130. $md5Hash = md5(filemtime($identifyResult[3]) . filesize($identifyResult[3]));
  2131. $result = FALSE;
  2132. if ($md5Hash) {
  2133. $fieldArray = array(
  2134. 'md5hash' => $md5Hash,
  2135. 'md5filename' => md5($identifyResult[3]),
  2136. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2137. 'filename' => $identifyResult[3],
  2138. 'imagewidth' => $identifyResult[0],
  2139. 'imageheight' => $identifyResult[1],
  2140. );
  2141. $GLOBALS['TYPO3_DB']->exec_INSERTquery(
  2142. 'cache_imagesizes',
  2143. $fieldArray
  2144. );
  2145. if (!$err = $GLOBALS['TYPO3_DB']->sql_error()) {
  2146. $result = TRUE;
  2147. }
  2148. }
  2149. return $result;
  2150. }
  2151. /**
  2152. * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
  2153. *
  2154. * @param string $imageFile The image filepath
  2155. * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
  2156. */
  2157. function getCachedImageDimensions($imageFile) {
  2158. // Create md5 hash of filemtime and filesize
  2159. $md5Hash = md5(filemtime($imageFile) . filesize($imageFile));
  2160. $cachedImageDimensions = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
  2161. 'md5hash, md5filename, imagewidth, imageheight',
  2162. 'cache_imagesizes',
  2163. 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(md5($imageFile), 'cache_imagesizes')
  2164. );
  2165. $result = FALSE;
  2166. if (is_array($cachedImageDimensions)) {
  2167. if ($cachedImageDimensions['md5hash'] != $md5Hash) {
  2168. // File has changed, delete the row
  2169. $GLOBALS['TYPO3_DB']->exec_DELETEquery(
  2170. 'cache_imagesizes',
  2171. 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($cachedImageDimensions['md5filename'], 'cache_imagesizes')
  2172. );
  2173. } else {
  2174. preg_match('/([^\.]*)$/', $imageFile, $imageExtension);
  2175. $result = array(
  2176. (int)$cachedImageDimensions['imagewidth'],
  2177. (int)$cachedImageDimensions['imageheight'],
  2178. strtolower($imageExtension[0]),
  2179. $imageFile,
  2180. );
  2181. }
  2182. }
  2183. return $result;
  2184. }
  2185. /**
  2186. * Get numbers for scaling the image based on input
  2187. *
  2188. * @param array $info Current image information: Width, Height etc.
  2189. * @param integer $w "required" width
  2190. * @param integer $h "required" height
  2191. * @param array $options Options: Keys are like "maxW", "maxH", "minW", "minH"
  2192. * @return array
  2193. * @access private
  2194. * @see imageMagickConvert()
  2195. */
  2196. function getImageScale($info, $w, $h, $options) {
  2197. if (strstr($w . $h, 'm')) {
  2198. $max = 1;
  2199. } else {
  2200. $max = 0;
  2201. }
  2202. if (strstr($w . $h, 'c')) {
  2203. $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
  2204. $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
  2205. $crs = TRUE;
  2206. } else {
  2207. $crs = FALSE;
  2208. }
  2209. $out['crs'] = $crs;
  2210. $w = intval($w);
  2211. $h = intval($h);
  2212. // If there are max-values...
  2213. if ($options['maxW']) {
  2214. // If width is given...
  2215. if ($w) {
  2216. if ($w > $options['maxW']) {
  2217. $w = $options['maxW'];
  2218. // Height should follow
  2219. $max = 1;
  2220. }
  2221. } else {
  2222. if ($info[0] > $options['maxW']) {
  2223. $w = $options['maxW'];
  2224. // Height should follow
  2225. $max = 1;
  2226. }
  2227. }
  2228. }
  2229. if ($options['maxH']) {
  2230. // If height is given...
  2231. if ($h) {
  2232. if ($h > $options['maxH']) {
  2233. $h = $options['maxH'];
  2234. // Height should follow
  2235. $max = 1;
  2236. }
  2237. } else {
  2238. // Changed [0] to [1] 290801
  2239. if ($info[1] > $options['maxH']) {
  2240. $h = $options['maxH'];
  2241. // Height should follow
  2242. $max = 1;
  2243. }
  2244. }
  2245. }
  2246. $out['origW'] = $w;
  2247. $out['origH'] = $h;
  2248. $out['max'] = $max;
  2249. if (!$this->mayScaleUp) {
  2250. if ($w > $info[0]) {
  2251. $w = $info[0];
  2252. }
  2253. if ($h > $info[1]) {
  2254. $h = $info[1];
  2255. }
  2256. }
  2257. // If scaling should be performed
  2258. if ($w || $h) {
  2259. if ($w && !$h) {
  2260. $info[1] = ceil($info[1] * ($w / $info[0]));
  2261. $info[0] = $w;
  2262. }
  2263. if (!$w && $h) {
  2264. $info[0] = ceil($info[0] * ($h / $info[1]));
  2265. $info[1] = $h;
  2266. }
  2267. if ($w && $h) {
  2268. if ($max) {
  2269. $ratio = $info[0] / $info[1];
  2270. if ($h * $ratio > $w) {
  2271. $h = round($w / $ratio);
  2272. } else {
  2273. $w = round($h * $ratio);
  2274. }
  2275. }
  2276. if ($crs) {
  2277. $ratio = $info[0] / $info[1];
  2278. if ($h * $ratio < $w) {
  2279. $h = round($w / $ratio);
  2280. } else {
  2281. $w = round($h * $ratio);
  2282. }
  2283. }
  2284. $info[0] = $w;
  2285. $info[1] = $h;
  2286. }
  2287. }
  2288. $out[0] = $info[0];
  2289. $out[1] = $info[1];
  2290. // Set minimum-measures!
  2291. if ($options['minW'] && $out[0] < $options['minW']) {
  2292. if (($max || $crs) && $out[0]) {
  2293. $out[1] = round($out[1] * $options['minW'] / $out[0]);
  2294. }
  2295. $out[0] = $options['minW'];
  2296. }
  2297. if ($options['minH'] && $out[1] < $options['minH']) {
  2298. if (($max || $crs) && $out[1]) {
  2299. $out[0] = round($out[0] * $options['minH'] / $out[1]);
  2300. }
  2301. $out[1] = $options['minH'];
  2302. }
  2303. return $out;
  2304. }
  2305. /**
  2306. * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
  2307. *
  2308. * @param string $output Output imagefile
  2309. * @param string $orig Original basis file
  2310. * @return boolean Returns TRUE if the file is already being made; thus "TRUE" means "Don't render the image again"
  2311. * @access private
  2312. */
  2313. function file_exists_typo3temp_file($output, $orig = '') {
  2314. if ($this->enable_typo3temp_db_tracking) {
  2315. // If file exists, then we return immediately
  2316. if (file_exists($output)) {
  2317. return 1;
  2318. } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
  2319. $md5Hash = md5($output);
  2320. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  2321. 'md5hash',
  2322. 'cache_typo3temp_log',
  2323. 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
  2324. );
  2325. // If there was a record, the image is being generated by another proces (we assume)
  2326. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  2327. if (is_object($GLOBALS['TSFE'])) {
  2328. $GLOBALS['TSFE']->set_no_cache();
  2329. } // ...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...)
  2330. if (is_object($GLOBALS['TT'])) {
  2331. $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: ' . $output);
  2332. }
  2333. // Return 'success - 2'
  2334. return 2;
  2335. } 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.
  2336. $insertFields = array(
  2337. 'md5hash' => $md5Hash,
  2338. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2339. 'filename' => $output,
  2340. 'orig_filename' => $orig
  2341. );
  2342. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
  2343. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
  2344. if (is_object($GLOBALS['TT'])) {
  2345. $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: ' . $output);
  2346. }
  2347. return 0;
  2348. }
  2349. }
  2350. } else {
  2351. return file_exists($output);
  2352. }
  2353. }
  2354. /***********************************
  2355. *
  2356. * ImageMagick API functions
  2357. *
  2358. ***********************************/
  2359. /**
  2360. * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
  2361. * Using ImageMagick
  2362. *
  2363. * @param string $imagefile The relative (to PATH_site) image filepath
  2364. * @return array
  2365. */
  2366. function imageMagickIdentify($imagefile) {
  2367. if (!$this->NO_IMAGE_MAGICK) {
  2368. $frame = $this->noFramePrepended ? '' : '[0]';
  2369. $cmd = t3lib_div::imageMagickCommand('identify', $this->wrapFileName($imagefile) . $frame);
  2370. $returnVal = array();
  2371. t3lib_utility_Command::exec($cmd, $returnVal);
  2372. $splitstring = $returnVal[0];
  2373. $this->IM_commands[] = array('identify', $cmd, $returnVal[0]);
  2374. if ($splitstring) {
  2375. preg_match('/([^\.]*)$/', $imagefile, $reg);
  2376. $splitinfo = explode(' ', $splitstring);
  2377. foreach ($splitinfo as $key => $val) {
  2378. $temp = '';
  2379. if ($val) {
  2380. $temp = explode('x', $val);
  2381. }
  2382. if (intval($temp[0]) && intval($temp[1])) {
  2383. $dim = $temp;
  2384. break;
  2385. }
  2386. }
  2387. if ($dim[0] && $dim[1]) {
  2388. return array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
  2389. }
  2390. }
  2391. }
  2392. }
  2393. /**
  2394. * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
  2395. * Can be used for many things, mostly scaling and effects.
  2396. *
  2397. * @param string $input The relative (to PATH_site) image filepath, input file (read from)
  2398. * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
  2399. * @param string $params ImageMagick parameters
  2400. * @param integer $frame Optional, refers to which frame-number to select in the image. '' or 0
  2401. * will select the first frame, 1 will select the next and so on...
  2402. * @return string The result of a call to PHP function "exec()"
  2403. */
  2404. function imageMagickExec($input, $output, $params, $frame = 0) {
  2405. if (!$this->NO_IMAGE_MAGICK) {
  2406. // Unless noFramePrepended is set in the Install Tool, a frame number is added to
  2407. // select a specific page of the image (by default this will be the first page)
  2408. if (!$this->noFramePrepended) {
  2409. $frame = '[' . intval($frame) . ']';
  2410. } else {
  2411. $frame = '';
  2412. }
  2413. $cmd = t3lib_div::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
  2414. $this->IM_commands[] = array($output, $cmd);
  2415. $ret = t3lib_utility_Command::exec($cmd);
  2416. // Change the permissions of the file
  2417. t3lib_div::fixPermissions($output);
  2418. return $ret;
  2419. }
  2420. }
  2421. /**
  2422. * 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)
  2423. * Can be used for many things, mostly scaling and effects.
  2424. *
  2425. * @param string $input The relative (to PATH_site) image filepath, bottom file
  2426. * @param string $overlay The relative (to PATH_site) image filepath, overlay file (top)
  2427. * @param string $mask The relative (to PATH_site) image filepath, the mask file (grayscale)
  2428. * @param string $output The relative (to PATH_site) image filepath, output filename (written to)
  2429. * @param boolean $handleNegation
  2430. * @return void
  2431. */
  2432. function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) {
  2433. if (!$this->NO_IMAGE_MAGICK) {
  2434. $params = '-colorspace GRAY +matte';
  2435. if ($handleNegation) {
  2436. if ($this->maskNegate) {
  2437. $params .= ' ' . $this->maskNegate;
  2438. }
  2439. }
  2440. $theMask = $this->randomName() . '.' . $this->gifExtension;
  2441. $this->imageMagickExec($mask, $theMask, $params);
  2442. $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
  2443. $this->IM_commands[] = array($output, $cmd);
  2444. $ret = t3lib_utility_Command::exec($cmd);
  2445. // Change the permissions of the file
  2446. t3lib_div::fixPermissions($output);
  2447. if (is_file($theMask)) {
  2448. @unlink($theMask);
  2449. }
  2450. return $ret;
  2451. }
  2452. }
  2453. /**
  2454. * Escapes a file name so it can safely be used on the command line.
  2455. *
  2456. * @param string $inputName filename to safeguard, must not be empty
  2457. *
  2458. * @return string $inputName escaped as needed
  2459. */
  2460. protected function wrapFileName($inputName) {
  2461. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
  2462. $currentLocale = setlocale(LC_CTYPE, 0);
  2463. setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
  2464. }
  2465. $escapedInputName = escapeshellarg($inputName);
  2466. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
  2467. setlocale(LC_CTYPE, $currentLocale);
  2468. }
  2469. return $escapedInputName;
  2470. }
  2471. /***********************************
  2472. *
  2473. * Various IO functions
  2474. *
  2475. ***********************************/
  2476. /**
  2477. * Returns TRUE if the input file existed
  2478. *
  2479. * @param string $file Input file to check
  2480. * @return string Returns the filename if the file existed, otherwise empty.
  2481. */
  2482. function checkFile($file) {
  2483. if (@is_file($file)) {
  2484. return $file;
  2485. } else {
  2486. return '';
  2487. }
  2488. }
  2489. /**
  2490. * Creates subdirectory in typo3temp/ if not already found.
  2491. *
  2492. * @param string $dirName Name of sub directory
  2493. * @return boolean Result of t3lib_div::mkdir(), TRUE if it went well.
  2494. */
  2495. function createTempSubDir($dirName) {
  2496. // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
  2497. if (t3lib_div::isFirstPartOfStr($this->tempPath, PATH_site)) {
  2498. $tmpPath = $this->tempPath;
  2499. } else {
  2500. $tmpPath = PATH_site . $this->tempPath;
  2501. }
  2502. // Making the temporary filename:
  2503. if (!@is_dir($tmpPath . $dirName)) {
  2504. return t3lib_div::mkdir($tmpPath . $dirName);
  2505. }
  2506. }
  2507. /**
  2508. * 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.
  2509. *
  2510. * @param pointer $im The image pointer (reference)
  2511. * @param string $command The ImageMagick parameters. Like effects, scaling etc.
  2512. * @return void
  2513. */
  2514. function applyImageMagickToPHPGif(&$im, $command) {
  2515. $tmpStr = $this->randomName();
  2516. $theFile = $tmpStr . '.' . $this->gifExtension;
  2517. $this->ImageWrite($im, $theFile);
  2518. $this->imageMagickExec($theFile, $theFile, $command);
  2519. $tmpImg = $this->imageCreateFromFile($theFile);
  2520. if ($tmpImg) {
  2521. ImageDestroy($im);
  2522. $im = $tmpImg;
  2523. $this->w = imagesx($im);
  2524. $this->h = imagesy($im);
  2525. }
  2526. if (!$this->dontUnlinkTempFiles) {
  2527. unlink($theFile);
  2528. }
  2529. }
  2530. /**
  2531. * 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.
  2532. * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
  2533. *
  2534. * @param string $type The file extension, lowercase.
  2535. * @param integer $w The width of the output image.
  2536. * @param integer $h The height of the output image.
  2537. * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
  2538. */
  2539. function gif_or_jpg($type, $w, $h) {
  2540. if ($type == 'ai' || $w * $h < $this->pixelLimitGif) {
  2541. return $this->gifExtension;
  2542. } else {
  2543. return 'jpg';
  2544. }
  2545. }
  2546. /**
  2547. * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
  2548. * Used in GIFBUILDER
  2549. * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
  2550. *
  2551. * @param string $file The filename to write to.
  2552. * @return string Returns input filename
  2553. * @see tslib_gifBuilder::gifBuild()
  2554. */
  2555. function output($file) {
  2556. if ($file) {
  2557. $reg = array();
  2558. preg_match('/([^\.]*)$/', $file, $reg);
  2559. $ext = strtolower($reg[0]);
  2560. switch ($ext) {
  2561. case 'gif':
  2562. case 'png':
  2563. if ($this->ImageWrite($this->im, $file)) {
  2564. // ImageMagick operations
  2565. if ($this->setup['reduceColors'] || !$this->png_truecolor) {
  2566. $reduced = $this->IMreduceColors($file, t3lib_utility_Math::forceIntegerInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256));
  2567. if ($reduced) {
  2568. @copy($reduced, $file);
  2569. @unlink($reduced);
  2570. }
  2571. }
  2572. // Compress with IM! (adds extra compression, LZW from ImageMagick)
  2573. // (Workaround for the absence of lzw-compression in GD)
  2574. t3lib_div::gif_compress($file, 'IM');
  2575. }
  2576. break;
  2577. case 'jpg':
  2578. case 'jpeg':
  2579. // Use the default
  2580. $quality = 0;
  2581. if ($this->setup['quality']) {
  2582. $quality = t3lib_utility_Math::forceIntegerInRange($this->setup['quality'], 10, 100);
  2583. }
  2584. if ($this->ImageWrite($this->im, $file, $quality)) {
  2585. }
  2586. break;
  2587. }
  2588. $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $file;
  2589. }
  2590. return $file;
  2591. }
  2592. /**
  2593. * Destroy internal image pointer, $this->im
  2594. *
  2595. * @return void
  2596. * @see tslib_gifBuilder::gifBuild()
  2597. */
  2598. function destroy() {
  2599. ImageDestroy($this->im);
  2600. }
  2601. /**
  2602. * Returns Image Tag for input image information array.
  2603. *
  2604. * @param array $imgInfo Image information array, key 0/1 is width/height and key 3 is the src value
  2605. * @return string Image tag for the input image information array.
  2606. */
  2607. function imgTag($imgInfo) {
  2608. return '<img src="' . $imgInfo[3] . '" width="' . $imgInfo[0] . '" height="' . $imgInfo[1] . '" border="0" alt="" />';
  2609. }
  2610. /**
  2611. * Writes the input GDlib image pointer to file
  2612. *
  2613. * @param pointer $destImg The GDlib image resource pointer
  2614. * @param string $theImage The filename to write to
  2615. * @param integer $quality The image quality (for JPEGs)
  2616. * @return boolean The output of either imageGif, imagePng or imageJpeg based on the filename to write
  2617. * @see maskImageOntoImage(), scale(), output()
  2618. */
  2619. function ImageWrite($destImg, $theImage, $quality = 0) {
  2620. imageinterlace($destImg, 0);
  2621. $ext = strtolower(substr($theImage, strrpos($theImage, '.') + 1));
  2622. $result = FALSE;
  2623. switch ($ext) {
  2624. case 'jpg':
  2625. case 'jpeg':
  2626. if (function_exists('imageJpeg')) {
  2627. if ($quality == 0) {
  2628. $quality = $this->jpegQuality;
  2629. }
  2630. $result = imageJpeg($destImg, $theImage, $quality);
  2631. }
  2632. break;
  2633. case 'gif':
  2634. if (function_exists('imageGif')) {
  2635. imagetruecolortopalette($destImg, TRUE, 256);
  2636. $result = imageGif($destImg, $theImage);
  2637. }
  2638. break;
  2639. case 'png':
  2640. if (function_exists('imagePng')) {
  2641. $result = ImagePng($destImg, $theImage);
  2642. }
  2643. break;
  2644. }
  2645. if ($result) {
  2646. t3lib_div::fixPermissions($theImage);
  2647. }
  2648. return $result;
  2649. }
  2650. /**
  2651. * Creates a new GDlib image resource based on the input image filename.
  2652. * 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.
  2653. *
  2654. * @param string $sourceImg Image filename
  2655. * @return pointer Image Resource pointer
  2656. */
  2657. function imageCreateFromFile($sourceImg) {
  2658. $imgInf = pathinfo($sourceImg);
  2659. $ext = strtolower($imgInf['extension']);
  2660. switch ($ext) {
  2661. case 'gif':
  2662. if (function_exists('imagecreatefromgif')) {
  2663. return imageCreateFromGif($sourceImg);
  2664. }
  2665. break;
  2666. case 'png':
  2667. if (function_exists('imagecreatefrompng')) {
  2668. $imageHandle = imageCreateFromPng($sourceImg);
  2669. if ($this->saveAlphaLayer) {
  2670. imagealphablending($imageHandle, FALSE);
  2671. imagesavealpha($imageHandle, TRUE);
  2672. }
  2673. return $imageHandle;
  2674. }
  2675. break;
  2676. case 'jpg':
  2677. case 'jpeg':
  2678. if (function_exists('imagecreatefromjpeg')) {
  2679. return imageCreateFromJpeg($sourceImg);
  2680. }
  2681. break;
  2682. }
  2683. // If non of the above:
  2684. $i = @getimagesize($sourceImg);
  2685. $im = imagecreatetruecolor($i[0], $i[1]);
  2686. $Bcolor = ImageColorAllocate($im, 128, 128, 128);
  2687. ImageFilledRectangle($im, 0, 0, $i[0], $i[1], $Bcolor);
  2688. return $im;
  2689. }
  2690. /**
  2691. * Returns the HEX color value for an RGB color array
  2692. *
  2693. * @param array RGB color array
  2694. * @return string HEX color value
  2695. */
  2696. function hexColor($col) {
  2697. $r = dechex($col[0]);
  2698. if (strlen($r) < 2) {
  2699. $r = '0' . $r;
  2700. }
  2701. $g = dechex($col[1]);
  2702. if (strlen($g) < 2) {
  2703. $g = '0' . $g;
  2704. }
  2705. $b = dechex($col[2]);
  2706. if (strlen($b) < 2) {
  2707. $b = '0' . $b;
  2708. }
  2709. return '#' . $r . $g . $b;
  2710. }
  2711. /**
  2712. * Unifies all colors given in the colArr color array to the first color in the array.
  2713. *
  2714. * @param pointer $img Image resource
  2715. * @param array $colArr Array containing RGB color arrays
  2716. * @param boolean $closest
  2717. * @return integer The index of the unified color
  2718. */
  2719. function unifyColors(&$img, $colArr, $closest = FALSE) {
  2720. $retCol = -1;
  2721. if (is_array($colArr) && count($colArr) && function_exists('imagepng') && function_exists('imagecreatefrompng')) {
  2722. $firstCol = array_shift($colArr);
  2723. $firstColArr = $this->convertColor($firstCol);
  2724. if (count($colArr) > 1) {
  2725. $origName = $preName = $this->randomName() . '.png';
  2726. $postName = $this->randomName() . '.png';
  2727. $this->imageWrite($img, $preName);
  2728. $firstCol = $this->hexColor($firstColArr);
  2729. foreach ($colArr as $transparentColor) {
  2730. $transparentColor = $this->convertColor($transparentColor);
  2731. $transparentColor = $this->hexColor($transparentColor);
  2732. $cmd = '-fill "' . $firstCol . '" -opaque "' . $transparentColor . '"';
  2733. $this->imageMagickExec($preName, $postName, $cmd);
  2734. $preName = $postName;
  2735. }
  2736. $this->imageMagickExec($postName, $origName, '');
  2737. if (@is_file($origName)) {
  2738. $tmpImg = $this->imageCreateFromFile($origName);
  2739. }
  2740. } else {
  2741. $tmpImg = $img;
  2742. }
  2743. if ($tmpImg) {
  2744. $img = $tmpImg;
  2745. if ($closest) {
  2746. $retCol = ImageColorClosest($img, $firstColArr[0], $firstColArr[1], $firstColArr[2]);
  2747. } else {
  2748. $retCol = ImageColorExact($img, $firstColArr[0], $firstColArr[1], $firstColArr[2]);
  2749. }
  2750. }
  2751. // Unlink files from process
  2752. if (!$this->dontUnlinkTempFiles) {
  2753. if ($origName) {
  2754. @unlink($origName);
  2755. }
  2756. if ($postName) {
  2757. @unlink($postName);
  2758. }
  2759. }
  2760. }
  2761. return $retCol;
  2762. }
  2763. }
  2764. ?>