<?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: cookie.engine.php,v 1.0 2011/06/14 20:52:11
//Cookie - Cookie Engine for Oorjit Deal System
//
class Cookie 
{
 
	public $_system_cookie_key;
	public $_system_cookie_expire_minute;

	//Constructor of cookie engine
  	public function __construct () 
	{
		$this->_system_cookie_key			= COOKIE_PREFIX;
		$this->_system_cookie_expire_minute	= COOKIE_TIME;
  	}
    
	//To set cookie
	public function setCookie($curr_key,$curr_value="",$cookie_expire_minute="",$curr_page="/",$encode="yes")  
	{
		
		    
		     $secret = 'password';
	         $algorithm = MCRYPT_RIJNDAEL_256;
	         $mode = MCRYPT_MODE_CBC;
			
		 $cookie_expire_minute = (trim($cookie_expire_minute)=="")?$this->_system_cookie_expire_minute:$cookie_expire_minute;
		 $expires = time()+$cookie_expire_minute;
		 if($encode=="yes")
		 {
        	$encodedValue = $this->encodeSecureCookie($curr_value, $expires, $secret, $algorithm, $mode);		 
			//setcookie($this->_system_cookie_key.$curr_key, $curr_value, time()+$cookie_expire_minute, $curr_page)or die("Error");
		 }else
		 {
			 $encodedValue=$curr_value;
		 }
                 $secure_cookie = FALSE;
                 // Check SSL Enable for all
                  if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) 
                    $request_protocol = $_SERVER['HTTP_X_FORWARDED_PROTO'];
                  else 
                    $request_protocol = !empty($_SERVER['HTTPS']) ? "https" : "http";
                  if ($request_protocol == "https" && (HTTPS_ONLY == 1)) {
					  $secure_cookie = TRUE;
                  }
		setcookie($this->_system_cookie_key.$curr_key, $encodedValue, time()+$cookie_expire_minute, $curr_page,null, $secure_cookie, true)or die("Error");
	}

	//To get cookie
	public function getCookie($curr_key,$decode="yes")   
	{
		if(!isset($_COOKIE[$this->_system_cookie_key.$curr_key]))
			return '';
		     $secret = 'password';
	         $algorithm = MCRYPT_RIJNDAEL_256;   
	         $mode = MCRYPT_MODE_CBC;
			
		 if($decode=="yes")
		 {
		      $decodedValue = $this->decodeSecureCookie($_COOKIE[$this->_system_cookie_key.$curr_key], $secret, $algorithm, $mode);
			
		 }
		 else
		 {
			 $decodedValue= $_COOKIE[$this->_system_cookie_key.$curr_key];
		 }
	
		     return $decodedValue;
	}
  
  	//To unset cookie
	public function unsetCookie($curr_key)  
	{
		unset($_COOKIE[$this->_system_cookie_key.$curr_key]);
	}

	//To set cookie expire
	public function setCookieExpire($cookie_expire_minute="")  
	{
		$cookie_expire_minute = ($cookie_expire_minute=="")?$this->_system_cookie_expire_minute:$cookie_expire_minute;
		$this->_system_cookie_expire_minute	= $session_expire_minute;
	}

	//To distroy cookie
	public function distroyCookie($curr_key,$cookie_expire_minute="")  
	{
                if(!isset($_COOKIE[$this->_system_cookie_key.$curr_key]))
                    return '';
		$cookie_expire_minute = ($cookie_expire_minute=="")?$this->_system_cookie_expire_minute:$cookie_expire_minute;
                $secure_cookie = FALSE;
                // Check SSL Enable for all
                 if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) 
                   $request_protocol = $_SERVER['HTTP_X_FORWARDED_PROTO'];
                 else 
                   $request_protocol = !empty($_SERVER['HTTPS']) ? "https" : "http";
                 if ($request_protocol == "https" && (HTTPS_ONLY == 1)) {
                     $secure_cookie = TRUE;
                 }
		setcookie($this->_system_cookie_key.$curr_key, "", time()-$cookie_expire_minute, "/",null, $secure_cookie, true);
                
	}
	
