xref: /dokuwiki/lib/exe/fetch.php (revision 09a5b61f4b388f9824bb5e1bed7ec6cbe3619ff7)
1f62ea8a1Sandi<?php
2f62ea8a1Sandi/**
3f62ea8a1Sandi * DokuWiki media passthrough file
4f62ea8a1Sandi *
5f62ea8a1Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6f62ea8a1Sandi * @author     Andreas Gohr <andi@splitbrain.org>
7f62ea8a1Sandi */
8f62ea8a1Sandi
9d0a27cb0SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
103138b5c7SAndreas Gohr  define('DOKU_DISABLE_GZIP_OUTPUT', 1);
11f62ea8a1Sandi  require_once(DOKU_INC.'inc/init.php');
12f62ea8a1Sandi  require_once(DOKU_INC.'inc/common.php');
13f62ea8a1Sandi  require_once(DOKU_INC.'inc/pageutils.php');
14f62ea8a1Sandi  require_once(DOKU_INC.'inc/confutils.php');
15f62ea8a1Sandi  require_once(DOKU_INC.'inc/auth.php');
168746e727Sandi  //close sesseion
178746e727Sandi  session_write_close();
18e935fb4aSAndreas Gohr  if(!defined('CHUNK_SIZE')) define('CHUNK_SIZE',16*1024);
198746e727Sandi
20f62ea8a1Sandi  $mimetypes = getMimeTypes();
21f62ea8a1Sandi
22f62ea8a1Sandi  //get input
2302b0b681SAndreas Gohr  $MEDIA  = stripctl(getID('media',false)); // no cleaning except control chars - maybe external
24f62ea8a1Sandi  $CACHE  = calc_cache($_REQUEST['cache']);
258fcc3410SAndreas Gohr  $WIDTH  = (int) $_REQUEST['w'];
268fcc3410SAndreas Gohr  $HEIGHT = (int) $_REQUEST['h'];
27f62ea8a1Sandi  list($EXT,$MIME) = mimetype($MEDIA);
28f62ea8a1Sandi  if($EXT === false){
29f62ea8a1Sandi    $EXT  = 'unknown';
30f62ea8a1Sandi    $MIME = 'application/octet-stream';
31f62ea8a1Sandi  }
32f62ea8a1Sandi
33f62ea8a1Sandi  //media to local file
34d1ed0b61SAndreas Gohr  if(preg_match('#^(https?)://#i',$MEDIA)){
35d1ed0b61SAndreas Gohr    //handle external images
36d1ed0b61SAndreas Gohr    if(strncmp($MIME,'image/',6) == 0) $FILE = get_from_URL($MEDIA,$EXT,$CACHE);
37f62ea8a1Sandi    if(!$FILE){
38f62ea8a1Sandi      //download failed - redirect to original URL
39f62ea8a1Sandi      header('Location: '.$MEDIA);
40f62ea8a1Sandi      exit;
41f62ea8a1Sandi    }
42f62ea8a1Sandi  }else{
43f62ea8a1Sandi    $MEDIA = cleanID($MEDIA);
44f62ea8a1Sandi    if(empty($MEDIA)){
45f62ea8a1Sandi      header("HTTP/1.0 400 Bad Request");
46f62ea8a1Sandi      print 'Bad request';
47f62ea8a1Sandi      exit;
48f62ea8a1Sandi    }
49f62ea8a1Sandi
50f62ea8a1Sandi    //check permissions (namespace only)
51f62ea8a1Sandi    if(auth_quickaclcheck(getNS($MEDIA).':X') < AUTH_READ){
52f62ea8a1Sandi      header("HTTP/1.0 401 Unauthorized");
53f62ea8a1Sandi      //fixme add some image for imagefiles
54f62ea8a1Sandi      print 'Unauthorized';
55f62ea8a1Sandi      exit;
56f62ea8a1Sandi    }
57f62ea8a1Sandi    $FILE  = mediaFN($MEDIA);
58f62ea8a1Sandi  }
59f62ea8a1Sandi
60f62ea8a1Sandi  //check file existance
61f62ea8a1Sandi  if(!@file_exists($FILE)){
62f62ea8a1Sandi    header("HTTP/1.0 404 Not Found");
63f62ea8a1Sandi    //FIXME add some default broken image
64f62ea8a1Sandi    print 'Not Found';
65f62ea8a1Sandi    exit;
66f62ea8a1Sandi  }
67f62ea8a1Sandi
68b80bedd6SAndreas Gohr  $ORIG = $FILE;
69b80bedd6SAndreas Gohr
7020bc86cfSAndreas Gohr  //handle image resizing/cropping
71f62ea8a1Sandi  if((substr($MIME,0,5) == 'image') && $WIDTH){
72d52a56e1SAndreas Gohr    if($HEIGHT){
7320bc86cfSAndreas Gohr        $FILE = get_cropped($FILE,$EXT,$WIDTH,$HEIGHT);
7420bc86cfSAndreas Gohr    }else{
75f62ea8a1Sandi        $FILE = get_resized($FILE,$EXT,$WIDTH,$HEIGHT);
76f62ea8a1Sandi    }
7720bc86cfSAndreas Gohr  }
78f62ea8a1Sandi
79e935fb4aSAndreas Gohr  // finally send the file to the client
80b80bedd6SAndreas Gohr  $data = array('file'   => $FILE,
81b80bedd6SAndreas Gohr                'mime'   => $MIME,
82b80bedd6SAndreas Gohr                'cache'  => $CACHE,
83b80bedd6SAndreas Gohr                'orig'   => $ORIG,
84b80bedd6SAndreas Gohr                'ext'    => $EXT,
85b80bedd6SAndreas Gohr                'width'  => $WIDTH,
86b80bedd6SAndreas Gohr                'height' => $HEIGHT);
87b80bedd6SAndreas Gohr
88b80bedd6SAndreas Gohr  $evt = new Doku_Event('MEDIA_SENDFILE', $data);
89b80bedd6SAndreas Gohr  if ($evt->advise_before()) {
90b80bedd6SAndreas Gohr    sendFile($data['file'],$data['mime'],$data['cache']);
91b80bedd6SAndreas Gohr  }
92f62ea8a1Sandi
93e935fb4aSAndreas Gohr/* ------------------------------------------------------------------------ */
94f62ea8a1Sandi
95e935fb4aSAndreas Gohr/**
96e935fb4aSAndreas Gohr * Set headers and send the file to the client
97e935fb4aSAndreas Gohr *
98e935fb4aSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9983730152SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
100e935fb4aSAndreas Gohr */
10183730152SBen Coburnfunction sendFile($file,$mime,$cache){
10283730152SBen Coburn  global $conf;
103*09a5b61fSgweissbach  $fmtime = @filemtime($file);
104e935fb4aSAndreas Gohr  // send headers
105e935fb4aSAndreas Gohr  header("Content-Type: $mime");
10683730152SBen Coburn  // smart http caching headers
10783730152SBen Coburn  if ($cache==-1) {
10883730152SBen Coburn    // cache
10983730152SBen Coburn    // cachetime or one hour
11083730152SBen Coburn    header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
11183730152SBen Coburn    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
112e935fb4aSAndreas Gohr    header('Pragma: public');
11383730152SBen Coburn  } else if ($cache>0) {
11483730152SBen Coburn    // recache
11583730152SBen Coburn    // remaining cachetime + 10 seconds so the newly recached media is used
11683730152SBen Coburn    header('Expires: '.gmdate("D, d M Y H:i:s", $fmtime+$conf['cachetime']+10).' GMT');
11783730152SBen Coburn    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($fmtime-time()+$conf['cachetime']+10, 0));
11883730152SBen Coburn    header('Pragma: public');
11983730152SBen Coburn  } else if ($cache==0) {
12083730152SBen Coburn    // nocache
12183730152SBen Coburn    header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
12283730152SBen Coburn    header('Pragma: public');
12383730152SBen Coburn  }
124ff4f5ee7SBen Coburn  //send important headers first, script stops here if '304 Not Modified' response
12583730152SBen Coburn  http_conditionalRequest($fmtime);
1269a87c72aSAndreas Gohr
127f62ea8a1Sandi
128f62ea8a1Sandi  //application mime type is downloadable
129e935fb4aSAndreas Gohr  if(substr($mime,0,11) == 'application'){
130e935fb4aSAndreas Gohr    header('Content-Disposition: attachment; filename="'.basename($file).'";');
131f62ea8a1Sandi  }
132f62ea8a1Sandi
1339a87c72aSAndreas Gohr  //use x-sendfile header to pass the delivery to compatible webservers
1349a87c72aSAndreas Gohr  if($conf['xsendfile'] == 1){
1359a87c72aSAndreas Gohr    header("X-LIGHTTPD-send-file: $file");
1369a87c72aSAndreas Gohr    exit;
1379a87c72aSAndreas Gohr  }elseif($conf['xsendfile'] == 2){
1389a87c72aSAndreas Gohr    header("X-Sendfile: $file");
1399a87c72aSAndreas Gohr    exit;
140deec6eb9Spierre.pracht  }elseif($conf['xsendfile'] == 3){
141deec6eb9Spierre.pracht    header("X-Accel-Redirect: $file");
142deec6eb9Spierre.pracht    exit;
1439a87c72aSAndreas Gohr  }
1449a87c72aSAndreas Gohr
1459a87c72aSAndreas Gohr  //support download continueing
1469a87c72aSAndreas Gohr  header('Accept-Ranges: bytes');
1479a87c72aSAndreas Gohr  list($start,$len) = http_rangeRequest(filesize($file));
1489a87c72aSAndreas Gohr
149e935fb4aSAndreas Gohr  // send file contents
150e935fb4aSAndreas Gohr  $fp = @fopen($file,"rb");
151f62ea8a1Sandi  if($fp){
152e935fb4aSAndreas Gohr    fseek($fp,$start); //seek to start of range
153e935fb4aSAndreas Gohr
154e935fb4aSAndreas Gohr    $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
155e935fb4aSAndreas Gohr    while (!feof($fp) && $chunk > 0) {
156d6751ba5SAndreas Gohr      @set_time_limit(30); // large files can take a lot of time
157e935fb4aSAndreas Gohr      print fread($fp, $chunk);
158615a21edSBrian Cowan      flush();
159e935fb4aSAndreas Gohr      $len -= $chunk;
160e935fb4aSAndreas Gohr      $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
161615a21edSBrian Cowan    }
162615a21edSBrian Cowan    fclose($fp);
163f62ea8a1Sandi  }else{
164f62ea8a1Sandi    header("HTTP/1.0 500 Internal Server Error");
165e935fb4aSAndreas Gohr    print "Could not read $file - bad permissions?";
166e935fb4aSAndreas Gohr  }
167f62ea8a1Sandi}
168f62ea8a1Sandi
169e935fb4aSAndreas Gohr/**
170e935fb4aSAndreas Gohr * Checks and sets headers to handle range requets
171e935fb4aSAndreas Gohr *
172e935fb4aSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
173e935fb4aSAndreas Gohr * @returns array The start byte and the amount of bytes to send
174e935fb4aSAndreas Gohr */
175e935fb4aSAndreas Gohrfunction http_rangeRequest($size){
176e935fb4aSAndreas Gohr  if(!isset($_SERVER['HTTP_RANGE'])){
177e935fb4aSAndreas Gohr    // no range requested - send the whole file
178e935fb4aSAndreas Gohr    header("Content-Length: $size");
179e935fb4aSAndreas Gohr    return array(0,$size);
180e935fb4aSAndreas Gohr  }
181e935fb4aSAndreas Gohr
182e935fb4aSAndreas Gohr  $t = explode('=', $_SERVER['HTTP_RANGE']);
183e935fb4aSAndreas Gohr  if (!$t[0]=='bytes') {
184e935fb4aSAndreas Gohr    // we only understand byte ranges - send the whole file
185e935fb4aSAndreas Gohr    header("Content-Length: $size");
186e935fb4aSAndreas Gohr    return array(0,$size);
187e935fb4aSAndreas Gohr  }
188e935fb4aSAndreas Gohr
189e935fb4aSAndreas Gohr  $r = explode('-', $t[1]);
190e935fb4aSAndreas Gohr  $start = (int)$r[0];
191e935fb4aSAndreas Gohr  $end = (int)$r[1];
192e935fb4aSAndreas Gohr  if (!$end) $end = $size - 1;
193e935fb4aSAndreas Gohr  if ($start > $end || $start > $size || $end > $size){
194e935fb4aSAndreas Gohr    header('HTTP/1.1 416 Requested Range Not Satisfiable');
195e935fb4aSAndreas Gohr    print 'Bad Range Request!';
196e935fb4aSAndreas Gohr    exit;
197e935fb4aSAndreas Gohr  }
198e935fb4aSAndreas Gohr
199e935fb4aSAndreas Gohr  $tot = $end - $start + 1;
200e935fb4aSAndreas Gohr  header('HTTP/1.1 206 Partial Content');
201e935fb4aSAndreas Gohr  header("Content-Range: bytes {$start}-{$end}/{$size}");
202e935fb4aSAndreas Gohr  header("Content-Length: $tot");
203e935fb4aSAndreas Gohr
204e935fb4aSAndreas Gohr  return array($start,$tot);
205e935fb4aSAndreas Gohr}
206e935fb4aSAndreas Gohr
207e935fb4aSAndreas Gohr/**
208f62ea8a1Sandi * Resizes the given image to the given size
209f62ea8a1Sandi *
210f62ea8a1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
211f62ea8a1Sandi */
212f62ea8a1Sandifunction get_resized($file, $ext, $w, $h=0){
213f62ea8a1Sandi  global $conf;
214f62ea8a1Sandi
215*09a5b61fSgweissbach  $info = @getimagesize($file); //get original size
216*09a5b61fSgweissbach  if($info == false) return $file; // that's no image - it's a spaceship!
217*09a5b61fSgweissbach
218f62ea8a1Sandi  if(!$h) $h = round(($w * $info[1]) / $info[0]);
219f62ea8a1Sandi
2208fcc3410SAndreas Gohr  // we wont scale up to infinity
2218fcc3410SAndreas Gohr  if($w > 2000 || $h > 2000) return $file;
222f62ea8a1Sandi
223f62ea8a1Sandi  //cache
22498407a7aSandi  $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
225f62ea8a1Sandi  $mtime = @filemtime($local); // 0 if not exists
226f62ea8a1Sandi
22768375754SPavel Vitis  if( $mtime > filemtime($file) ||
22868375754SPavel Vitis      resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
22968375754SPavel Vitis      resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
23028d5e270SOtto Vainio    if($conf['fperm']) chmod($local, $conf['fperm']);
231f62ea8a1Sandi    return $local;
232f62ea8a1Sandi  }
233f62ea8a1Sandi  //still here? resizing failed
234f62ea8a1Sandi  return $file;
235f62ea8a1Sandi}
236f62ea8a1Sandi
237f62ea8a1Sandi/**
23820bc86cfSAndreas Gohr * Crops the given image to the wanted ratio, then calls get_resized to scale it
23920bc86cfSAndreas Gohr * to the wanted size
24020bc86cfSAndreas Gohr *
241a7ead82dSAndreas Gohr * Crops are centered horizontally but prefer the upper third of an vertical
242a7ead82dSAndreas Gohr * image because most pics are more interesting in that area (rule of thirds)
243a7ead82dSAndreas Gohr *
24420bc86cfSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
24520bc86cfSAndreas Gohr */
24620bc86cfSAndreas Gohrfunction get_cropped($file, $ext, $w, $h=0){
24720bc86cfSAndreas Gohr  global $conf;
24820bc86cfSAndreas Gohr
24920bc86cfSAndreas Gohr  if(!$h) $h = $w;
250e42176e6SGerry Weissbach  $info = @getimagesize($file); //get original size
251e42176e6SGerry Weissbach  if($info == false) return $file; // that's no image - it's a spaceship!
25220bc86cfSAndreas Gohr
25320bc86cfSAndreas Gohr  // calculate crop size
25420bc86cfSAndreas Gohr  $fr = $info[0]/$info[1];
25520bc86cfSAndreas Gohr  $tr = $w/$h;
25620bc86cfSAndreas Gohr  if($tr >= 1){
25720bc86cfSAndreas Gohr    if($tr > $fr){
25820bc86cfSAndreas Gohr        $cw = $info[0];
25920bc86cfSAndreas Gohr        $ch = (int) $info[0]/$tr;
26020bc86cfSAndreas Gohr    }else{
26120bc86cfSAndreas Gohr        $cw = (int) $info[1]*$tr;
26220bc86cfSAndreas Gohr        $ch = $info[1];
26320bc86cfSAndreas Gohr    }
26420bc86cfSAndreas Gohr  }else{
26520bc86cfSAndreas Gohr    if($tr < $fr){
26620bc86cfSAndreas Gohr        $cw = (int) $info[1]*$tr;
26720bc86cfSAndreas Gohr        $ch = $info[1];
26820bc86cfSAndreas Gohr    }else{
26920bc86cfSAndreas Gohr        $cw = $info[0];
27020bc86cfSAndreas Gohr        $ch = (int) $info[0]/$tr;
27120bc86cfSAndreas Gohr    }
27220bc86cfSAndreas Gohr  }
27320bc86cfSAndreas Gohr  // calculate crop offset
27420bc86cfSAndreas Gohr  $cx = (int) ($info[0]-$cw)/2;
275a7ead82dSAndreas Gohr  $cy = (int) ($info[1]-$ch)/3;
27620bc86cfSAndreas Gohr
27720bc86cfSAndreas Gohr  //cache
27820bc86cfSAndreas Gohr  $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
27920bc86cfSAndreas Gohr  $mtime = @filemtime($local); // 0 if not exists
28020bc86cfSAndreas Gohr
28120bc86cfSAndreas Gohr  if( $mtime > filemtime($file) ||
28220bc86cfSAndreas Gohr      crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
28320bc86cfSAndreas Gohr      resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
28420bc86cfSAndreas Gohr    if($conf['fperm']) chmod($local, $conf['fperm']);
28520bc86cfSAndreas Gohr    return get_resized($local,$ext, $w, $h);
28620bc86cfSAndreas Gohr  }
28720bc86cfSAndreas Gohr
28820bc86cfSAndreas Gohr  //still here? cropping failed
28920bc86cfSAndreas Gohr  return get_resized($file,$ext, $w, $h);
29020bc86cfSAndreas Gohr}
29120bc86cfSAndreas Gohr
29220bc86cfSAndreas Gohr
29320bc86cfSAndreas Gohr/**
294f62ea8a1Sandi * Returns the wanted cachetime in seconds
295f62ea8a1Sandi *
296f62ea8a1Sandi * Resolves named constants
297f62ea8a1Sandi *
298f62ea8a1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
299f62ea8a1Sandi */
300f62ea8a1Sandifunction calc_cache($cache){
301f62ea8a1Sandi  global $conf;
302f62ea8a1Sandi
303f62ea8a1Sandi  if(strtolower($cache) == 'nocache') return 0; //never cache
304f62ea8a1Sandi  if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
305f62ea8a1Sandi  return -1; //cache endless
306f62ea8a1Sandi}
307f62ea8a1Sandi
308f62ea8a1Sandi/**
309f62ea8a1Sandi * Download a remote file and return local filename
310f62ea8a1Sandi *
311f62ea8a1Sandi * returns false if download fails. Uses cached file if available and
312f62ea8a1Sandi * wanted
313f62ea8a1Sandi *
314f62ea8a1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31568375754SPavel Vitis * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
316f62ea8a1Sandi */
317f62ea8a1Sandifunction get_from_URL($url,$ext,$cache){
318f62ea8a1Sandi  global $conf;
319f62ea8a1Sandi
320847b8298SAndreas Gohr  // if no cache or fetchsize just redirect
321847b8298SAndreas Gohr  if ($cache==0)           return false;
322847b8298SAndreas Gohr  if (!$conf['fetchsize']) return false;
3234f3c4962SBen Coburn
32468375754SPavel Vitis  $local = getCacheName(strtolower($url),".media.$ext");
325f62ea8a1Sandi  $mtime = @filemtime($local); // 0 if not exists
326f62ea8a1Sandi
327f62ea8a1Sandi  //decide if download needed:
3284f3c4962SBen Coburn  if( ($mtime == 0) ||                           // cache does not exist
3294f3c4962SBen Coburn      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
33068375754SPavel Vitis    ){
331894a80ccSAndreas Gohr      if(image_download($url,$local)){
332f62ea8a1Sandi        return $local;
333f62ea8a1Sandi      }else{
334f62ea8a1Sandi        return false;
335f62ea8a1Sandi      }
336f62ea8a1Sandi  }
337f62ea8a1Sandi
338f62ea8a1Sandi  //if cache exists use it else
339f62ea8a1Sandi  if($mtime) return $local;
340f62ea8a1Sandi
341f62ea8a1Sandi  //else return false
342f62ea8a1Sandi  return false;
343f62ea8a1Sandi}
344f62ea8a1Sandi
345f62ea8a1Sandi/**
346894a80ccSAndreas Gohr * Download image files
347894a80ccSAndreas Gohr *
348894a80ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
349894a80ccSAndreas Gohr */
350894a80ccSAndreas Gohrfunction image_download($url,$file){
351894a80ccSAndreas Gohr  global $conf;
352894a80ccSAndreas Gohr  $http = new DokuHTTPClient();
353894a80ccSAndreas Gohr  $http->max_bodysize = $conf['fetchsize'];
354894a80ccSAndreas Gohr  $http->timeout = 25; //max. 25 sec
355894a80ccSAndreas Gohr  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
356894a80ccSAndreas Gohr
357894a80ccSAndreas Gohr  $data = $http->get($url);
358894a80ccSAndreas Gohr  if(!$data) return false;
359894a80ccSAndreas Gohr
360894a80ccSAndreas Gohr  $fileexists = @file_exists($file);
361894a80ccSAndreas Gohr  $fp = @fopen($file,"w");
362894a80ccSAndreas Gohr  if(!$fp) return false;
363894a80ccSAndreas Gohr  fwrite($fp,$data);
364894a80ccSAndreas Gohr  fclose($fp);
365894a80ccSAndreas Gohr  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
366d1ed0b61SAndreas Gohr
367d1ed0b61SAndreas Gohr  // check if it is really an image
368d1ed0b61SAndreas Gohr  $info = @getimagesize($file);
369d1ed0b61SAndreas Gohr  if(!$info){
370d1ed0b61SAndreas Gohr    @unlink($file);
371d1ed0b61SAndreas Gohr    return false;
372d1ed0b61SAndreas Gohr  }
373d1ed0b61SAndreas Gohr
374894a80ccSAndreas Gohr  return true;
375894a80ccSAndreas Gohr}
376894a80ccSAndreas Gohr
377894a80ccSAndreas Gohr/**
37868375754SPavel Vitis * resize images using external ImageMagick convert program
37968375754SPavel Vitis *
38068375754SPavel Vitis * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
38168375754SPavel Vitis * @author Andreas Gohr <andi@splitbrain.org>
38268375754SPavel Vitis */
38368375754SPavel Vitisfunction resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
38468375754SPavel Vitis  global $conf;
38568375754SPavel Vitis
3867bc7a78eSAndreas Gohr  // check if convert is configured
3877bc7a78eSAndreas Gohr  if(!$conf['im_convert']) return false;
38868375754SPavel Vitis
38968375754SPavel Vitis  // prepare command
39068375754SPavel Vitis  $cmd  = $conf['im_convert'];
39168375754SPavel Vitis  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
3922b03e74dSBen Coburn  if ($ext == 'jpg' || $ext == 'jpeg') {
3932b03e74dSBen Coburn      $cmd .= ' -quality '.$conf['jpg_quality'];
3942b03e74dSBen Coburn  }
39568375754SPavel Vitis  $cmd .= " $from $to";
39668375754SPavel Vitis
39768375754SPavel Vitis  @exec($cmd,$out,$retval);
39868375754SPavel Vitis  if ($retval == 0) return true;
39968375754SPavel Vitis  return false;
40068375754SPavel Vitis}
40168375754SPavel Vitis
40268375754SPavel Vitis/**
40320bc86cfSAndreas Gohr * crop images using external ImageMagick convert program
40420bc86cfSAndreas Gohr *
40520bc86cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
40620bc86cfSAndreas Gohr */
40720bc86cfSAndreas Gohrfunction crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
40820bc86cfSAndreas Gohr  global $conf;
409681eb61bSAndreas Gohr
41020bc86cfSAndreas Gohr  // check if convert is configured
41120bc86cfSAndreas Gohr  if(!$conf['im_convert']) return false;
41220bc86cfSAndreas Gohr
41320bc86cfSAndreas Gohr  // prepare command
41420bc86cfSAndreas Gohr  $cmd  = $conf['im_convert'];
41520bc86cfSAndreas Gohr  $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
41620bc86cfSAndreas Gohr  if ($ext == 'jpg' || $ext == 'jpeg') {
41720bc86cfSAndreas Gohr      $cmd .= ' -quality '.$conf['jpg_quality'];
41820bc86cfSAndreas Gohr  }
41920bc86cfSAndreas Gohr  $cmd .= " $from $to";
42020bc86cfSAndreas Gohr
42120bc86cfSAndreas Gohr  @exec($cmd,$out,$retval);
42220bc86cfSAndreas Gohr  if ($retval == 0) return true;
42320bc86cfSAndreas Gohr  return false;
42420bc86cfSAndreas Gohr}
42520bc86cfSAndreas Gohr
42620bc86cfSAndreas Gohr/**
42720bc86cfSAndreas Gohr * resize or crop images using PHP's libGD support
428f62ea8a1Sandi *
429f62ea8a1Sandi * @author Andreas Gohr <andi@splitbrain.org>
430e582e8b6Ss_wienecke * @author Sebastian Wienecke <s_wienecke@web.de>
431f62ea8a1Sandi */
43220bc86cfSAndreas Gohrfunction resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
433f62ea8a1Sandi  global $conf;
434f62ea8a1Sandi
435f62ea8a1Sandi  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
436f62ea8a1Sandi
4374e406776SAndreas Gohr  // check available memory
4384e406776SAndreas Gohr  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
4394e406776SAndreas Gohr    return false;
4404e406776SAndreas Gohr  }
4414e406776SAndreas Gohr
442f62ea8a1Sandi  // create an image of the given filetype
443f62ea8a1Sandi  if ($ext == 'jpg' || $ext == 'jpeg'){
444f62ea8a1Sandi    if(!function_exists("imagecreatefromjpeg")) return false;
445f62ea8a1Sandi    $image = @imagecreatefromjpeg($from);
446f62ea8a1Sandi  }elseif($ext == 'png') {
447f62ea8a1Sandi    if(!function_exists("imagecreatefrompng")) return false;
448f62ea8a1Sandi    $image = @imagecreatefrompng($from);
449f62ea8a1Sandi
450f62ea8a1Sandi  }elseif($ext == 'gif') {
451f62ea8a1Sandi    if(!function_exists("imagecreatefromgif")) return false;
452f62ea8a1Sandi    $image = @imagecreatefromgif($from);
453f62ea8a1Sandi  }
454f62ea8a1Sandi  if(!$image) return false;
455f62ea8a1Sandi
456e582e8b6Ss_wienecke  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
457f62ea8a1Sandi    $newimg = @imagecreatetruecolor ($to_w, $to_h);
458f62ea8a1Sandi  }
459f62ea8a1Sandi  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
460dd7bbbf4SAndreas Gohr  if(!$newimg){
461dd7bbbf4SAndreas Gohr    imagedestroy($image);
462dd7bbbf4SAndreas Gohr    return false;
463dd7bbbf4SAndreas Gohr  }
464f62ea8a1Sandi
465f62ea8a1Sandi  //keep png alpha channel if possible
466f62ea8a1Sandi  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
467f62ea8a1Sandi    imagealphablending($newimg, false);
468f62ea8a1Sandi    imagesavealpha($newimg,true);
469f62ea8a1Sandi  }
470f62ea8a1Sandi
471e582e8b6Ss_wienecke  //keep gif transparent color if possible
472e582e8b6Ss_wienecke  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
473e582e8b6Ss_wienecke    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
474e582e8b6Ss_wienecke      $transcolorindex = @imagecolortransparent($image);
475e582e8b6Ss_wienecke      if($transcolorindex >= 0 ) { //transparent color exists
476e582e8b6Ss_wienecke        $transcolor = @imagecolorsforindex($image, $transcolorindex);
477e582e8b6Ss_wienecke        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
478e582e8b6Ss_wienecke        @imagefill($newimg, 0, 0, $transcolorindex);
479e582e8b6Ss_wienecke        @imagecolortransparent($newimg, $transcolorindex);
480e582e8b6Ss_wienecke      }else{ //filling with white
481e582e8b6Ss_wienecke        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
482e582e8b6Ss_wienecke        @imagefill($newimg, 0, 0, $whitecolorindex);
483e582e8b6Ss_wienecke      }
484e582e8b6Ss_wienecke    }else{ //filling with white
485e582e8b6Ss_wienecke      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
486e582e8b6Ss_wienecke      @imagefill($newimg, 0, 0, $whitecolorindex);
487e582e8b6Ss_wienecke    }
488e582e8b6Ss_wienecke  }
489e582e8b6Ss_wienecke
490f62ea8a1Sandi  //try resampling first
491f62ea8a1Sandi  if(function_exists("imagecopyresampled")){
49220bc86cfSAndreas Gohr    if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
49320bc86cfSAndreas Gohr      imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
494f62ea8a1Sandi    }
495f62ea8a1Sandi  }else{
49620bc86cfSAndreas Gohr    imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
497f62ea8a1Sandi  }
498f62ea8a1Sandi
499dd7bbbf4SAndreas Gohr  $okay = false;
500f62ea8a1Sandi  if ($ext == 'jpg' || $ext == 'jpeg'){
501dd7bbbf4SAndreas Gohr    if(!function_exists('imagejpeg')){
502dd7bbbf4SAndreas Gohr      $okay = false;
503dd7bbbf4SAndreas Gohr    }else{
5042b03e74dSBen Coburn      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
505dd7bbbf4SAndreas Gohr    }
506f62ea8a1Sandi  }elseif($ext == 'png') {
507dd7bbbf4SAndreas Gohr    if(!function_exists('imagepng')){
508dd7bbbf4SAndreas Gohr      $okay = false;
509dd7bbbf4SAndreas Gohr    }else{
510dd7bbbf4SAndreas Gohr      $okay =  imagepng($newimg, $to);
511dd7bbbf4SAndreas Gohr    }
512f62ea8a1Sandi  }elseif($ext == 'gif') {
513dd7bbbf4SAndreas Gohr    if(!function_exists('imagegif')){
514dd7bbbf4SAndreas Gohr      $okay = false;
515dd7bbbf4SAndreas Gohr    }else{
516dd7bbbf4SAndreas Gohr      $okay = imagegif($newimg, $to);
517dd7bbbf4SAndreas Gohr    }
518f62ea8a1Sandi  }
519f62ea8a1Sandi
520dd7bbbf4SAndreas Gohr  // destroy GD image ressources
521dd7bbbf4SAndreas Gohr  if($image) imagedestroy($image);
522dd7bbbf4SAndreas Gohr  if($newimg) imagedestroy($newimg);
523dd7bbbf4SAndreas Gohr
524dd7bbbf4SAndreas Gohr  return $okay;
525f62ea8a1Sandi}
526f62ea8a1Sandi
5274e406776SAndreas Gohr/**
5284e406776SAndreas Gohr * Checks if the given amount of memory is available
5294e406776SAndreas Gohr *
5304e406776SAndreas Gohr * If the memory_get_usage() function is not available the
53173038c47SAndreas Gohr * function just assumes $bytes of already allocated memory
5324e406776SAndreas Gohr *
5334e406776SAndreas Gohr * @param  int $mem  Size of memory you want to allocate in bytes
5344e406776SAndreas Gohr * @param  int $used already allocated memory (see above)
5354e406776SAndreas Gohr * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
5364e406776SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5374e406776SAndreas Gohr */
5384e406776SAndreas Gohrfunction is_mem_available($mem,$bytes=1048576){
5394e406776SAndreas Gohr  $limit = trim(ini_get('memory_limit'));
5404e406776SAndreas Gohr  if(empty($limit)) return true; // no limit set!
5414e406776SAndreas Gohr
5424e406776SAndreas Gohr  // parse limit to bytes
54373038c47SAndreas Gohr  $limit = php_to_byte($limit);
5444e406776SAndreas Gohr
5454e406776SAndreas Gohr  // get used memory if possible
5464e406776SAndreas Gohr  if(function_exists('memory_get_usage')){
5474e406776SAndreas Gohr    $used = memory_get_usage();
5484e406776SAndreas Gohr  }
5494e406776SAndreas Gohr
5504e406776SAndreas Gohr  if($used+$mem > $limit){
5514e406776SAndreas Gohr    return false;
5524e406776SAndreas Gohr  }
5534e406776SAndreas Gohr
5544e406776SAndreas Gohr  return true;
5554e406776SAndreas Gohr}
556f62ea8a1Sandi
557f62ea8a1Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
558f62ea8a1Sandi?>
559