<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VirtuePlanet Framework for Joomla!
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */
defined('_JEXEC') or die;

class VPFrameworkHttp
{
	public $response_code = 0;
	
	public $strict = true;
	
	protected $adapter = null;
	
	protected static $instance = null;
	
	public function __construct()
	{
		jimport('joomla.http.factory');

		if(!class_exists('JHttpFactory'))
		{
			throw new BadFunctionCallException('JHttpFactory not present. Please upgrade your version of Joomla. Exiting optimizer.');
		}

		$options = new JRegistry(array('follow_location' => true));

		$this->adapter = JHttpFactory::getAvailableDriver($options);
	}
	
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new VPFrameworkHttp();
		}
		
		return self::$instance;
	}
	
	public function request($url, $post = null, $headers = null, $userAgent = '')
	{
		if(!$this->adapter)
		{
			throw new BadFunctionCallException('JHttpFactory not present. Please upgrade your version of Joomla. Exiting optimizer.');
		}

		$uri      = JUri::getInstance($url);
		$method   = empty($post) || !is_array($post) ? 'GET' : 'POST';
		$response = $this->adapter->request($method, $uri, $post, $headers, 10, $userAgent);

		return $response;
	}
	
	public function hasAdapter()
	{
		return ($this->adapter !== null);
	}
	
	public function getFileContents($path, $post = null, $headers = null, $userAgent = '', $originalPath = '')
	{
		$contents = '';
		
		if(strpos($path, 'http:') === 0 || strpos($path, 'https:') === 0)
		{
			if($this->adapter === null)
			{
				throw new Exception('No Http Adapters are available.');
			}
			
			$userAgent = !empty($userAgent) ? $userAgent : (!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
			
			try
			{
				$response = $this->request($path, $post, $headers, $userAgent);
			}
			catch(Exception $e)
			{
				throw new Exception($path . ': ' . $e->getMessage());
			}
			
			if(empty($response))
			{
				//TODO: Log error
			}
			
			$this->response_code = $response->code;
			
			if($this->response_code != 200 && $this->strict)
			{
				$path = !empty($originalPath) ? $originalPath : $path;
				
				$contents = $this->markNotFound($path);
			}
			else
			{
				$contents = $response->body;
			}
		}
		else
		{
			if(file_exists($path))
			{
				$contents = @file_get_contents($path);
			}
			elseif($this->adapter !== null)
			{
				$newPath = VPFrameworkUrl::path2Url($path);
				
				// Try again with http adapter over url
				$contents = $this->getFileContents($newPath, $post, $headers, $userAgent, $path);
			}
			else
			{
				$contents = $this->markNotFound($path);
			}
		}
		
		return $contents;
	}
	
	public function isUrlAccessible($url, $json = true)
	{
		$contents = $this->getFileContents($url);
		
		if($this->response_code == 200)
		{
			if($json)
			{
				$data = !empty($contents) && is_string($contents) ? @json_decode($contents, true) : array();

				return !empty($data['success']) ? true : false;
			}

			return true;
		}

		return false;
	}
	
	public function markNotFound($path)
	{
		return '|"VP_COMMENT_START File [' . $path . '] not found VP_COMMENT_END"|;';
	}
}
