xref: /dokuwiki/lib/exe/fetch.php (revision 213124048fff33fec5777750f0706ad0cfa901ee)
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    if($conf['fperm']) chmod($local, $conf['fperm']);
212    return $local;
213  }
214  //still here? resizing failed
215  return $file;
216}
217
218/**
219 * Returns the wanted cachetime in seconds
220 *
221 * Resolves named constants
222 *
223 * @author  Andreas Gohr <andi@splitbrain.org>
224 */
225function calc_cache($cache){
226  global $conf;
227
228  if(strtolower($cache) == 'nocache') return 0; //never cache
229  if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
230  return -1; //cache endless
231}
232
233/**
234 * Download a remote file and return local filename
235 *
236 * returns false if download fails. Uses cached file if available and
237 * wanted
238 *
239 * @author  Andreas Gohr <andi@splitbrain.org>
240 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
241 */
242function get_from_URL($url,$ext,$cache){
243  global $conf;
244
245  // if no cache or fetchsize just redirect
246  if ($cache==0)           return false;
247  if (!$conf['fetchsize']) return false;
248
249  $local = getCacheName(strtolower($url),".media.$ext");
250  $mtime = @filemtime($local); // 0 if not exists
251
252  //decide if download needed:
253  if( ($mtime == 0) ||                           // cache does not exist
254      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
255    ){
256      if(image_download($url,$local)){
257        return $local;
258      }else{
259        return false;
260      }
261  }
262
263  //if cache exists use it else
264  if($mtime) return $local;
265
266  //else return false
267  return false;
268}
269
270/**
271 * Download image files
272 *
273 * @author Andreas Gohr <andi@splitbrain.org>
274 */
275function image_download($url,$file){
276  global $conf;
277  $http = new DokuHTTPClient();
278  $http->max_bodysize = $conf['fetchsize'];
279  $http->timeout = 25; //max. 25 sec
280  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
281
282  $data = $http->get($url);
283  if(!$data) return false;
284
285  $fileexists = @file_exists($file);
286  $fp = @fopen($file,"w");
287  if(!$fp) return false;
288  fwrite($fp,$data);
289  fclose($fp);
290  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
291
292  // check if it is really an image
293  $info = @getimagesize($file);
294  if(!$info){
295    @unlink($file);
296    return false;
297  }
298
299  return true;
300}
301
302/**
303 * resize images using external ImageMagick convert program
304 *
305 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
306 * @author Andreas Gohr <andi@splitbrain.org>
307 */
308function resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
309  global $conf;
310
311  // check if convert is configured
312  if(!$conf['im_convert']) return false;
313
314  // prepare command
315  $cmd  = $conf['im_convert'];
316  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
317  if ($ext == 'jpg' || $ext == 'jpeg') {
318      $cmd .= ' -quality '.$conf['jpg_quality'];
319  }
320  $cmd .= " $from $to";
321
322  @exec($cmd,$out,$retval);
323  if ($retval == 0) return true;
324  return false;
325}
326
327/**
328 * resize images using PHP's libGD support
329 *
330 * @author Andreas Gohr <andi@splitbrain.org>
331 * @author Sebastian Wienecke <s_wienecke@web.de>
332 */
333function resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
334  global $conf;
335
336  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
337
338  // check available memory
339  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
340    return false;
341  }
342
343  // create an image of the given filetype
344  if ($ext == 'jpg' || $ext == 'jpeg'){
345    if(!function_exists("imagecreatefromjpeg")) return false;
346    $image = @imagecreatefromjpeg($from);
347  }elseif($ext == 'png') {
348    if(!function_exists("imagecreatefrompng")) return false;
349    $image = @imagecreatefrompng($from);
350
351  }elseif($ext == 'gif') {
352    if(!function_exists("imagecreatefromgif")) return false;
353    $image = @imagecreatefromgif($from);
354  }
355  if(!$image) return false;
356
357  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
358    $newimg = @imagecreatetruecolor ($to_w, $to_h);
359  }
360  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
361  if(!$newimg){
362    imagedestroy($image);
363    return false;
364  }
365
366  //keep png alpha channel if possible
367  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
368    imagealphablending($newimg, false);
369    imagesavealpha($newimg,true);
370  }
371
372  //keep gif transparent color if possible
373  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
374    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
375      $transcolorindex = @imagecolortransparent($image);
376      if($transcolorindex >= 0 ) { //transparent color exists
377        $transcolor = @imagecolorsforindex($image, $transcolorindex);
378        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
379        @imagefill($newimg, 0, 0, $transcolorindex);
380        @imagecolortransparent($newimg, $transcolorindex);
381      }else{ //filling with white
382        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
383        @imagefill($newimg, 0, 0, $whitecolorindex);
384      }
385    }else{ //filling with white
386      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
387      @imagefill($newimg, 0, 0, $whitecolorindex);
388    }
389  }
390
391  //try resampling first
392  if(function_exists("imagecopyresampled")){
393    if(!@imagecopyresampled($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h)) {
394      imagecopyresized($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h);
395    }
396  }else{
397    imagecopyresized($newimg, $image, 0, 0, 0, 0, $to_w, $to_h, $from_w, $from_h);
398  }
399
400  $okay = false;
401  if ($ext == 'jpg' || $ext == 'jpeg'){
402    if(!function_exists('imagejpeg')){
403      $okay = false;
404    }else{
405      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
406    }
407  }elseif($ext == 'png') {
408    if(!function_exists('imagepng')){
409      $okay = false;
410    }else{
411      $okay =  imagepng($newimg, $to);
412    }
413  }elseif($ext == 'gif') {
414    if(!function_exists('imagegif')){
415      $okay = false;
416    }else{
417      $okay = imagegif($newimg, $to);
418    }
419  }
420
421  // destroy GD image ressources
422  if($image) imagedestroy($image);
423  if($newimg) imagedestroy($newimg);
424
425  return $okay;
426}
427
428/**
429 * Checks if the given amount of memory is available
430 *
431 * If the memory_get_usage() function is not available the
432 * function just assumes $bytes of already allocated memory
433 *
434 * @param  int $mem  Size of memory you want to allocate in bytes
435 * @param  int $used already allocated memory (see above)
436 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
437 * @author Andreas Gohr <andi@splitbrain.org>
438 */
439function is_mem_available($mem,$bytes=1048576){
440  $limit = trim(ini_get('memory_limit'));
441  if(empty($limit)) return true; // no limit set!
442
443  // parse limit to bytes
444  $limit = php_to_byte($limit);
445
446  // get used memory if possible
447  if(function_exists('memory_get_usage')){
448    $used = memory_get_usage();
449  }
450
451  if($used+$mem > $limit){
452    return false;
453  }
454
455  return true;
456}
457
458//Setup VIM: ex: et ts=2 enc=utf-8 :
459?>
460