<?php
/***************************************************************************
*                                                                          *
* Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
*                                                                          *
* This  is  commercial  software,  only  users  who have purchased a valid *
* license  and  accept  to the terms of the  License Agreement can install *
* and use this program.                                                    *
*                                                                          *
****************************************************************************
* PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
* "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
****************************************************************************/

//
//$Id: tool.engine.php,v 1.0 2011/06/14 20:52:11
//Tool - Tool Engine for Oorjit Deal System
//

class Tool 
{
	private static $_options;

	//Constructor for Tool class
	public function __construct ($options=null) 
	{
		$this->init($options);
	}

	//To initialize objects
	public function init($options) 
	{
		$this->setOptions($options);
	}

	//To set options
	private function setOptions($options)  
	{
		return $this->_options =	$options;
	}

	//To encode url string  
	public function encodeUrlString($urlString)  
	{
		$urlString    			= strtolower($urlString);	
		$convertionFormatArray  = array('/' => '--fwdslash--','#' => '--hash--','.' => '--dot--','+' => '--plus--');
		$urlString 			    = strtr($urlString,$convertionFormatArray);
		$urlString  		    = urlencode($urlString);
		return $urlString;
	}


	//To decode url string
	public function decodeUrlString($urlString)  
	{
		$urlString  			= urldecode($urlString);
		$convertionFormatArray  = array('--fwdslash--' => '/','--hash--' => '#','--dot--'=> '.','--plus--' => '+');
		$urlString 				= strtr($urlString,$convertionFormatArray);
		$urlString    			= strtolower($urlString);
		return $urlString;
	}

