TYPO3 API  SVNRelease
thumbs.php
Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00027 /**
00028  * Generates a thumbnail and returns an image stream, either GIF/PNG or JPG
00029  *
00030  * $Id: thumbs.php 10121 2011-01-18 20:15:30Z ohader $
00031  * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
00032  *
00033  * @author      Kasper Skårhøj    <kasperYYYY@typo3.com>
00034  */
00035 /**
00036  * [CLASS/FUNCTION INDEX of SCRIPT]
00037  *
00038  *
00039  *
00040  *  113: class SC_t3lib_thumbs
00041  *  134:     function init()
00042  *  164:     function main()
00043  *
00044  *              SECTION: OTHER FUNCTIONS:
00045  *  267:     function errorGif($l1,$l2,$l3)
00046  *  319:     function fontGif($font)
00047  *  366:     function wrapFileName($inputName)
00048  *
00049  * TOTAL FUNCTIONS: 5
00050  * (This index is automatically created/updated by the extension "extdeveval")
00051  *
00052  */
00053 
00054 
00055 // *******************************
00056 // Set error reporting
00057 // *******************************
00058 if (defined('E_DEPRECATED')) {
00059     error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
00060 } else {
00061     error_reporting(E_ALL ^ E_NOTICE);
00062 }
00063 
00064 
00065 
00066 // ******************
00067 // Constants defined
00068 // ******************
00069 define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
00070 define('TYPO3_MODE','BE');
00071 
00072 if(!defined('PATH_thisScript')) {
00073     define('PATH_thisScript', str_replace('//', '/', str_replace('\\', '/',
00074         (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
00075         ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
00076         ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
00077         ($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME']))));
00078 }
00079 
00080 if(!defined('PATH_site'))       define('PATH_site', preg_replace('/[^\/]*.[^\/]*$/','',PATH_thisScript));       // the path to the website folder (see init.php)
00081 if(!defined('PATH_t3lib'))      define('PATH_t3lib', PATH_site.'t3lib/');
00082 define('PATH_typo3conf', PATH_site.'typo3conf/');
00083 define('TYPO3_mainDir', 'typo3/');      // This is the directory of the backend administration for the sites of this TYPO3 installation.
00084 define('PATH_typo3', PATH_site.TYPO3_mainDir);
00085 
00086 
00087 // ******************
00088 // Including config
00089 // ******************
00090 require_once(PATH_t3lib.'class.t3lib_div.php');
00091 require_once(PATH_t3lib.'class.t3lib_extmgm.php');
00092 
00093 require(PATH_t3lib.'config_default.php');
00094 if (!defined ('TYPO3_db'))  die ('The configuration file was not included.');
00095 if (!$TYPO3_CONF_VARS['GFX']['image_processing'])   die ('ImageProcessing was disabled!');
00096 
00097 
00098 
00099 
00100 
00101 
00102 
00103 
00104 
00105 
00106 
00107 
00108 
00109 
00110 
00111 
00112 
00113 /**
00114  * Class for generating a thumbnail from the input parameters given to the script
00115  *
00116  * Input GET var, &file:        relative or absolute reference to an imagefile. WILL be validated against PATH_site / lockRootPath
00117  * Input GET var, &size:        integer-values defining size of thumbnail, format '[int]' or '[int]x[int]'
00118  *
00119  * Relative paths MUST BE the first two characters ONLY: eg: '../dir/file.gif', otherwise it is expect to be absolute
00120  *
00121  * @author      Kasper Skårhøj    <kasperYYYY@typo3.com>
00122  * @package TYPO3
00123  * @subpackage t3lib
00124  */
00125 class SC_t3lib_thumbs {
00126     var $include_once = array();
00127 
00128     var $outdir = 'typo3temp/';     // The output directory of temporary files in PATH_site
00129     var $output = '';
00130     var $sizeDefault='56x56';
00131 
00132     var $imageList;     // Coming from $TYPO3_CONF_VARS['GFX']['imagefile_ext']
00133     var $input;     // Contains the absolute path to the file for which to make a thumbnail (after init())
00134 
00135         // Internal, static: GPvar:
00136     var $file;      // Holds the input filename (GET: file)
00137     var $size;      // Holds the input size (GET: size)
00138     var $mtime = 0;     // Last modification time of the supplied file
00139 
00140 
00141     /**
00142      * Initialize; reading parameters with GPvar and checking file path
00143      * Results in internal var, $this->input, being set to the absolute path of the file for which to make the thumbnail.
00144      *
00145      * @return  void
00146      */
00147     function init() {
00148         global $TYPO3_CONF_VARS;
00149 
00150             // Setting GPvars:
00151         $file = t3lib_div::_GP('file');
00152         $size = t3lib_div::_GP('size');
00153         $md5sum = t3lib_div::_GP('md5sum');
00154 
00155             // Image extension list is set:
00156         $this->imageList = $TYPO3_CONF_VARS['GFX']['imagefile_ext'];            // valid extensions. OBS: No spaces in the list, all lowercase...
00157 
00158             // If the filereference $this->file is relative, we correct the path
00159         if (substr($file,0,3)=='../')   {
00160             $file = PATH_site.substr($file,3);
00161         }
00162 
00163             // Now the path is absolute.
00164             // Checking for backpath and double slashes + the thumbnail can be made from files which are in the PATH_site OR the lockRootPath only!
00165         if (t3lib_div::isAllowedAbsPath($file)) {
00166             $mtime = filemtime($file);
00167         }
00168 
00169             // Do an MD5 check to prevent viewing of images without permission
00170         $OK = FALSE;
00171         if ($mtime) {
00172                 // Always use the absolute path for this check!
00173             $check = basename($file).':'.$mtime.':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
00174             $md5_real = t3lib_div::shortMD5($check);
00175             if (!strcmp($md5_real,$md5sum)) {
00176                 $OK = TRUE;
00177             }
00178         }
00179 
00180         if ($OK)    {
00181             $this->input = $file;
00182             $this->size = $size;
00183             $this->mtime = $mtime;
00184         } else {
00185             throw new RuntimeException(
00186                 'TYPO3 Fatal Error: Image does not exist and/or MD5 checksum did not match.',
00187                 1270853950
00188             );
00189         }
00190     }
00191 
00192     /**
00193      * Create the thumbnail
00194      * Will exit before return if all is well.
00195      *
00196      * @return  void
00197      */
00198     function main() {
00199         global $TYPO3_CONF_VARS;
00200 
00201             // If file exists, we make a thumbsnail of the file.
00202         if ($this->input && file_exists($this->input))  {
00203 
00204                 // Check file extension:
00205             $reg = array();
00206             if (preg_match('/(.*)\.([^\.]*$)/',$this->input,$reg))  {
00207                 $ext=strtolower($reg[2]);
00208                 $ext=($ext=='jpeg')?'jpg':$ext;
00209                 if ($ext=='ttf')    {
00210                     $this->fontGif($this->input);   // Make font preview... (will not return)
00211                 } elseif (!t3lib_div::inList($this->imageList, $ext))   {
00212                     $this->errorGif('Not imagefile!',$ext,basename($this->input));
00213                 }
00214             } else {
00215                 $this->errorGif('Not imagefile!','No ext!',basename($this->input));
00216             }
00217 
00218                 // ... so we passed the extension test meaning that we are going to make a thumbnail here:
00219             if (!$this->size)   $this->size = $this->sizeDefault;   // default
00220 
00221                 // I added extra check, so that the size input option could not be fooled to pass other values. That means the value is exploded, evaluated to an integer and the imploded to [value]x[value]. Furthermore you can specify: size=340 and it'll be translated to 340x340.
00222             $sizeParts = explode('x', $this->size.'x'.$this->size); // explodes the input size (and if no "x" is found this will add size again so it is the same for both dimensions)
00223             $sizeParts = array(t3lib_div::intInRange($sizeParts[0],1,1000),t3lib_div::intInRange($sizeParts[1],1,1000));    // Cleaning it up, only two parameters now.
00224             $this->size = implode('x',$sizeParts);      // Imploding the cleaned size-value back to the internal variable
00225             $sizeMax = max($sizeParts); // Getting max value
00226 
00227                 // Init
00228             $outpath = PATH_site.$this->outdir;
00229 
00230                 // Should be - ? 'png' : 'gif' - , but doesn't work (ImageMagick prob.?)
00231                 // René: png work for me
00232             $thmMode = t3lib_div::intInRange($TYPO3_CONF_VARS['GFX']['thumbnails_png'],0);
00233             $outext = ($ext!='jpg' || ($thmMode & 2)) ? ($thmMode & 1 ? 'png' : 'gif') : 'jpg';
00234 
00235             $outfile = 'tmb_'.substr(md5($this->input.$this->mtime.$this->size),0,10).'.'.$outext;
00236             $this->output = $outpath.$outfile;
00237 
00238             if ($TYPO3_CONF_VARS['GFX']['im'])  {
00239                     // If thumbnail does not exist, we generate it
00240                 if (!file_exists($this->output))    {
00241                     $parameters = '-sample ' . $this->size . ' ' . $this->wrapFileName($this->input) . '[0] ' . $this->wrapFileName($this->output);
00242                     $cmd = t3lib_div::imageMagickCommand('convert', $parameters);
00243                     t3lib_utility_Command::exec($cmd);
00244                     if (!file_exists($this->output))    {
00245                         $this->errorGif('No thumb','generated!',basename($this->input));
00246                     } else {
00247                         t3lib_div::fixPermissions($this->output);
00248                     }
00249                 }
00250                     // The thumbnail is read and output to the browser
00251                 if($fd = @fopen($this->output,'rb'))    {
00252                     header('Content-type: image/'.$outext);
00253                     fpassthru($fd);
00254                     fclose($fd);
00255                 } else {
00256                     $this->errorGif('Read problem!','',$this->output);
00257                 }
00258             } else exit;
00259         } else {
00260             $this->errorGif('No valid','inputfile!',basename($this->input));
00261         }
00262     }
00263 
00264 
00265 
00266 
00267 
00268 
00269 
00270 
00271 
00272 
00273 
00274     /***************************
00275      *
00276      * OTHER FUNCTIONS:
00277      *
00278      ***************************/
00279 
00280     /**
00281      * Creates error image based on gfx/notfound_thumb.png
00282      * Requires GD lib enabled, otherwise it will exit with the three textstrings outputted as text.
00283      * Outputs the image stream to browser and exits!
00284      *
00285      * @param   string      Text line 1
00286      * @param   string      Text line 2
00287      * @param   string      Text line 3
00288      * @return  void
00289      */
00290     function errorGif($l1,$l2,$l3)  {
00291         global $TYPO3_CONF_VARS;
00292 
00293         if (!$TYPO3_CONF_VARS['GFX']['gdlib']) {
00294             throw new RuntimeException(
00295                 'TYPO3 Fatal Error: No gdlib. ' . $l1 . ' ' . $l2 . ' ' . $l3,
00296                 1270853952
00297             );
00298         }
00299 
00300             // Creates the basis for the error image
00301         if ($TYPO3_CONF_VARS['GFX']['gdlib_png'])   {
00302             header('Content-type: image/png');
00303             $im = imagecreatefrompng(PATH_typo3.'gfx/notfound_thumb.png');
00304         } else {
00305             header('Content-type: image/gif');
00306             $im = imagecreatefromgif(PATH_typo3.'gfx/notfound_thumb.gif');
00307         }
00308             // Sets background color and print color.
00309         $white = imageColorAllocate($im, 0,0,0);
00310         $black = imageColorAllocate($im, 255,255,0);
00311 
00312             // Prints the text strings with the build-in font functions of GD
00313         $x=0;
00314         $font=0;
00315         if ($l1)    {
00316             imagefilledrectangle($im, $x, 9, 56, 16, $black);
00317             imageString($im,$font,$x,9,$l1,$white);
00318         }
00319         if ($l2)    {
00320             imagefilledrectangle($im, $x, 19, 56, 26, $black);
00321             imageString($im,$font,$x,19,$l2,$white);
00322         }
00323         if ($l3)    {
00324             imagefilledrectangle($im, $x, 29, 56, 36, $black);
00325             imageString($im,$font,$x,29,substr($l3,-14),$white);
00326         }
00327 
00328             // Outputting the image stream and exit
00329         if ($TYPO3_CONF_VARS['GFX']['gdlib_png'])   {
00330             imagePng($im);
00331         } else {
00332             imageGif($im);
00333         }
00334         imagedestroy($im);
00335         exit;
00336     }
00337 
00338     /**
00339      * Creates a font-preview thumbnail.
00340      * This means a PNG/GIF file with the text "AaBbCc...." set with the font-file given as input and in various sizes to show how the font looks
00341      * Requires GD lib enabled.
00342      * Outputs the image stream to browser and exits!
00343      *
00344      * @param   string      The filepath to the font file (absolute, probably)
00345      * @return  void
00346      */
00347     function fontGif($font) {
00348         global $TYPO3_CONF_VARS;
00349 
00350         if (!$TYPO3_CONF_VARS['GFX']['gdlib']) {
00351             throw new RuntimeException(
00352                 'TYPO3 Fatal Error: No gdlib.',
00353                 1270853953
00354             );
00355         }
00356 
00357             // Create image and set background color to white.
00358         $im = imageCreate(250,76);
00359         $white = imageColorAllocate($im, 255,255,255);
00360         $col = imageColorAllocate($im, 0,0,0);
00361 
00362             // The test string and offset in x-axis.
00363         $string = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÆæØøÅåÄäÖöÜüß';
00364         $x=13;
00365 
00366             // Print (with non-ttf font) the size displayed
00367         imagestring ($im, 1, 0, 2, '10', $col);
00368         imagestring ($im, 1, 0, 15, '12', $col);
00369         imagestring ($im, 1, 0, 30, '14', $col);
00370         imagestring ($im, 1, 0, 47, '18', $col);
00371         imagestring ($im, 1, 0, 68, '24', $col);
00372 
00373             // Print with ttf-font the test string
00374         imagettftext ($im, t3lib_div::freetypeDpiComp(10), 0, $x, 8, $col, $font, $string);
00375         imagettftext ($im, t3lib_div::freetypeDpiComp(12), 0, $x, 21, $col, $font, $string);
00376         imagettftext ($im, t3lib_div::freetypeDpiComp(14), 0, $x, 36, $col, $font, $string);
00377         imagettftext ($im, t3lib_div::freetypeDpiComp(18), 0, $x, 53, $col, $font, $string);
00378         imagettftext ($im, t3lib_div::freetypeDpiComp(24), 0, $x, 74, $col, $font, $string);
00379 
00380             // Output PNG or GIF based on $TYPO3_CONF_VARS['GFX']['gdlib_png']
00381         if ($TYPO3_CONF_VARS['GFX']['gdlib_png'])   {
00382             header('Content-type: image/png');
00383             imagePng($im);
00384         } else {
00385             header('Content-type: image/gif');
00386             imageGif($im);
00387         }
00388         imagedestroy($im);
00389         exit;
00390     }
00391 
00392     /**
00393      * Escapes a file name so it can safely be used on the command line.
00394      *
00395      * @param string $inputName filename to safeguard, must not be empty
00396      *
00397      * @return string $inputName escaped as needed
00398      */
00399     protected function wrapFileName($inputName) {
00400         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
00401             $currentLocale = setlocale(LC_CTYPE, 0);
00402             setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
00403         }
00404         $escapedInputName = escapeshellarg($inputName);
00405         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
00406             setlocale(LC_CTYPE, $currentLocale);
00407         }
00408         return $escapedInputName;
00409     }
00410 }
00411 
00412 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/thumbs.php'])) {
00413     include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/thumbs.php']);
00414 }
00415 
00416 
00417 
00418 
00419 // Make instance:
00420 $SOBE = t3lib_div::makeInstance('SC_t3lib_thumbs');
00421 $SOBE->init();
00422 $SOBE->main();
00423 
00424 ?>