xref: /dokuwiki/lib/exe/fetch.php (revision c06cd517522c06ce1095926770bef7a66cd2714e)
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  //handle image resizing
69  if((substr($MIME,0,5) == 'image') && $WIDTH){
70    $FILE = get_resized($FILE,$EXT,$WIDTH,$HEIGHT);
71  }
72
73  // finally send the file to the client
74  sendFile($FILE,$MIME,$CACHE);
75
76/* ------------------------------------------------------------------------ */
77
78/**
79 * Set headers and send the file to the client
80 *
81 * @author Andreas Gohr <andi@splitbrain.org>
82 * @author Ben Coburn <btcoburn@silicodon.net>
83 */
84function sendFile($file,$mime,$cache){
85  global $conf;
86  $fmtime = filemtime($file);
87  // send headers
88  header("Content-Type: $mime");
89  // smart http caching headers
90  if ($cache==-1) {
91    // cache
92    // cachetime or one hour
93    header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
94    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
95    header('Pragma: public');
96  } else if ($cache>0) {
97    // recache
98    // remaining cachetime + 10 seconds so the newly recached media is used
99    header('Expires: '.gmdate("D, d M Y H:i:s", $fmtime+$conf['cachetime']+10).' GMT');
100    header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($fmtime-time()+$conf['cachetime']+10, 0));
101    header('Pragma: public');
102  } else if ($cache==0) {
103    // nocache
104    header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
105    header('Pragma: public');
106  }
107  //send important headers first, script stops here if '304 Not Modified' response
108  http_conditionalRequest($fmtime);
109
110
111  //application mime type is downloadable
112  if(substr($mime,0,11) == 'application'){
113    header('Content-Disposition: attachment; filename="'.basename($file).'";');
114  }
115
116  //use x-sendfile header to pass the delivery to compatible webservers
117  if($conf['xsendfile'] == 1){
118    header("X-LIGHTTPD-send-file: $file");
119    exit;
120  }elseif($conf['xsendfile'] == 2){
121    header("X-Sendfile: $file");
122    exit;
123  }elseif($conf['xsendfile'] == 3){
124    header("X-Accel-Redirect: $file");
125    exit;
126  }
127
128  //support download continueing
129  header('Accept-Ranges: bytes');
130  list($start,$len) = http_rangeRequest(filesize($file));
131
132  // send file contents
133  $fp = @fopen($file,"rb");
134  if($fp){
135    fseek($fp,$start); //seek to start of range
136
137    $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
138    while (!feof($fp) && $chunk > 0) {
139      @set_time_limit(30); // large files can take a lot of time
140      print fread($fp, $chunk);
141      flush();
142      $len -= $chunk;
143      $chunk = ($len > CHUNK_SIZE) ? CHUNK_SIZE : $len;
144    }
145    fclose($fp);
146  }else{
147    header("HTTP/1.0 500 Internal Server Error");
148    print "Could not read $file - bad permissions?";
149  }
150}
151
152/**
153 * Checks and sets headers to handle range requets
154 *
155 * @author  Andreas Gohr <andi@splitbrain.org>
156 * @returns array The start byte and the amount of bytes to send
157 */
158function http_rangeRequest($size){
159  if(!isset($_SERVER['HTTP_RANGE'])){
160    // no range requested - send the whole file
161    header("Content-Length: $size");
162    return array(0,$size);
163  }
164
165  $t = explode('=', $_SERVER['HTTP_RANGE']);
166  if (!$t[0]=='bytes') {
167    // we only understand byte ranges - send the whole file
168    header("Content-Length: $size");
169    return array(0,$size);
170  }
171
172  $r = explode('-', $t[1]);
173  $start = (int)$r[0];
174  $end = (int)$r[1];
175  if (!$end) $end = $size - 1;
176  if ($start > $end || $start > $size || $end > $size){
177    header('HTTP/1.1 416 Requested Range Not Satisfiable');
178    print 'Bad Range Request!';
179    exit;
180  }
181
182  $tot = $end - $start + 1;
183  header('HTTP/1.1 206 Partial Content');
184  header("Content-Range: bytes {$start}-{$end}/{$size}");
185  header("Content-Length: $tot");
186
187  return array($start,$tot);
188}
189
190/**
191 * Resizes the given image to the given size
192 *
193 * @author  Andreas Gohr <andi@splitbrain.org>
194 */
195function get_resized($file, $ext, $w, $h=0){
196  global $conf;
197
198  $info  = getimagesize($file);
199  if(!$h) $h = round(($w * $info[1]) / $info[0]);
200
201  // we wont scale up to infinity
202  if($w > 2000 || $h > 2000) return $file;
203
204  //cache
205  $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
206  $mtime = @filemtime($local); // 0 if not exists
207
208  if( $mtime > filemtime($file) ||
209      resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
210      resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
211    return $local;
212  }
213  //still here? resizing failed
214  return $file;
215}
216
217/**
218 * Returns the wanted cachetime in seconds
219 *
220 * Resolves named constants
221 *
222 * @author  Andreas Gohr <andi@splitbrain.org>
223 */
224function calc_cache($cache){
225  global $conf;
226
227  if(strtolower($cache) == 'nocache') return 0; //never cache
228  if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
229  return -1; //cache endless
230}
231
232/**
233 * Download a remote file and return local filename
234 *
235 * returns false if download fails. Uses cached file if available and
236 * wanted
237 *
238 * @author  Andreas Gohr <andi@splitbrain.org>
239 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
240 */
241function get_from_URL($url,$ext,$cache){
242  global $conf;
243
244  // if no cache or fetchsize just redirect
245  if ($cache==0)           return false;
246  if (!$conf['fetchsize']) return false;
247
248  $local = getCacheName(strtolower($url),".media.$ext");
249  $mtime = @filemtime($local); // 0 if not exists
250
251  //decide if download needed:
252  if( ($mtime == 0) ||                           // cache does not exist
253      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
254    ){
255      if(image_download($url,$local)){
256        return $local;
257      }else{
258        return false;
259      }
260  }
261
262  //if cache exists use it else
263  if($mtime) return $local;
264
265  //else return false
266  return false;
267}
268
269/**
270 * Download image files
271 *
272 * @author Andreas Gohr <andi@splitbrain.org>
273 */
274function image_download($url,$file){
275  global $conf;
276  $http = new DokuHTTPClient();
277  $http->max_bodysize = $conf['fetchsize'];
278  $http->timeout = 25; //max. 25 sec
279  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
280
281  $data = $http->get($url);
282  if(!$data) return false;
283
284  $fileexists = @file_exists($file);
285  $fp = @fopen($file,"w");
286  if(!$fp) return false;
287  fwrite($fp,$data);
288  fclose($fp);
289  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
290
291  // check if it is really an image
292  $info = @getimagesize($file);
293  if(!$info){
294    @unlink($file);
295    return false;
296  }
297
298  return true;
299}
300
301/**
302 * resize images using external ImageMagick convert program
303 *
304 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
305 * @author Andreas Gohr <andi@splitbrain.org>
306 */
307function resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
308  global $conf;
309
310  // check if convert is configured
311  if(!$conf['im_convert']) return false;
312
313  // prepare command
314  $cmd  = $conf['im_convert'];
315  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
316  if ($ext == 'jpg' || $ext == 'jpeg') {
317      $cmd .= ' -quality '.$conf['jpg_quality'];
318  }
319  $cmd .= " $from $to";
320
321  @exec($cmd,$out,$retval);
322  if ($retval == 0) return true;
323  return false;
324}
325
326/**
327 * resize images using PHP's libGD support
328 *
329 * @author Andreas Gohr <andi@splitbrain.org>
330 * @author Sebastian Wienecke <s_wienecke@web.de>
331 */
332function resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
333  global $conf;
334
335  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
336
337  // check available memory
338  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
339    return false;
340  }
341
342  // create an image of the given filetype
343  if ($ext == 'jpg' || $ext == 'jpeg'){
344    if(!function_exists("imagecreatefromjpeg")) return false;
345    $image = @imagecreatefromjpeg($from);
346  }elseif($ext == 'png') {
347    if(!function_exists("imagecreatefrompng")) return false;
348    $image = @imagecreatefrompng($from);
349
350  }elseif($ext == 'gif') {
351    if(!function_exists("imagecreatefromgif")) return false;
352    $image = @imagecreatefromgif($from);
353  }
354  if(!$image) return false;
355
356  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
357    $newimg = @imagecreatetruecolor ($to_w, $to_h);
358  }
359  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
360  if(!$newimg){
361    imagedestroy($image);
362    return false;
363  }
364
365  //keep png alpha channel if possible
366  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
367    imagealphablending($newimg, false);
368    imagesavealpha($newimg,true);
369  }
370
371  //keep gif transparent color if possible
372  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
373    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
374      $transcolorindex = @imagecolortransparent($image);
375      if($transcolorindex >= 0 ) { //transparent color exists
376        $transcolor = @imagecolorsforindex($image, $transcolorindex);
377        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
378        @imagefill($newimg, 0, 0, $transcolorindex);
379        @imagecolortransparent($newimg, $transcolorindex);
380      }else{ //filling with white
381        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
382        @imagefill($newimg, 0, 0, $whitecolorindex);
383      }
384    }else{ //filling with white
385      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
386      @imagefill($newimg, 0, 0, $whitecolorindex);
387    }
388  }
389
390  //try resampling first
391  if(function_exists("imagecopyresampled")){
392    if(!@imagecopyresampled($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h)) {
393      imagecopyresized($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h);
394    }
395  }else{
396    imagecopyresized($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h);
397  }
398
399  $okay = false;
400  if ($ext == 'jpg' || $ext == 'jpeg'){
401    if(!function_exists('imagejpeg')){
402      $okay = false;
403    }else{
404      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
405    }
406  }elseif($ext == 'png') {
407    if(!function_exists('imagepng')){
408      $okay = false;
409    }else{
410      $okay =  imagepng($newimg, $to);
411    }
412  }elseif($ext == 'gif') {
413    if(!function_exists('imagegif')){
414      $okay = false;
415    }else{
416      $okay = imagegif($newimg, $to);
417    }
418  }
419
420  // destroy GD image ressources
421  if($image) imagedestroy($image);
422  if($newimg) imagedestroy($newimg);
423
424  return $okay;
425}
426
427/**
428 * Checks if the given amount of memory is available
429 *
430 * If the memory_get_usage() function is not available the
431 * function just assumes $bytes of already allocated memory
432 *
433 * @param  int $mem  Size of memory you want to allocate in bytes
434 * @param  int $used already allocated memory (see above)
435 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
436 * @author Andreas Gohr <andi@splitbrain.org>
437 */
438function is_mem_available($mem,$bytes=1048576){
439  $limit = trim(ini_get('memory_limit'));
440  if(empty($limit)) return true; // no limit set!
441
442  // parse limit to bytes
443  $limit = php_to_byte($limit);
444
445  // get used memory if possible
446  if(function_exists('memory_get_usage')){
447    $used = memory_get_usage();
448  }
449
450  if($used+$mem > $limit){
451    return false;
452  }
453
454  return true;
455}
456
457//Setup VIM: ex: et ts=2 enc=utf-8 :
458?>
459