	//To encode string
	function encodeString($text,$key=__ENCRYPTION_KEY)
	{
		$key="STRING".$key;
		$key = substr(md5($key),0,8);
		$encrypted_data = '';
		$td = @mcrypt_module_open('tripledes', '', 'ecb', '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		//echo "<br/>";
		if (mcrypt_generic_init($td, $key, $iv) != -1) {

			// attempt to sanitize encryption for use as a form element name
			$encrypted_data = @mcrypt_generic($td, $text);
			$encrypted_data = base64_encode($encrypted_data);
			$encrypted_data = 'i' . strtr($encrypted_data, '+/=', '-~.');

		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		}
		return $encrypted_data;
	}

	//To encode url using base64
	private function urlBase64Encode($str) {
		
		return strtr(base64_encode($str),
		array('+' => '.','=' => '-','/' => '~','[' => ':',']' => '@'));
	}

	//To decode url using base64
	private function urlBase64Decode($str) {

		return base64_decode(strtr($str,array('.' => '+','-' => '=','~' => '/',':' => ']','@' => ']')));
	}    

	//To decode string

	function decodeString($text,$key=__ENCRYPTION_KEY)
	{
		$key="STRING".$key;
		$key = substr(md5($key),0,8);
		$decrypted_data = '';
		$td = mcrypt_module_open('tripledes', '', 'ecb', '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		if (mcrypt_generic_init($td, $key, $iv) != -1) {

			 // reverse form element name sanitization and decrypt
		  $text = substr($text, 1);
		  $text = strtr($text, '-~.', '+/=');
		  $text = base64_decode($text);
		  $decrypted_data = @mdecrypt_generic($td, $text);

		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		}
		return $decrypted_data;
	}


	//To check Is file exist
	public function isFileExist($fileSource)  
	{
		$fileSource  	= ltrim($fileSource,"/");
		if(file_exists(__CORE_PUBLIC_UPLOADS_PATH."/".$fileSource))	{
			return true;
		} else {
			return false;
		}
	}

	//To check is uploaded
	public function isUploaded($fileSource,$defaultFile="")  
	{
	   
		if(file_exists(__CORE_PUBLIC_UPLOADS_PATH."/".ltrim(trim($fileSource),"/")))	{ 
			return $fileSource;
		} else {
			return $defaultFile;
		}
	}

	//function for converting to sql compactable date
	public function convertDateForSQL($date,$assignedDateformat)
	{
		if($assignedDateformat=='%m/%d/%Y' && $date){
			$dateArray=@explode('/',$date);
			$date=$dateArray[1].'-'.$dateArray[0].'-'.$dateArray[2];
		}
		if(!$date) $returnvalue="";
		else{
			if($assignedDateformat=='%Y-%m-%d')
			   $returnvalue= $date;
			else{ 
			   $dateVal=strtotime($date);
			   if(strpos($date,':')>0) $returnvalue=date("Y-m-d H:i:s",$dateVal);
			   else $returnvalue=date("Y-m-d",$dateVal);
			}   
		  
	   }
	   return $returnvalue;    
	}

	//set or get date when passing to url or retrieving from url for escaping from '/' in date format
	public function urlDate($date,$mode,$assignedDateformat)//mode can be 'set' or 'get'
	{
		if($mode=='set'){
		if(strpos($date,'/'))$date=str_replace('/','-',$date);
		if(strpos($date,' '))$date=str_replace(' ','_',$date);
		if(strpos($date,':'))$date=str_replace(':','-',$date);
		return $date;
		}elseif($mode=='get'){
		$dateTimeArray = explode('_',$date);
		$dateTimeArray[0]	= isset($dateTimeArray[0]) ? $dateTimeArray[0]  : '';
		$dateTimeArray[1]	= isset($dateTimeArray[1]) ? $dateTimeArray[1]  : '';
		$date	=	$dateTimeArray[0];
		if(strpos($assignedDateformat,'/'))$date=str_replace('-','/',$dateTimeArray[0]);
		if(strpos($dateTimeArray[1],'-'))$getTime=str_replace('-',':',$dateTimeArray[1]);
		$get = (empty($getTime)) ? $date :$date.' '.$getTime;
		return $get;
		}
	}
	//To decode HTML special characters
	public function decodeSplChar($str)  
	{
                if($str!="" && !is_array($str)){
                    return(htmlspecialchars_decode($str));
                }
	}
	//To encode HTML special characters
	public function encodeSplChar($str)
	{
		return(htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8'));  
	}

	//To generate Combination Hash

	//$str='61_2_5';
	//usage : makeHAsh($str);
	function makeHAsh($Str='')
	{
		$hashArray = explode('_',$Str);
		natsort($hashArray);
		$key = implode('_', $hashArray);
		$hash = sprintf('%u', crc32($key));
		return $hash;
	}
	
	//to hash the password
	function generateHash($password)
	{
		if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
		$salt = '$2y$07$' . substr(md5(uniqid(mt_rand(), true)), 0, 22);
		return crypt($password, $salt);
		}
	}
	//Advanced Method to Retrieve Client IP Address
	//Ref : https://gist.github.com/cballou/2201933#file-get-ip-address-optimized-php
	public function getIpAddress() 
	{
		$ipKeys = array
				(
					'HTTP_CLIENT_IP',
					'HTTP_X_FORWARDED_FOR',
					'HTTP_X_FORWARDED',
					'HTTP_X_CLUSTER_CLIENT_IP',
					'HTTP_FORWARDED_FOR',
					'HTTP_FORWARDED',
					'REMOTE_ADDR'
				);
		foreach ($ipKeys as $key) 
		{
			if (array_key_exists($key, $_SERVER) === true) 
			{
				foreach (explode(',', $_SERVER[$key]) as $ip) 
				{
					// trim for safety measures
					$ip = trim($ip);
					// attempt to validate IP
					if($this->validateIp($ip)) 
					{
						return $ip;
					}
				}
			}
		} 
		return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
	}
 
	/**
	 * Ensures an ip address is both a valid IP and does not fall within
	 * a private network range.
	 */
	private function validateIp($ip)
	{
		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) 
		{
			return false;
		}
		return true;
	}
	
	/* To encode data in xml file */
	public function encryptDecrypt($action, $string)
	{
		$output = false;
		$encrypt_method = "AES-256-CBC";
		$secret_key = 'awft5KtJ3LFqVQR6cI9CyZIi9s1R7OwE';
		$secret_iv = 'g1k6LXf5woeEUY5e';
		// hash
		$key = hash('sha256', $secret_key);
		// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
		$iv = substr(hash('sha256', $secret_iv), 0, 16);
		if($action == 'encrypt')
		{
			$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
			$output = base64_encode($output);
		}
		else if($action == 'decrypt')
		{   
                        
			$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
		}		
		return $output;
	}
	
}
