xref: /dokuwiki/lib/exe/fetch.php (revision d1accf260c7c4d3b6d0ed6bdf3538e91573d0de8)
1<?php
2/**
3 * DokuWiki media passthrough file
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9  if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
10  define('DOKU_DISABLE_GZIP_OUTPUT', 1);
11  require_once(DOKU_INC.'inc/init.php');
12  require_once(DOKU_INC.'inc/common.php');
13  require_once(DOKU_INC.'inc/pageutils.php');
14  require_once(DOKU_INC.'inc/confutils.php');
15  require_once(DOKU_INC.'inc/auth.php');
16  //close sesseion
17  session_write_close();
18  if(!defined('CHUNK_SIZE')) define('CHUNK_SIZE',16*1024);
19
20  $mimetypes = getMimeTypes();
21
22  //get input
23  $MEDIA  = stripctl(getID('media',false)); // no cleaning except control chars - maybe external
24  $CACHE  = calc_cache($_REQUEST['cache']);
25  $WIDTH  = (int) $_REQUEST['w'];
26  $HEIGHT = (int) $_REQUEST['h'];
27  list($EXT,$MIME) = mimetype($MEDIA);
28  if($EXT === false){
29    $EXT  = 'unknown';
30    $MIME = 'application/octet-stream';
31  }
32
33  //media to local file
34  if(preg_match('#^(https?)://#i',$MEDIA)){
35    //handle external images
36    if(strncmp($MIME,'image/',6) == 0) $FILE = get_from_URL($MEDIA,$EXT,$CACHE);
37    if(!$FILE){
38      //download failed - redirect to original URL
39      header('Location: '.$MEDIA);
40      exit;
41    }
42  }else{
43    $MEDIA = cleanID($MEDIA);
44    if(empty($MEDIA)){
45      header("HTTP/1.0 400 Bad Request");
46      print 'Bad request';
47      exit;
48    }
49
50    //check permissions (namespace only)
51    if(auth_quickaclcheck(getNS($MEDIA).':X') < AUTH_READ){
52      header("HTTP/1.0 401 Unauthorized");
53      //fixme add some image for imagefiles
54      print 'Unauthorized';
55      exit;
56    }
57    $FILE  = mediaFN($MEDIA);
58  }
59
60  //check file existance
61  if(!@file_exists($FILE)){
62    header("HTTP/1.0 404 Not Found");
63    //FIXME add some default broken image
64    print 'Not Found';
65    exit;
66  }
67
68  $ORIG = $FILE;
69
70  //handle image resizing/cropping
71  if((substr($MIME,0,5) == 'image') && $WIDTH){
72    if($HEIGHT){
73        $FILE = get_cropped($FILE,$EXT,$WIDTH,$HEIGHT);
74    }else{
75        $FILE = get_resized($FILE,$EXT,$WIDTH,$HEIGHT);
76    }
77  }
78
79  // finally send the file to the client
80  $data = array('file'   => $FILE,
81                'mime'   => $MIME,
82                'cache'  => $CACHE,
83                'orig'   => $ORIG,
84                'ext'    => $EXT,
85                'width'  => $WIDTH,
86                'height' => $HEIGHT);
87
88  $evt = new Doku_Event('MEDIA_SENDFILE', $data);
89  if ($evt->advise_before()) {
90    sendFile($data['file'],$data['mime'],$data['cache']);
91  }
92
93/* ------------------------------------------------------------------------ */
94
95/**
96 * Set headers and send the file to the client
97 *
98 * @author Andreas Gohr <andi@splitbrain.org>
99 * @author Ben Coburn <btcoburn@silicodon.net>
100 */
101function sendFile($file,$mime,$cache){
102  global $conf;
103  $fmtime = filemtime($file);
104  // send headers
105  header("Content-Type: $mime");
106  // smart http caching headers
107  if ($cache==-1) {
108    // cache
109    // cachetime or one hour
110    header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
111    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
112    header('Pragma: public');
113  } else if ($cache>0) {
114    // recache
115    // remaining cachetime + 10 seconds so the newly recached media is used
116    header('Expires: '.gmdate("D, d M Y H:i:s", $fmtime+$conf['cachetime']+10).' GMT');
117    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($fmtime-time()+$conf['cachetime']+10, 0));
118    header('Pragma: public');
119  } else if ($cache==0) {
120    // nocache
121    header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
122    header('Pragma: public');
123  }
124  //send important headers first, script stops here if '304 Not Modified' response
125  http_conditionalRequest($fmtime);
126
127
128  //application mime type is downloadable
129  if(substr($mime,0,11) == 'application'){
130    header('Content-Disposition: attachment; filename="'.basename($file).'";');
131  }
132
133  //use x-sendfile header to pass the delivery to compatible webservers
134  if($conf['xsendfile'] == 1){
135    header("X-LIGHTTPD-send-file: $file");
136    exit;
137  }elseif($conf['xsendfile'] == 2){
138    header("X-Sendfile: $file");
139    exit;
140  }elseif($conf['xsendfile'] == 3){
141    header("X-Accel-Redirect: $file");
142    exit;
143  }
144
145  //support download continueing
146  header('Accept-Ranges: bytes');
147  list($start,$len) = http_rangeRequest(filesize($file));
148
149  // send file contents
150  $fp = @fopen($file,"rb");
151  if($fp){
152    fseek($fp,$start); //seek to start of range
153
154    $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
155    while (!feof($fp) && $chunk > 0) {
156      @set_time_limit(30); // large files can take a lot of time
157      print fread($fp, $chunk);
158      flush();
159      $len -= $chunk;
160      $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
161    }
162    fclose($fp);
163  }else{
164    header("HTTP/1.0 500 Internal Server Error");
165    print "Could not read $file - bad permissions?";
166  }
167}
168
169/**
170 * Checks and sets headers to handle range requets
171 *
172 * @author  Andreas Gohr <andi@splitbrain.org>
173 * @returns array The start byte and the amount of bytes to send
174 */
175function http_rangeRequest($size){
176  if(!isset($_SERVER['HTTP_RANGE'])){
177    // no range requested - send the whole file
178    header("Content-Length: $size");
179    return array(0,$size);
180  }
181
182  $t = explode('=', $_SERVER['HTTP_RANGE']);
183  if (!$t[0]=='bytes') {
184    // we only understand byte ranges - send the whole file
185    header("Content-Length: $size");
186    return array(0,$size);
187  }
188
189  $r = explode('-', $t[1]);
190  $start = (int)$r[0];
191  $end = (int)$r[1];
192  if (!$end) $end = $size - 1;
193  if ($start > $end || $start > $size || $end > $size){
194    header('HTTP/1.1 416 Requested Range Not Satisfiable');
195    print 'Bad Range Request!';
196    exit;
197  }
198
199  $tot = $end - $start + 1;
200  header('HTTP/1.1 206 Partial Content');
201  header("Content-Range: bytes {$start}-{$end}/{$size}");
202  header("Content-Length: $tot");
203
204  return array($start,$tot);
205}
206
207/**
208 * Resizes the given image to the given size
209 *
210 * @author  Andreas Gohr <andi@splitbrain.org>
211 */
212function get_resized($file, $ext, $w, $h=0){
213  global $conf;
214
215  $info  = getimagesize($file);
216  if(!$h) $h = round(($w * $info[1]) / $info[0]);
217
218  // we wont scale up to infinity
219  if($w > 2000 || $h > 2000) return $file;
220
221  //cache
222  $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
223  $mtime = @filemtime($local); // 0 if not exists
224
225  if( $mtime > filemtime($file) ||
226      resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
227      resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
228    if($conf['fperm']) chmod($local, $conf['fperm']);
229    return $local;
230  }
231  //still here? resizing failed
232  return $file;
233}
234
235/**
236 * Crops the given image to the wanted ratio, then calls get_resized to scale it
237 * to the wanted size
238 *
239 * Crops are centered horizontally but prefer the upper third of an vertical
240 * image because most pics are more interesting in that area (rule of thirds)
241 *
242 * @author  Andreas Gohr <andi@splitbrain.org>
243 */
244function get_cropped($file, $ext, $w, $h=0){
245  global $conf;
246
247  if(!$h) $h = $w;
248  $info = @getimagesize($file); //get original size
249  if($info == false) return $file; // that's no image - it's a spaceship!
250
251  // calculate crop size
252  $fr = $info[0]/$info[1];
253  $tr = $w/$h;
254  if($tr >= 1){
255    if($tr > $fr){
256        $cw = $info[0];
257        $ch = (int) $info[0]/$tr;
258    }else{
259        $cw = (int) $info[1]*$tr;
260        $ch = $info[1];
261    }
262  }else{
263    if($tr < $fr){
264        $cw = (int) $info[1]*$tr;
265        $ch = $info[1];
266    }else{
267        $cw = $info[0];
268        $ch = (int) $info[0]/$tr;
269    }
270  }
271  // calculate crop offset
272  $cx = (int) ($info[0]-$cw)/2;
273  $cy = (int) ($info[1]-$ch)/3;
274
275  //cache
276  $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
277  $mtime = @filemtime($local); // 0 if not exists
278
279  if( $mtime > filemtime($file) ||
280      crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
281      resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
282    if($conf['fperm']) chmod($local, $conf['fperm']);
283    return get_resized($local,$ext, $w, $h);
284  }
285
286  //still here? cropping failed
287  return get_resized($file,$ext, $w, $h);
288}
289
290
291/**
292 * Returns the wanted cachetime in seconds
293 *
294 * Resolves named constants
295 *
296 * @author  Andreas Gohr <andi@splitbrain.org>
297 */
298function calc_cache($cache){
299  global $conf;
300
301  if(strtolower($cache) == 'nocache') return 0; //never cache
302  if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
303  return -1; //cache endless
304}
305
306/**
307 * Download a remote file and return local filename
308 *
309 * returns false if download fails. Uses cached file if available and
310 * wanted
311 *
312 * @author  Andreas Gohr <andi@splitbrain.org>
313 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
314 */
315function get_from_URL($url,$ext,$cache){
316  global $conf;
317
318  // if no cache or fetchsize just redirect
319  if ($cache==0)           return false;
320  if (!$conf['fetchsize']) return false;
321
322  $local = getCacheName(strtolower($url),".media.$ext");
323  $mtime = @filemtime($local); // 0 if not exists
324
325  //decide if download needed:
326  if( ($mtime == 0) ||                           // cache does not exist
327      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
328    ){
329      if(image_download($url,$local)){
330        return $local;
331      }else{
332        return false;
333      }
334  }
335
336  //if cache exists use it else
337  if($mtime) return $local;
338
339  //else return false
340  return false;
341}
342
343/**
344 * Download image files
345 *
346 * @author Andreas Gohr <andi@splitbrain.org>
347 */
348function image_download($url,$file){
349  global $conf;
350  $http = new DokuHTTPClient();
351  $http->max_bodysize = $conf['fetchsize'];
352  $http->timeout = 25; //max. 25 sec
353  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
354
355  $data = $http->get($url);
356  if(!$data) return false;
357
358  $fileexists = @file_exists($file);
359  $fp = @fopen($file,"w");
360  if(!$fp) return false;
361  fwrite($fp,$data);
362  fclose($fp);
363  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
364
365  // check if it is really an image
366  $info = @getimagesize($file);
367  if(!$info){
368    @unlink($file);
369    return false;
370  }
371
372  return true;
373}
374
375/**
376 * resize images using external ImageMagick convert program
377 *
378 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
379 * @author Andreas Gohr <andi@splitbrain.org>
380 */
381function resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
382  global $conf;
383
384  // check if convert is configured
385  if(!$conf['im_convert']) return false;
386
387  // prepare command
388  $cmd  = $conf['im_convert'];
389  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
390  if ($ext == 'jpg' || $ext == 'jpeg') {
391      $cmd .= ' -quality '.$conf['jpg_quality'];
392  }
393  $cmd .= " $from $to";
394
395  @exec($cmd,$out,$retval);
396  if ($retval == 0) return true;
397  return false;
398}
399
400/**
401 * crop images using external ImageMagick convert program
402 *
403 * @author Andreas Gohr <andi@splitbrain.org>
404 */
405function crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
406  global $conf;
407
408  // check if convert is configured
409  if(!$conf['im_convert']) return false;
410
411  // prepare command
412  $cmd  = $conf['im_convert'];
413  $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
414  if ($ext == 'jpg' || $ext == 'jpeg') {
415      $cmd .= ' -quality '.$conf['jpg_quality'];
416  }
417  $cmd .= " $from $to";
418
419  @exec($cmd,$out,$retval);
420  if ($retval == 0) return true;
421  return false;
422}
423
424/**
425 * resize or crop images using PHP's libGD support
426 *
427 * @author Andreas Gohr <andi@splitbrain.org>
428 * @author Sebastian Wienecke <s_wienecke@web.de>
429 */
430function resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
431  global $conf;
432
433  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
434
435  // check available memory
436  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
437    return false;
438  }
439
440  // create an image of the given filetype
441  if ($ext == 'jpg' || $ext == 'jpeg'){
442    if(!function_exists("imagecreatefromjpeg")) return false;
443    $image = @imagecreatefromjpeg($from);
444  }elseif($ext == 'png') {
445    if(!function_exists("imagecreatefrompng")) return false;
446    $image = @imagecreatefrompng($from);
447
448  }elseif($ext == 'gif') {
449    if(!function_exists("imagecreatefromgif")) return false;
450    $image = @imagecreatefromgif($from);
451  }
452  if(!$image) return false;
453
454  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
455    $newimg = @imagecreatetruecolor ($to_w, $to_h);
456  }
457  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
458  if(!$newimg){
459    imagedestroy($image);
460    return false;
461  }
462
463  //keep png alpha channel if possible
464  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
465    imagealphablending($newimg, false);
466    imagesavealpha($newimg,true);
467  }
468
469  //keep gif transparent color if possible
470  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
471    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
472      $transcolorindex = @imagecolortransparent($image);
473      if($transcolorindex >= 0 ) { //transparent color exists
474        $transcolor = @imagecolorsforindex($image, $transcolorindex);
475        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
476        @imagefill($newimg, 0, 0, $transcolorindex);
477        @imagecolortransparent($newimg, $transcolorindex);
478      }else{ //filling with white
479        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
480        @imagefill($newimg, 0, 0, $whitecolorindex);
481      }
482    }else{ //filling with white
483      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
484      @imagefill($newimg, 0, 0, $whitecolorindex);
485    }
486  }
487
488  //try resampling first
489  if(function_exists("imagecopyresampled")){
490    if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
491      imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
492    }
493  }else{
494    imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
495  }
496
497  $okay = false;
498  if ($ext == 'jpg' || $ext == 'jpeg'){
499    if(!function_exists('imagejpeg')){
500      $okay = false;
501    }else{
502      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
503    }
504  }elseif($ext == 'png') {
505    if(!function_exists('imagepng')){
506      $okay = false;
507    }else{
508      $okay =  imagepng($newimg, $to);
509    }
510  }elseif($ext == 'gif') {
511    if(!function_exists('imagegif')){
512      $okay = false;
513    }else{
514      $okay = imagegif($newimg, $to);
515    }
516  }
517
518  // destroy GD image ressources
519  if($image) imagedestroy($image);
520  if($newimg) imagedestroy($newimg);
521
522  return $okay;
523}
524
525/**
526 * Checks if the given amount of memory is available
527 *
528 * If the memory_get_usage() function is not available the
529 * function just assumes $bytes of already allocated memory
530 *
531 * @param  int $mem  Size of memory you want to allocate in bytes
532 * @param  int $used already allocated memory (see above)
533 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
534 * @author Andreas Gohr <andi@splitbrain.org>
535 */
536function is_mem_available($mem,$bytes=1048576){
537  $limit = trim(ini_get('memory_limit'));
538  if(empty($limit)) return true; // no limit set!
539
540  // parse limit to bytes
541  $limit = php_to_byte($limit);
542
543  // get used memory if possible
544  if(function_exists('memory_get_usage')){
545    $used = memory_get_usage();
546  }
547
548  if($used+$mem > $limit){
549    return false;
550  }
551
552  return true;
553}
554
555//Setup VIM: ex: et ts=2 enc=utf-8 :
556?>
557