<?php
/*
 * ARI Framework Lite
 *
 * @package		ARI Framework Lite
 * @version		1.0.0
 * @author		ARI Soft
 * @copyright	Copyright (c) 2009 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

jimport('joomla.filesystem.file');

class AriRemote
{
	var $_curlEnabled;
	var $_allowUrlFopen;
	
	function &getInstance()
	{
		static $instance;
		
		if (is_null($instance))
			$instance = new AriRemote();

		return $instance;
	}
	
	function getRemoteFile($url, $type = 'auto')
	{
		$type = $this->getType($type);
		$content = null;
		switch ($type)
		{
			case 'curl':
				$content = $this->_getCurlRemoteFile($url);
				break;
				
			case 'fopen':
				$content = $this->_getRemoteFile($url);
				break;
				
			case 'socket':
			default:
				$content = $this->_getSocketRemoteFile($url);
		}

		return $content;
	}
	
	function saveRemoteFile($url, $destFolder, $cachePeriod = 0, $type = 'auto')
	{
		$fileName = null;
		$content = $this->getRemoteFile($url, $type);
		if (empty($content))
			return $fileName;

		$needRewrite = true;
		$fileName = $this->generateFileName($url);
		$fullPath = $destFolder . DS . $fileName;
		if ($cachePeriod > 0)
		{
			if (@file_exists($fullPath))
				$needRewrite = (filemtime($fullPath) + $cachePeriod * 60 < time());
		}
		
		if ($needRewrite)
		{
			if (!JFile::write($fullPath, $content))
				$fileName = null;
		}
				
		return $fileName;
	}
	
	function generateFileName($url)
	{
		return md5($url);
	}
	
	function getType($type)
	{
		if ($type != 'auto')
			return $type;
			
		if ($this->isCurlEnabled())
			$type = 'curl';
		else if ($this->allowUrlFopen())
			$type = 'fopen';
		else
			$type = 'socket';
			
		return $type;
	}
	
	function isCurlEnabled()
	{
		if (is_null($this->_curlEnabled))
			$this->_curlEnabled = function_exists('curl_init');
			
		return $this->_curlEnabled;
	}
	
	function allowUrlFopen()
	{
		if (is_null($this->_allowUrlFopen))
			$this->_allowUrlFopen = ini_get('allow_url_fopen');
			
		return $this->_allowUrlFopen;
	}
	
	function _getCurlRemoteFile($url)
	{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
   
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
		
		$cookie_file = JPATH_ROOT . '/tmp/' . uniqid('cookie_', false);
		curl_setopt($ch, CURLOPT_COOKIESESSION, true);
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
		curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);

   		$content = curl_exec($ch);

		curl_close($ch);
		
		if (JFile::exists($cookie_file))
			JFile::delete($cookie_file);

		return $content;
	}
	
	function _getRemoteFile($url)
	{
		return file_get_contents($url);
	}
	
	function _getSocketRemoteFile($url)
	{
		$parsedUrl = parse_url($url);
		$host = $parsedUrl['host'];
		$path = !empty($parsedUrl['path']) ? $parsedUrl['path'] : '/'; 

		if (isset($parsedUrl['query'])) 
		{
			$path .= '?' . $parsedUrl['query'];
		}

		$port = isset($parsedUrl['port']) ? $parsedUrl['port'] : 80;
   		$timeout = 10;
   		$content = null;

		$fp = @fsockopen($host, '80', $errno, $errstr, $timeout );

		if (!$fp) 
			return $content;

		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");

		$content = '';
		while ($line = fread($fp, 4096))
         	$content .= $line;
         	
		fclose($fp);

		// strip the headers
		$pos = strpos($content, "\r\n\r\n");
		if ($pos !== false)
      		$content = substr($content, $pos + 4);
      		
      	return $content;
	}
}