<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

class emp_license{

	const SUCCESS = 0;
	const ERROR_NO_FILE = 1;
	const ERROR_NO_DOWNLOADID = 2;
	const ERROR_NO_SIGNATURE = 3;
	const ERROR_INVALID_SIGNATURE = 4;
	const ERROR_LICENSE_INVALID = 5;
	const ERROR_LICENSE_EXPIRED = 6;
	const ERROR_DOMAIN_NOT_MATCH = 7;
	const ERROR_CONNECTION_FAILED = 8;
	const ERROR_LICENSE_INVALID_REQUEST = 9;

	public static function checkLicense(){

		return self::SUCCESS;

		$license = array();
		$licensePath = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_vmeepro'.DS.'license';

		//check that license file exists
		if(!file_exists($licensePath)){
			return self::ERROR_NO_FILE;
		}

		//get the download ID
		$downloadId = emp_helper::getGlobalParam('download_id');
		if(empty($downloadId)){
			return self::ERROR_NO_DOWNLOADID;
		}

		$license = unserialize(file_get_contents($licensePath));

		//chekc that the file is signed
		if(!isset($license['signature']) || empty($license['signature'])){
			return self::ERROR_NO_SIGNATURE;
		}

		//check the signature
		$signature = $license['signature'];
		unset($license['signature']);
		$licenseStr = $downloadId . serialize($license) . md5($downloadId);
		for ($i = 0; $i < 365; $i++){
			$licenseStr = md5($licenseStr);
		}

		if(base64_encode($licenseStr) != $signature){
			return self::ERROR_INVALID_SIGNATURE;
		}

		//check base URI
		$baseUri = JURI::base() /* 'http://www.svsound.com/' */;
		//Paypal notify.php set the JPATH_BASE to the full path to virtuemart before initializing Joomla. 
		//This influences the JURI class and fuck up all functions. 
		emp_logger::log('License check - uri:', emp_logger::LEVEL_INFO,$baseUri);
		if(!empty($baseUri)){
			self::fixBaseUri($baseUri);
			if(!isset($license['base_uri']) || $license['base_uri'] != $baseUri){
			//check the new uri_list field
				if(!isset($license['uri_list']) || !in_array($baseUri, $license['uri_list'])){
				 	return self::ERROR_DOMAIN_NOT_MATCH;
				}
			}
		}

		//check license status
		if(!isset($license['status']) || $license['status'] != 'valid'){
			return self::ERROR_LICENSE_INVALID;
		}

		//check license expiration
		$current = time();
		if(!isset($license['expired']) || $license['expired'] < $current){
			return self::ERROR_LICENSE_EXPIRED;
		}

		return self::SUCCESS;
	}

	public static function getLicenseFromServer(){
		//get the download ID
		$downloadId = emp_helper::getGlobalParam('download_id');
		if(empty($downloadId)){
			return self::ERROR_NO_DOWNLOADID;
		}

		$baseUri = JURI::base() /* 'http://www.svsound.com/' */;
		self::fixBaseUri($baseUri);
		$req = 'http://www.interamind.com/index.php?option=com_vmeeproservice&task=getLicense';
		$params = sprintf("&downloadid=%s&baseuri=%s",urlencode($downloadId), urlencode($baseUri));
		$req .= $params;
		$reqRes = self::doReq($req);
		if(!isset($reqRes) || empty($reqRes)){
			return self::ERROR_CONNECTION_FAILED;
		}
		elseif($reqRes == 'failed'){
			return self::ERROR_LICENSE_INVALID_REQUEST;
		}

		$licensePath = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_vmeepro'.DS.'license';
		file_put_contents($licensePath, $reqRes);
		return self::SUCCESS;
	}

	private static function doReq($request){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$request);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
		curl_setopt($ch, CURLOPT_NOBODY, false);
		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result= curl_exec ($ch);
		curl_close ($ch);
		return $result;
	}

	private static function fixBaseUri(&$baseUri){
		$matches = array();
		preg_match('/(https?:\/\/.*?\/).*/',$baseUri,$matches);
		$baseUri = str_ireplace('www.', '', $matches[1]);
		$baseUri = str_ireplace('ww.', '', $baseUri);
		$baseUri = str_ireplace('https://', 'http://', $baseUri);
// 		$adminPart = 'administrator/';
// 		$pos = strpos($baseUri, $adminPart);
// 		if($pos !== false){
// 			$baseUri = substr($baseUri, 0, strlen($baseUri) - strlen($adminPart));
// 		}
	}
}
