<?php
/**
 * Http 工具类
 * 提供一系列的Http方法
 */
class http {
	static public function remotehttp($url){
		if (function_exists('curl_init')) {
			return self::curl_http($url);
		} elseif (function_exists('allow_url_fopen')){
			if (function_exists('fsockopen')) {
				return self::fsockopen_http($url, array('timeout'=>10,'block'=>false));
			} else {
				return file_get_contents($url);
			}
		} else {
			return ;
		}
	}
	
	static public function curl_http($url){
		$ch=curl_init();
		$opt=array();
		$opt[CURLOPT_URL]=$url;
		$opt[CURLOPT_HEADER]=false;
		$opt[CURLOPT_CONNECTTIMEOUT]=5;
		$opt[CURLOPT_TIMEOUT]=300;
		$opt[CURLOPT_AUTOREFERER]=true;
		$opt[CURLOPT_USERAGENT]='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; CIBA; .NET CLR 2.0.50727)';
		$opt[CURLOPT_RETURNTRANSFER]=true;
		//$opt[CURLOPT_FOLLOWLOCATION]=true;
		//$opt[CURLOPT_MAXREDIRS]=10;
		curl_setopt_array($ch,$opt);
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}
	
	

    /**
     * 采集远程文件
     * @access public
     * @param string $remote 远程文件名
     * @param string $local 本地保存文件名
     * @return mixed
     */
    static public function curlDownload($remote,$local) {
    	if (is_array($remote) && is_array($local)) {
    		$return = array();
    		$cp = curl_multi_init();
    		$opt = array();
    		foreach ($remote as $i => $url) {// 初始化 
    			if (!isset($local[$i])) {
    				continue;
    			}
    			$fp[$i] = fopen($local[$i],"wb");
				$opt[$i] = curl_init($url);
				curl_setopt($opt[$i], CURLOPT_TIMEOUT, 15);
				curl_setopt($opt[$i], CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
				curl_setopt($opt[$i], CURLOPT_HEADER ,0);
				//curl_setopt($opt[$i], CURLOPT_CONNECTTIMEOUT,15);
				curl_setopt($opt[$i], CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($opt[$i], CURLOPT_FILE, $fp[$i]);
				curl_multi_add_handle ($cp, $opt[$i]);
			}
			
			do{
				$mrc = curl_multi_exec($cp,$active);
			} while ($mrc == CURLM_CALL_MULTI_PERFORM);
			while ($active and $mrc == CURLM_OK) {//当无数据时或请求暂停时，active=true
				if (curl_multi_select($cp) != -1) {
					do {
						$mrc = curl_multi_exec($cp, $active);
					} while ($mrc == CURLM_CALL_MULTI_PERFORM);
				}
			} 
			
			foreach ($remote as $i => $url) {//结束清理
				if(!curl_errno($opt[$i])){  
					//$data[$k]=curl_multi_getcontent($opt[$i]);//数据转换为array  
					$statusCode = curl_getinfo($opt[$i],CURLINFO_HTTP_CODE);//返回http头信息  
					if ($statusCode==200) {
			        	$return[$i] = true;
			        } else {
			        	unlink($local[$i]);
			        	$return[$i] = false;
			        }
				}else{  
					unset($i,$url);  
				}
				curl_close($opt[$i]);
				curl_multi_remove_handle($cp,$opt[$i]);
				fclose($fp[$i]);
			}
			curl_multi_close($cp);
			return $return;
		
    	} elseif (is_string($remote) && is_string($local)){
	        $cp = curl_init($remote);
	        $fp = fopen($local,"wb");
	        curl_setopt($cp, CURLOPT_FILE, $fp);
	        curl_setopt($cp, CURLOPT_HEADER, 0);
	        curl_exec($cp);
	        fclose($fp);
	        $statusCode = curl_getinfo($cp, CURLINFO_HTTP_CODE);
	        curl_close($cp);
	        if ($statusCode==200) {
	        	return true;
	        } else {
	        	unlink($local);
	        	return false;
	        }	        
    	}
    }

   /**
    * 使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件
    * 如果主机或服务器没有开启 CURL 扩展可考虑使用
    * fsockopen 比 CURL 稍慢,但性能稳定
    * @static
    * @access public
    * @param string $url 远程URL
    * @param array $conf 其他配置信息
    *        int   limit 分段读取字符个数
    *        string post  post的内容,字符串或数组,key=value&形式
    *        string cookie 携带cookie访问,该参数是cookie内容
    *        string ip    如果该参数传入,$url将不被使用,ip访问优先
    *        int    timeout 采集超时时间
    *        bool   block 是否阻塞访问,默认为true
    * @return mixed
    */
    static public function fsockopen_http($url, $conf = array()) {
        $return = '';
        if(!is_array($conf)) return $return;

        $matches = parse_url($url);
        !isset($matches['host']) 	&& $matches['host'] 	= '';
        !isset($matches['path']) 	&& $matches['path'] 	= '';
        !isset($matches['query']) 	&& $matches['query'] 	= '';
        !isset($matches['port']) 	&& $matches['port'] 	= '';
        $host = $matches['host'];
        $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
        $port = !empty($matches['port']) ? $matches['port'] : 80;

        $conf_arr = array(
            'limit'		=>	0,
            'post'		=>	'',
            'cookie'	=>	'',
            'ip'		=>	'',
            'timeout'	=>	15,
            'block'		=>	TRUE,
            );

        foreach (array_merge($conf_arr, $conf) as $k=>$v) ${$k} = $v;

        if($post) {
            if(is_array($post))
            {
                $post = http_build_query($post);
            }
            $out  = "POST $path HTTP/1.0\r\n";
            $out .= "Accept: */*\r\n";
            //$out .= "Referer: $boardurl\r\n";
            $out .= "Accept-Language: zh-cn\r\n";
            $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
            $out .= "Host: $host\r\n";
            $out .= 'Content-Length: '.strlen($post)."\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Cache-Control: no-cache\r\n";
            $out .= "Cookie: $cookie\r\n\r\n";
            $out .= $post;
        } else {
            $out  = "GET $path HTTP/1.0\r\n";
            $out .= "Accept: */*\r\n";
            //$out .= "Referer: $boardurl\r\n";
            $out .= "Accept-Language: zh-cn\r\n";
            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Cookie: $cookie\r\n\r\n";
        }
        $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
        if(!$fp) {
            return '';
        } else {
            stream_set_blocking($fp, $block);
            stream_set_timeout($fp, $timeout);
            @fwrite($fp, $out);
            $status = stream_get_meta_data($fp);
            if(!$status['timed_out']) {
                while (!feof($fp)) {
                    if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
                        break;
                    }
                }

                $stop = false;
                while(!feof($fp) && !$stop) {
                    $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
                    $return .= $data;
                    if($limit) {
                        $limit -= strlen($data);
                        $stop = $limit <= 0;
                    }
                }
            }
            @fclose($fp);
            return $return;
        }
    }

    /**
     * 下载文件
     * 可以指定下载显示的文件名，并自动发送相应的Header信息
     * 如果指定了content参数，则下载该参数的内容
     * @static
     * @access public
     * @param string $filename 下载文件名
     * @param string $showname 下载显示的文件名
     * @param string $content  下载的内容
     * @param integer $expire  下载内容浏览器缓存时间
     * @return void
     */
    static public function download ($filename, $showname='',$content='',$expire=180) {
        if(is_file($filename)) {
            $length = filesize($filename);
        }elseif(is_file(UPLOAD_PATH.$filename)) {
            $filename = UPLOAD_PATH.$filename;
            $length = filesize($filename);
        }elseif($content != '') {
            $length = strlen($content);
        }else {
            throw_exception($filename.L('下载文件不存在！'));
        }
        if(empty($showname)) {
            $showname = $filename;
        }
        $showname = basename($showname);
		if(!empty($filename)) {
	        $type = mime_content_type($filename);
		}else{
			$type	 =	 "application/octet-stream";
		}
        //发送Http Header信息 开始下载
        header("Pragma: public");
        header("Cache-control: max-age=".$expire);
        //header('Cache-Control: no-store, no-cache, must-revalidate');
        header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
        header("Content-Disposition: attachment; filename=".$showname);
        header("Content-Length: ".$length);
        header("Content-type: ".$type);
        header('Content-Encoding: none');
        header("Content-Transfer-Encoding: binary" );
        if($content == '' ) {
            readfile($filename);
        }else {
        	echo($content);
        }
        exit();
    }


}//类定义结束

if(!function_exists('image_type_to_extension')){
   function image_type_to_extension($imagetype) {
       if(empty($imagetype)) return false;
       switch($imagetype) {
           case IMAGETYPE_GIF    	: return '.gif';
           case IMAGETYPE_JPEG		: return '.jpg';
           case IMAGETYPE_PNG    	: return '.png';
           case IMAGETYPE_SWF    	: return '.swf';
           case IMAGETYPE_PSD    	: return '.psd';
           case IMAGETYPE_BMP    	: return '.bmp';
           case IMAGETYPE_TIFF_II 	: return '.tiff';
           case IMAGETYPE_TIFF_MM 	: return '.tiff';
           case IMAGETYPE_JPC    	: return '.jpc';
           case IMAGETYPE_JP2    	: return '.jp2';
           case IMAGETYPE_JPX    	: return '.jpf';
           case IMAGETYPE_JB2    	: return '.jb2';
           case IMAGETYPE_SWC    	: return '.swc';
           case IMAGETYPE_IFF    	: return '.aiff';
           case IMAGETYPE_WBMP    	: return '.wbmp';
           case IMAGETYPE_XBM    	: return '.xbm';
           default                	: return false;
       }
   }

}