<?php

/**
* @version 2.8.17
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

class DT_Session{


    public function asArray($data)
	{
		$array = array();

		if (is_object($data))
		{
			$data = get_object_vars($data);
		}

		foreach ($data as $k => $v)
		{
			if (is_object($v) || is_array($v))
			{
				$array[$k] = self::asArray($v);

				continue;
			}

			$array[$k] = $v;
		}

		return $array;
	}
	
    public static function restore(){

	    //  need changes in set function 

	   $session = JFactory::getSession();

	   if($session->has('DTH','dtregister')){

	     if($session->has('DTH','dtregisterdup')){

			 $DTregisterdup = & $session->get('DTH','null','dtregisterdup');

		 }else{

			  return;

	     }

		 $DTregister = $session->get('DTH','null','dtregister');

		 $DTregister = $DTregisterdup;

	   }else{

		   $session->set('DTH',array(),'dtregister');

		   if($session->has('DTH','dtregisterdup')){

			 $DTregisterdup = & $session->get('DTH','null','dtregisterdup');

		   }else{

			  return;

	       }

		   $DTregister = $session->get('DTH','null','dtregister');

		   $DTregister = $DTregisterdup;

	   }

   } 
   
   
   
   public static function set($path, $value, $separator = ".")
	{
		
			
	
		
		$session = JFactory::getSession();
		$data = $session->get('DTH',array(),'dtregister');

		
		$nodes = array_values(array_filter(explode($separator, $path), 'strlen'));

		if (!$nodes)
		{
			return null;
		}

		// Initialize the current node to be the registry root.
		$node = &$data;

		// Traverse the registry to find the correct node for the result.
		for ($i = 0, $n = count($nodes) - 1; $i < $n; $i++)
		{
			
			if (is_object($node))
			{
				$node = (array) $node ;
				if (!isset($node[$nodes[$i]]) && ($i != $n))
				{
					$node[$nodes[$i]] = array(); // new \stdClass;
				}

				// Pass the child as pointer in case it is an object
				$node = &$node[$nodes[$i]];

				continue;
			}

			if (is_array($node))
			{
				if (!isset($node[$nodes[$i]]) && ($i != $n))
				{
					$node[$nodes[$i]] = array(); // new \stdClass;
				}

				// Pass the child as pointer in case it is an array
				$node = &$node[$nodes[$i]];
			}
		}

		// Get the old value if exists so we can return it
		switch (true)
		{
			case (is_object($node)):
				$result = $node->{$nodes[$i]} = $value;
				break;

			case (is_array($node)):
				$result = $node[$nodes[$i]] = $value;
				break;

			default:
				$result = null;
				break;
		}
         $data = $session->set('DTH',$data,'dtregister');
		return $result;
	}
   
   public static function set_old($path='',$value=null){

      $session = JFactory::getSession();

      if($session->has('DTH','dtregister')){

	     $DTregister = $session->get('DTH',null,'dtregister');	

	  }else{

		 $session->set('DTH',null,'dtregister');

		 $DTregister = $session->get('DTH',null,'dtregister');

	  }
	  
       $path = "DTH.".$path;
	 
	  //debug_print_backtrace();
	  $path_array = array();
	   $numeric_key =  false;
	   $paths  = array();
	   $numeric_keys = array();
	   if ($nodes = explode('.', $path)){
		   
	      foreach($nodes as $node){
		     if(is_numeric($node) ){
				
				$numeric_key = true;
			    $paths[] = implode(".",$path_array);
				$numeric_keys[] = $node;
				$path_array = array();
			 }else{
				 $path_array[] = $node;
				 
			 }
		  }
		 // if($numeric_key ==  false){
		     $paths[] = implode(".",$path_array);
		 // }
		}
		 $path_first = $paths[0];
		
		$str_eval = "";
		$return =  $value;
		if(count($paths) > 1){
			$return = $session->get($path_first,null,'dtregister');
			
			$node = &$return;
			$j = 0;
			 $str_eval = "";
		   foreach($paths as $index => $path_in){
		      if($index == 0){ continue; }
			 
			  $str_eval = "[".$numeric_keys[$j]."]";
			  $node = &$return[$numeric_keys[$j]];
			  if ($nodes = explode('.', $path_in))
			  {
				  
				  for ($i = 0, $n = count($nodes); $i < $n; $i++)
				  {
					 
					  if(isset($nodes[$i]) && $nodes[$i] != "" ){
						 if(is_object($node)){
						     $str_eval .=  "->".$nodes[$i];
							 $node = &$node->$nodes[$i];
						 }elseif(is_array($node)){
						    $str_eval .= "['".$nodes[$i]."']";
							$node = &$node[$nodes[$i]];
						 }
					   //$str_eval .=  "->".$nodes[$i];
					   
					  }   
					
				  }

			  }
			  $j++;
			  
		   }
		  
		}
			
		 $eval = "\$return$str_eval = \$value;"; 		
		 eval($eval);

	   echo $path." >> ".$value." >> $eval <br />";
	$return = $session->set($path_first,$return,'dtregister');
	  
	  return $return;
	  
   }
   
   	public static function get($path)
	{
		$session = JFactory::getSession();
		 $data = $session->get('DTH',array(),'dtregister');
		// echo "<pre>";
		// print_r($data);
		if (!strpos($path, "."))
		{
			//die;
		//	return (isset($data[$path]) && $data[$path] !== null && $data[$path] !== '') ? $data[$path] : array();
		}

		// Explode the registry path into an array
		$nodes = explode(".", trim($path));

		// Initialize the current node to be the registry root.
		$node = $data;
		$found = false;

		// Traverse the registry to find the correct node for the result.
		foreach ($nodes as $n)
		{
			if (is_array($node) && isset($node[$n]))
			{
				$node = $node[$n];
				$found = true;

				continue;
			}

			if (!isset($node->$n))
			{
				return false;
			}

			$node = $node->$n;
			$found = true;
		}

		if (!$found || $node === null || $node === '')
		{
			return $default;
		}
		if($path == 'register'){
			echo "<pre>";
            print_R($node);
           // die;
		}
		return $node;
	}

   
   public static function get_old($path=""){
	 
      $session = JFactory::getSession();
	  
       $path = "DTH.".$path;
	   $path_array = array();
	   $numeric_key = false;
	   $paths  = array();
	   $numeric_keys = array();
	   if ($nodes = explode('.', $path)){
	      foreach($nodes as $node){
		     if(is_numeric($node)){
				
				$numeric_key = true;
			    $paths[] = implode(".",$path_array);
				$numeric_keys[] = $node;
				$path_array = array();
			 }else{
				 $path_array[] = $node;
				 
			 }
		  }
		  //if($numeric_key ==  false){
		     $paths[] = implode(".",$path_array);
		 //}
		}
		$path = $paths[0];
	    $return = $session->get($path,null,'dtregister');
		
		if(count($paths) > 1 && $return != ""){
			
			$j = 0;
		   foreach($paths as $index => $path){
		      if($index == 0){ continue; }
			  if(!isset($return[$numeric_keys[$j]])){
			     $return = false;
				 break;
			  }
			  $return = $return[$numeric_keys[$j]];
			  
			  if ($nodes = explode('.', $path))
			  {
				  // Initialize the current node to be the registry root.
				  $node = $return;
	  
				  // Traverse the registry to find the correct node for the result.
				  for ($i = 0, $n = count($nodes)-1; $i < $n; $i++)
				  {
					  if (!isset($node->$nodes[$i]) && ($i != $n))
					  {
						  $node->$nodes[$i] = false;
						  break;
					  }
					  $node = $node->$nodes[$i];
				  }
				  if($node != "" && isset($node->$nodes[$i])){
				       
						  
						   $return = $node->$nodes[$i];
				  }else{
				      $return = false;
					  break;
				  }
					  
				  // Get the old value if exists so we can return it
				 
			  }
			  $j++;
			  
		   }
		}
		 // print_R($session->getData());
		 // pr(get_class_methods($return));
		$array = json_decode(json_encode($return),true);
		
		//die("jfjhgjh");
		return ($array==null)?false:$array;
	    
		return $return;
	  
  }

   public static function clear($path){
       DT_Session::set($path,null);
	   return ;
	   $session = JFactory::getSession();
	   $path = "DTH.".$path;
      $session->clear($path,'dtregister');
	  return;
	   $DTregister = $session->get('DTH','null','dtregister');

	   $namespace = "__default";

	   if($path!=""){

		   $pathElements = explode(".", $path);

		   $pathdata = $DTregister;

		   $str = "\$_SESSION['__dtregister']['DTH']";

		  // $str = "";

		   if($pathdata == "" || $pathdata == "null") return; 

		   foreach($pathElements as $key=>$e){

			    if(!isset($pathdata[$e])){

					 //$eval = "unset(\$DTregister$str);";

		             //eval($eval);

				   	return;

			    }

				if($pathdata[$e] === ""){ prd('good');

				    return;	

				}

				 $pathdata = $pathdata[$e];	

				 $str .="['".$e."']";

		   }

		  // unset(${'DTregister'.$str});

		   $eval = "unset(\$DTregister$str);";

		   $eval = "unset($str);";

		   eval($eval);

	   }else{

		  //pr('session cleared');

		  //$session->clear('DTH','dtregisterdup');

	   }

  }

   public static function clearAll(){

	  //echo "<pre>";

	  //debug_print_backtrace();

	  //prd('clear');

	  $session = JFactory::getSession();

	  $session->clear('DTH','dtregister');

	  if(isset($_SESSION['__default']['__dtregister'])){

	  		 unset($_SESSION['__default']['__dtregister']);

	  }

  }

  public static function restoreFromPayment($paypal_session_id = 0){
	 
	 $database = JFactory::getDBO();

	    $sql = "select * from #__dtregister_session where id=$paypal_session_id";

        $database->setQuery($sql);

        $database->query();

       // echo $database->getQuery();

		$row = $database->loadObjectList();

        $data_old = unserialize($row[0]->data);

        $dt_userId = $row[0]->user_id;
        $options = array('id' =>$row[0]->session_id );
		// $options
		$session = JFactory::getSession();

		//$_SESSION = $data_old;
       // $_SESSION['joomla'] = base64_encode(serialize($data_old['joomla']));
		//$session->destroy();
		//$session->getToken(true); 
        //$session->restart();
		//$session->getToken(true); 
		$data = $session->getData();
		
		
		$old_session = unserialize(base64_decode($data_old['joomla']));
		
		$old_session_vars = $old_session->toObject();
		
		foreach($data_old as $key=>$value){
		   if($key == "joomla"){ continue;}
		   $_SESSION[$key] == $value;
		}
		
		foreach($old_session_vars as $namescpace => $vars){
		   $namescpace = substr($namescpace,2);// str_replace("__","",$namescpace);
		   
		   //prd($namescpace);
		   foreach($vars as $key => $value){
			   
			   if($key == 'registry' || $key == "session"){
			      continue;
			   }
			  
		      $session->set($key,$value,$namescpace);      
		   }
		   
		}
		$data = $session->getData();
		
		//$migratableKeys = array("user", "session.token", "session.counter", "session.timer.start", "session.timer.last", "session.timer.now");
		
		//$session->fork();

		/*$session->set('session.timer.start',strtotime('now'));

		$session->set('session.counter',1);

		$session->set('session.timer.last',(strtotime('now')));

		$session->set('session.timer.now',(strtotime('now')));  */

		//$session->set('__dtregister',$data['__dtregister']);

		//$_SESSION['__dtregister'] = $data['__dtregister'];

		$process = DT_Session::get('Setting.process');

		DT_Session::set($process.'.restore.userId',$dt_userId);

		DT_Session::set($process.'.restore.processed',$row[0]->processed);

		DT_Session::set($process.'.restore.id',$paypal_session_id);
		
		self::update_session($paypal_session_id);
		
		 /* $sql = "select * from #__dtregister_session where id=$paypal_session_id";

        $database->setQuery($sql);

        $database->query();

       // echo $database->getQuery();

		$row = $database->loadObjectList();

        $data = unserialize($row[0]->data);*/

  }
  
  public static function update_session($id){
	    $database = JFactory::getDBO();
	    $session = JFactory::getSession();
		$data    = $session->getData();

		// Before storing it, let's serialize and encode the JRegistry object
		$_SESSION['joomla'] = base64_encode(serialize($data));
        $data = $_SESSION;
	   
	    $sql = "update #__dtregister_session set `data`= ".$database->Quote(serialize($data))."  where id=".$id;
	    $database->setQuery($sql);
	    $database->query();
	   
	}

}

?>