<?php
class js_proxy {
	var $cache_time;
	
	function js_proxy() {
		$this->cache_time=24*60*60;
	}
	
	function mkdirs($key) {
		if(!is_dir(dirname(__FILE__).'/bin/'.$key[0])) {
			@mkdir(dirname(__FILE__).'/bin/'.$key[0], 0777);
		}
		
		if(!is_dir(dirname(__FILE__).'/bin/'.$key[0].'/'.$key[1])) {
			@mkdir(dirname(__FILE__).'/bin/'.$key[0].'/'.$key[1], 0777);
		}
	}
	
	function get_page($url, $value) {
		$key=md5($value);
		
		$this->mkdirs($key);
		$fn=dirname(__FILE__).'/bin/'.$key[0].'/'.$key[1].'/'.$key.'.js';
		
		clearstatcache();
		
		if(!is_file($fn)) {
			$data=$this->load_page($url, $value);
		} elseif(time()-filemtime($fn)<$this->cache_time) {
			$data=file_get_contents($fn);
		} else {
			$data=$this->load_page($url, $type, $value);
		}
		
		return $data;
	}
	
	function load_page($url, $value) {
		$key=md5($value);
		
		$this->mkdirs($key);
		$fn=dirname(__FILE__).'/bin/'.$key[0].'/'.$key[1].'/'.$key.'.js';
		
		$data=$this->load_url($url);
		
		if(!$data)
			return false;
		
		$fd=fopen($fn, 'w');
		fwrite($fd, $data);
		fclose($fd);
		
		return $data;
	}
	
	function load_url($url) {
		if(function_exists('curl_init'))
		{
			$ch = @curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, FALSE);
			curl_setopt($ch, CURLOPT_TIMEOUT, 600);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			$data=curl_exec($ch);
			curl_close($ch);
			
			return $data;
		} else {
			$parsedUrl = parse_url($url);
			$host = $parsedUrl['host'];
			
			if(isset($parsedUrl['path']))
			{
				$path = $parsedUrl['path'];
			}
			else
			{
				$path = '/';
			}
			
			if(isset($parsedUrl['query']))
			{
				$path .= '?' . $parsedUrl['query'];
			}
			if(isset($parsedUrl['port']))
			{
				$port = $parsedUrl['port'];
			}
			else
			{
				$port = '80';
			}
			
			$timeout = 20;
			$response = '';
			
			$fp = @fsockopen($host, '80', $errno, $errstr, $timeout );
			
			if( $fp )
			{
				fputs($fp, "GET $path HTTP/1.0\r\n" . "Host: $host\r\n" . "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" . "Accept: */*\r\n" . "Accept-Language: en-us,en;q=0.5\r\n" . "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" . "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" . "Referer: http://$host\r\n\r\n");
				
				while ( $line = fread( $fp, 4096 ) )
				{
					$response .= $line;
				}
				
				fclose( $fp );
				
				$pos = strpos($response, "\r\n\r\n");
				
				$response = substr($response, $pos + 4);
			}
			return $response;
		}
		
		return false;
	}
}
?>