xref: /dokuwiki/lib/exe/fetch.php (revision 35876a0c9db73d9c77c03456b1910ee1529e3c96)
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
250  // calculate crop size
251  $fr = $info[0]/$info[1];
252  $tr = $w/$h;
253  if($tr >= 1){
254    if($tr > $fr){
255        $cw = $info[0];
256        $ch = (int) $info[0]/$tr;
257    }else{
258        $cw = (int) $info[1]*$tr;
259        $ch = $info[1];
260    }
261  }else{
262    if($tr < $fr){
263        $cw = (int) $info[1]*$tr;
264        $ch = $info[1];
265    }else{
266        $cw = $info[0];
267        $ch = (int) $info[0]/$tr;
268    }
269  }
270  // calculate crop offset
271  $cx = (int) ($info[0]-$cw)/2;
272  $cy = (int) ($info[1]-$ch)/3;
273
274  //cache
275  $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
276  $mtime = @filemtime($local); // 0 if not exists
277
278  if( $mtime > filemtime($file) ||
279      crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
280      resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
281    if($conf['fperm']) chmod($local, $conf['fperm']);
282    return get_resized($local,$ext, $w, $h);
283  }
284
285  //still here? cropping failed
286  return get_resized($file,$ext, $w, $h);
287}
288
289
290/**
291 * Returns the wanted cachetime in seconds
292 *
293 * Resolves named constants
294 *
295 * @author  Andreas Gohr <andi@splitbrain.org>
296 */
297function calc_cache($cache){
298  global $conf;
299
300  if(strtolower($cache) == 'nocache') return 0; //never cache
301  if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
302  return -1; //cache endless
303}
304
305/**
306 * Download a remote file and return local filename
307 *
308 * returns false if download fails. Uses cached file if available and
309 * wanted
310 *
311 * @author  Andreas Gohr <andi@splitbrain.org>
312 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
313 */
314function get_from_URL($url,$ext,$cache){
315  global $conf;
316
317  // if no cache or fetchsize just redirect
318  if ($cache==0)           return false;
319  if (!$conf['fetchsize']) return false;
320
321  $local = getCacheName(strtolower($url),".media.$ext");
322  $mtime = @filemtime($local); // 0 if not exists
323
324  //decide if download needed:
325  if( ($mtime == 0) ||                           // cache does not exist
326      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
327    ){
328      if(image_download($url,$local)){
329        return $local;
330      }else{
331        return false;
332      }
333  }
334
335  //if cache exists use it else
336  if($mtime) return $local;
337
338  //else return false
339  return false;
340}
341
342/**
343 * Download image files
344 *
345 * @author Andreas Gohr <andi@splitbrain.org>
346 */
347function image_download($url,$file){
348  global $conf;
349  $http = new DokuHTTPClient();
350  $http->max_bodysize = $conf['fetchsize'];
351  $http->timeout = 25; //max. 25 sec
352  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
353
354  $data = $http->get($url);
355  if(!$data) return false;
356
357  $fileexists = @file_exists($file);
358  $fp = @fopen($file,"w");
359  if(!$fp) return false;
360  fwrite($fp,$data);
361  fclose($fp);
362  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
363
364  // check if it is really an image
365  $info = @getimagesize($file);
366  if(!$info){
367    @unlink($file);
368    return false;
369  }
370
371  return true;
372}
373
374/**
375 * resize images using external ImageMagick convert program
376 *
377 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
378 * @author Andreas Gohr <andi@splitbrain.org>
379 */
380function resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
381  global $conf;
382
383  // check if convert is configured
384  if(!$conf['im_convert']) return false;
385
386  // prepare command
387  $cmd  = $conf['im_convert'];
388  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
389  if ($ext == 'jpg' || $ext == 'jpeg') {
390      $cmd .= ' -quality '.$conf['jpg_quality'];
391  }
392  $cmd .= " $from $to";
393
394  @exec($cmd,$out,$retval);
395  if ($retval == 0) return true;
396  return false;
397}
398
399/**
400 * crop images using external ImageMagick convert program
401 *
402 * @author Andreas Gohr <andi@splitbrain.org>
403 */
404function crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
405  global $conf;
406
407  // check if convert is configured
408  if(!$conf['im_convert']) return false;
409
410  // prepare command
411  $cmd  = $conf['im_convert'];
412  $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
413  if ($ext == 'jpg' || $ext == 'jpeg') {
414      $cmd .= ' -quality '.$conf['jpg_quality'];
415  }
416  $cmd .= " $from $to";
417
418  @exec($cmd,$out,$retval);
419  if ($retval == 0) return true;
420  return false;
421}
422
423/**
424 * resize or crop images using PHP's libGD support
425 *
426 * @author Andreas Gohr <andi@splitbrain.org>
427 * @author Sebastian Wienecke <s_wienecke@web.de>
428 */
429function resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
430  global $conf;
431
432  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
433
434  // check available memory
435  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
436    return false;
437  }
438
439  // create an image of the given filetype
440  if ($ext == 'jpg' || $ext == 'jpeg'){
441    if(!function_exists("imagecreatefromjpeg")) return false;
442    $image = @imagecreatefromjpeg($from);
443  }elseif($ext == 'png') {
444    if(!function_exists("imagecreatefrompng")) return false;
445    $image = @imagecreatefrompng($from);
446
447  }elseif($ext == 'gif') {
448    if(!function_exists("imagecreatefromgif")) return false;
449    $image = @imagecreatefromgif($from);
450  }
451  if(!$image) return false;
452
453  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
454    $newimg = @imagecreatetruecolor ($to_w, $to_h);
455  }
456  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
457  if(!$newimg){
458    imagedestroy($image);
459    return false;
460  }
461
462  //keep png alpha channel if possible
463  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
464    imagealphablending($newimg, false);
465    imagesavealpha($newimg,true);
466  }
467
468  //keep gif transparent color if possible
469  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
470    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
471      $transcolorindex = @imagecolortransparent($image);
472      if($transcolorindex >= 0 ) { //transparent color exists
473        $transcolor = @imagecolorsforindex($image, $transcolorindex);
474        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
475        @imagefill($newimg, 0, 0, $transcolorindex);
476        @imagecolortransparent($newimg, $transcolorindex);
477      }else{ //filling with white
478        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
479        @imagefill($newimg, 0, 0, $whitecolorindex);
480      }
481    }else{ //filling with white
482      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
483      @imagefill($newimg, 0, 0, $whitecolorindex);
484    }
485  }
486
487  //try resampling first
488  if(function_exists("imagecopyresampled")){
489    if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
490      imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
491    }
492  }else{
493    imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
494  }
495
496  $okay = false;
497  if ($ext == 'jpg' || $ext == 'jpeg'){
498    if(!function_exists('imagejpeg')){
499      $okay = false;
500    }else{
501      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
502    }
503  }elseif($ext == 'png') {
504    if(!function_exists('imagepng')){
505      $okay = false;
506    }else{
507      $okay =  imagepng($newimg, $to);
508    }
509  }elseif($ext == 'gif') {
510    if(!function_exists('imagegif')){
511      $okay = false;
512    }else{
513      $okay = imagegif($newimg, $to);
514    }
515  }
516
517  // destroy GD image ressources
518  if($image) imagedestroy($image);
519  if($newimg) imagedestroy($newimg);
520
521  return $okay;
522}
523
524/**
525 * Checks if the given amount of memory is available
526 *
527 * If the memory_get_usage() function is not available the
528 * function just assumes $bytes of already allocated memory
529 *
530 * @param  int $mem  Size of memory you want to allocate in bytes
531 * @param  int $used already allocated memory (see above)
532 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
533 * @author Andreas Gohr <andi@splitbrain.org>
534 */
535function is_mem_available($mem,$bytes=1048576){
536  $limit = trim(ini_get('memory_limit'));
537  if(empty($limit)) return true; // no limit set!
538
539  // parse limit to bytes
540  $limit = php_to_byte($limit);
541
542  // get used memory if possible
543  if(function_exists('memory_get_usage')){
544    $used = memory_get_usage();
545  }
546
547  if($used+$mem > $limit){
548    return false;
549  }
550
551  return true;
552}
553
554//Setup VIM: ex: et ts=2 enc=utf-8 :
555?>
556