public function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode ) {
	if($value!=''){
        $key = hash_hmac('sha1', $expires, $secret);
        $iv = md5($expires);
        $secureString = base64_encode($this->encrypt($value, $key, $iv, array(
            'algorithm' => $algorithm,
            'mode' => $mode
        )));
        $verificationString = hash_hmac('sha1', $expires . $value, $key);
        return implode('|', array($expires, $secureString, $verificationString));
	}
	else
	{
		return $value;
	}
    } 
	
	public function decodeSecureCookie($value, $secret, $algorithm, $mode ){
        if ( $value ) {
            $value = explode('|', $value);
            if ( count($value) === 3 && ( (int)$value[0] === 0 || (int)$value[0] > time() ) ) {
                $key = hash_hmac('sha1', $value[0], $secret);
                $iv = md5($value[0]);
                $data = $this->decrypt(base64_decode($value[1]), $key, $iv, array(
                    'algorithm' => $algorithm,
                    'mode' => $mode
                ));
                $verificationString = hash_hmac('sha1', $value[0] . $data, $key);
                if ( $verificationString === $value[2] ) {
                    return $data;
                }
            }
        }
		
        return $value;
    }
	
	
	public static function encrypt( $data, $key, $iv, $settings = array() ) {
        if ( $data === '' || !extension_loaded('mcrypt') ) {
            return $data;
        }
 
        //Merge settings with defaults
        $settings = array_merge(array(
            'algorithm' => MCRYPT_RIJNDAEL_256,
            'mode' => MCRYPT_MODE_CBC
        ), $settings);
 
        //Get module
        $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
 
        //Validate IV
        $ivSize = mcrypt_enc_get_iv_size($module);
        if ( strlen($iv) > $ivSize ) {
            $iv = substr($iv, 0, $ivSize);
        }
 
        //Validate key
        $keySize = mcrypt_enc_get_key_size($module);
        if ( strlen($key) > $keySize ) {
            $key = substr($key, 0, $keySize);
        }
 
        //Encrypt value
        mcrypt_generic_init($module, $key, $iv);
        $res = @mcrypt_generic($module, $data);
        mcrypt_generic_deinit($module);
 
        return $res;
    }
 
    /**
     * Decrypt data
     *
     * This method will decrypt data using a given key, vector, and cipher.
     * By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You
     * may override the default cipher and cipher mode by passing your own desired
     * cipher and cipher mode as the final key-value array argument.
     *
     * @param   string  $data       The encrypted data
     * @param   string  $key        The encryption key
     * @param   string  $iv         The encryption initialization vector
     * @param   array   $settings   Optional key-value array with custom algorithm and mode
     * @return  string 
     */
    public static function decrypt( $data, $key, $iv, $settings = array() ) {
        if ( $data === '' || !extension_loaded('mcrypt') ) {
            return $data;
        }
 
        //Merge settings with defaults
        $settings = array_merge(array(
            'algorithm' => MCRYPT_RIJNDAEL_256,
            'mode' => MCRYPT_MODE_CBC
        ), $settings);
 
        //Get module
        $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
 
        //Validate IV
        $ivSize = mcrypt_enc_get_iv_size($module);
        if ( strlen($iv) > $ivSize ) {
            $iv = substr($iv, 0, $ivSize);
        }
 
        //Validate key
        $keySize = mcrypt_enc_get_key_size($module);
        if ( strlen($key) > $keySize ) {
            $key = substr($key, 0, $keySize);
        }
 
        //Decrypt value
        mcrypt_generic_init($module, $key, $iv);
        $decryptedData = @mdecrypt_generic($module, $data);
        $res = str_replace("\x0", '', $decryptedData);
        mcrypt_generic_deinit($module);
 
        return $res;
    }
  
}