<?php 
/*
已经测试可代理的图片应用
img.ly - 
Flickr&flic.kr - http://farm[0-9].static.flickr.com
Picasa - http://lh[0-9].ggpht.com/_BpxLF02Z-r0/S1kQ8c9lgLI/AAAAAAAAAFA/Qn0NudfxYPE/The%20Cloud%20Player.jpg
PhotoBucket - http://i1001.photobucket.com/albums/af131/bolo1988/res01_attpic_brief.jpg
Tinypic&twitgoo.com
twimg.com
*/


$allow_referer = array("imbolo.com,img.imbolo.com");
//允许使用本代理程序的域名

define('IS_PROTECT',true);
//是否需要设置防盗链 ture表示防盗链，false表示不需要防盗链

define('ERROR_IMG','http://img.imbolo.com/wrong.gif');
//盗链时显示的图片

$allow_image = false;
$i = 0;
if( IS_PROTECT ){
	while( $allow_referer[$i] ){
			if( substr_count($_SERVER['HTTP_REFERER'], $allow_referer[$i] ) > 0 ) $allow_image = true;
			if( $allow_image) break;
			$i ++ ;
	}
}else{
	$allow_image = true ;
}
 
if( $allow_image = false ){
	header("Content-type: image/gif");
	header("location: ".NOPIC_IMG);
}
//判断是否盗链

if (isset($_GET['host'])) {
	$host = $_GET['host'];
	//获取图片所在服务器
	if (preg_match('/farm[0-9]/',$host)) {
		$imgsrc = 'http://'.$host.'.static.flickr.com/'.$_GET['img'];
	} elseif (preg_match('/lh[0-9]/',$host)) {
		$imgsrc = 'http://'.$host.'.ggpht.com/'.$_GET['img'];
	} elseif (preg_match('/i[0-9]{4}/',$host)) {
		$imgsrc = 'http://'.$host.'.photobucket.com/'.$_GET['img'];
	}
	$imgsrc = urldecode( htmlspecialchars( $imgsrc ) );
} else {
	$imgsrc = urldecode( htmlspecialchars(  $_GET['img']  ) );
	//获取图片地址，变量名为img
}

if( substr_count( strtolower($imgsrc), 'jpg') > 0 ){
	$append = "jpg";
}else if( substr_count( strtolower($imgsrc), 'gif') > 0 ){
	$append = "gif";
}else{
	$append = "png";
}
//判断图片格式

$cache_image = md5( $imgsrc ).".".$append  ;
//图片缓存文件名

$cache_folder = "cache/sip/";
//图片缓存文件夹

$cache_file = $cache_folder . $cache_image ;
//图片缓存位置

if( file_exists($cache_file) && filesize($cache_file) > 10 ){
	header("Content-type: image/".$append );
	//声明文件类型
	readfile($cache_file);
	//如果发现缓存存在，则调用缓存
}else{
//	$thumb = file_get_contents($imgsrc, false, $context);
	$ch = curl_init();
	$timeout = 5;
	curl_setopt ($ch, CURLOPT_URL, $imgsrc);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.2) Gecko/20100115 Firefox/3.6 GTBDFff GTB7.0');
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$thumb = curl_exec($ch);
	curl_close($ch);
	header("Content-type: image/".$append );
	//声明文件类型
	echo $thumb;
	$fp = @fopen( $cache_file , "w+" );
		//写入缓存
		if( flock($fp ,LOCK_EX ) ){
			ftruncate($fp, 0) ;
			fwrite($fp , $thumb );
			@flock($fp, LOCK_UN);
		}
		fclose($fp);
}

?>
