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