Current File : //root/panel/restoreclient.php
<?php
if($argc!==3)
{
	echo "could you please pass the parameters correctly.";
	exit();
}
require('/etc/sentora/panel/cnf/db.php');
include('/etc/sentora/panel/dryden/db/driver.class.php');
include('/etc/sentora/panel/dryden/debug/logger.class.php');
include('/etc/sentora/panel/dryden/runtime/dataobject.class.php');
include('/etc/sentora/panel/dryden/runtime/hook.class.php');
include('/etc/sentora/panel/dryden/sys/versions.class.php');
include('/etc/sentora/panel/dryden/ctrl/options.class.php');
include('/etc/sentora/panel/dryden/fs/director.class.php');
include('/etc/sentora/panel/dryden/fs/filehandler.class.php');
include('/etc/sentora/panel/inc/dbc.inc.php');
try {
    $zdbh = new db_driver("mysql:host=" . $host . ";dbname=" . $dbname . "", $user, $pass);
} catch (PDOException $e) {
    exit();
}

$username=trim($argv[2]);
$download=1;

$SERVICE_EXEC=trim(shell_exec("whereis service | awk '{print $2}'"));
shell_exec("$SERVICE_EXEC crond stop");

				$rows = $zdbh->prepare("
				SELECT * FROM x_accounts 
				LEFT JOIN x_profiles ON (x_accounts.ac_id_pk=x_profiles.ud_user_fk) 
				LEFT JOIN x_groups   ON (x_accounts.ac_group_fk=x_groups.ug_id_pk) 
				LEFT JOIN x_packages ON (x_accounts.ac_package_fk=x_packages.pk_id_pk) 
				LEFT JOIN x_quotas   ON (x_accounts.ac_package_fk=x_quotas.qt_package_fk) 
				WHERE x_accounts.ac_user_vc= :ac_user_vc
				");
				$rows->bindParam(':ac_user_vc', $username);
				$rows->execute();
				if ($rows->fetchColumn() != 0) {
					$rows = $zdbh->prepare("
					SELECT * FROM x_accounts 
					LEFT JOIN x_profiles ON (x_accounts.ac_id_pk=x_profiles.ud_user_fk) 
					LEFT JOIN x_groups   ON (x_accounts.ac_group_fk=x_groups.ug_id_pk) 
					LEFT JOIN x_packages ON (x_accounts.ac_package_fk=x_packages.pk_id_pk) 
					LEFT JOIN x_quotas   ON (x_accounts.ac_package_fk=x_quotas.qt_package_fk) 
					WHERE x_accounts.ac_user_vc= :ac_user_vc AND x_accounts.ac_deleted_ts IS NULL
					");
					$rows->bindParam(':ac_user_vc', $username);
					$rows->execute();
					$dbvals = $rows->fetch();
					$userid=$dbvals['ac_id_pk'];
					$filename=$argv[1];
					if ($backup = ExecuteRestore($userid, $dbvals['ac_user_vc'], $download,$filename)) {
					echo $filename." - successfully restore";	
					} else {
					echo "<h2>Unauthorized Access!</h2>";
					echo "You have no permission to view this module.";
					}		
				}
				else
				{
				echo "Username does not exists.";
				exit();	
				}
				
function ExecuteRestore($userid, $username, $download = 0,$getfilename) 
{
	global $controller;
	include('/etc/sentora/panel/cnf/db.php');
	$vhost_path = ctrl_options::GetSystemOption('hosted_dir');
	// Database Connectivity
	$inserted_domain_name=array();
	try {
	$zdbh = new db_driver("mysql:host=" . $host . ";dbname=" . $dbname . "", $user, $pass);
	} catch (PDOException $e) {
	exit();
	}
	$mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
	$z_db_user = $user;
	$z_db_pass = $pass;
	try {
	$mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
	} catch (PDOException $e) {
	echo $e;
	}
	// Needed Directory Path 
	$filename=$getfilename;
	$homedir = ctrl_options::GetSystemOption('hosted_dir') . $username;
	$backupdir = $homedir . "/backups/";
	$filepath=$backupdir . $filename;
	$foldername=substr($getfilename,0,-7);
	$jsonfilepath=$backupdir.$foldername."/userdata/cache.json";
	$jsonfilepath=$backupdir.$foldername."/userdata/";
	$mainfilepath=$backupdir.$foldername."/userdata/main";
	$mailforwarderpath=$backupdir.$foldername."/va/";
	//echo $f=str_replace(".tar.gz","",$getfilename);
	
	if (file_exists($backupdir . $filename)){
			// if file Exists
			//tar -xvzf community_images.tar.gz
			// Step 1 untar the File 
			/* ///////////////////////////// untar file working code start //////////////////////////////// */
			//$exec_cmd="chmod -R 0777 /var/sentora/hostdata/zadmin/backups/";
			//$exec_cmd="chmod -R 0777 /var/sentora/hostdata/".$username."/backups/";
			$exec_cmd="chmod -R 0777 ".$vhost_path.$username."/backups/";
			
			$reasult=exec($exec_cmd);
			$exec_cmd="cd ".$backupdir . " && tar -xvzf ".$filename;
			$reasult=exec($exec_cmd);
			$cpanelhomepath = trim(file_get_contents($backupdir.$foldername."/homedir_paths"));
			/* ///////////////////////////// untar file working code end //////////////////////////////// */

				
		
			 /* ///////////////////////////// Cron tab Working Start ///////////////////////////////////// */
			 if(file_exists($backupdir.$foldername."/homedir_paths"))
			 {

				$c_file = fopen($backupdir.$foldername."/homedir_paths","r");
				$c_i=0;
				$c_filename="";
				$path=fgets($c_file);
				$c_array=explode("/",$path);
				$c_filename=trim($c_array[count($c_array)-1]);
				fclose($c_file);
				if(file_exists($backupdir.$foldername."/cron/".$c_filename))
				{
				 echo "cron restore starting .. \n ";	
				$c1_file = fopen($backupdir.$foldername."/cron/".$c_filename,"r");
				$iter=0;
				while(! feof($c1_file))
				{
				$get_value=fgets($c1_file);
					
					if(trim($get_value)!="")
	                {

                        $csplit_array=explode(" ",trim($get_value));
                         if(count($csplit_array)<7)
                         continue;
                         $ct_timing_vc=$csplit_array[0]." ".$csplit_array[1]." ".$csplit_array[2]." ".$csplit_array[3]." ".$csplit_array[4];
                         $ct_script_vc=trim(shell_exec("whereis ".$csplit_array[5]." | awk '{print $2}'"));
                         $cronfilepath=trim($csplit_array[6]);
                         unset($csplit_array[0]);
                         unset($csplit_array[1]);
                         unset($csplit_array[2]);
                         unset($csplit_array[3]);
                         unset($csplit_array[4]);
                         unset($csplit_array[5]);
                         unset($csplit_array[6]);
                         $desc="";
                         $array_count=count($csplit_array);

                         if($array_count!=0)
                         {
                                $desc=implode(" ",$csplit_array);
                                $desc=trim(str_replace(">>","", $desc));
                		$fsplit1=explode("/public_html/",$desc);
				//$desc="/var/sentora/hostdata/".$username."/public_html/".$fsplit1[1]; 
				$desc=$vhost_path.$username."/public_html/".$fsplit1[1]; 
                         }


                     	if (strpos($cronfilepath,"http://")!==false || strpos($cronfilepath,"https://")!==false)
			{
				$final_get_Path=$cronfilepath;
			}
			else
			{
				$fsplit=explode("/public_html/",$cronfilepath);
				// $final_get_Path="/var/sentora/hostdata/zadmin/public_html/".$fsplit[1];
				//$final_get_Path="/var/sentora/hostdata/".$username."/public_html/".$fsplit[1];
				$final_get_Path=$vhost_path.$username."/public_html/".$fsplit[1];
			}


                    $sql = $zdbh->prepare("INSERT INTO x_cronjobs (ct_acc_fk, ct_script_vc, ct_description_tx, ct_timing_vc, ct_fullpath_vc, ct_created_ts) VALUES (:userid, :script, :desc, :timing, :fullpath, " . time() . ")");
					$sql->bindParam(':userid',$userid);
					$sql->bindParam(':script', $ct_script_vc);
					$sql->bindParam(':desc', $desc);
					$sql->bindParam(':timing', $ct_timing_vc);
					$full_path = $final_get_Path;
					$sql->bindParam(':fullpath', $full_path);
					$sql->execute();
					if($array_count!=0)
  					$updateline = $ct_timing_vc . ' ' .$ct_script_vc.' '.$full_path.' >> '.$desc;
  					else 
					$updateline = $ct_timing_vc . ' ' .$ct_script_vc.' '.$full_path;
					$cmd='echo "'.$updateline.'" >> /var/spool/cron/apache';
					shell_exec($cmd);

    	            }
				}
				fclose($c1_file);
				 echo "cron restored successfully.. \n ";
				}
			 }
			 /* ///////////////////////////// Cron tab Working End ///////////////////////////////////// */
			 
			/* ///////////////////////////// mysql database working code start ////////////////////////////////  */
			if(file_exists($backupdir.$foldername."/mysql/"))
			{
				echo "MySQL DB restore starting .. \n ";
			$files1 = scandir($backupdir.$foldername."/mysql/");
			foreach($files1 as $key => $value)
			{
				if(substr($value,-7)==".create")
				{
				 $db_name=substr($value,0,-7);	
				 $dbsql=" CREATE DATABASE IF NOT EXISTS ".$db_name;
				 $sql = $zdbh->prepare($dbsql);
				 $sql->execute();
				 $bkcommand = "mysql -h " . $host . " -u " . $user . " -p" . $pass . " ".$db_name." < " . $backupdir.$foldername."/mysql/".$db_name.".sql";
				 $r=passthru($bkcommand); 
			
			// Bug Fixing code start //
						$sql_db = "SELECT COUNT(*) FROM x_mysql_databases WHERE my_name_vc='".$db_name."' And my_deleted_ts IS NULL And my_acc_fk='".$userid."'";
						if ($numrows_db = $zdbh->query($sql_db)) {
						if ($numrows_db ->fetchColumn() == 0) {
						$sql = $zdbh->prepare("INSERT INTO x_mysql_databases (
							my_acc_fk,
							my_name_vc,
							my_created_ts) VALUES (
							:userid,
							:name,
							:time)");
						$time = time();
						$name =$db_name;
						$sql->bindParam(':userid',$userid);
						$sql->bindParam(':time', $time);
						$sql->bindParam(':name', $name);
						$sql->execute();
						}
					}			
				}	
				
			}
			echo "MySQL DB restored successfully.. \n ";
			}
			/*  ///////////////////////////// mysql database working code end //////////////////////////////// */
		    /*  ///////////////////////////// mysql users working code start //////////////////////////////// */
		
			
			if( file_exists($backupdir.$foldername."/mysql.sql") )
			{
			/////////////////////////////////////////////// Update Mysql Table start ////////////////////////////////////////////////
			echo "mysql user restore starting .. \n ";
			 $bkcommand = "mysql -h " . $host . " -u " . $user . " -p" . $pass . " mysql < " . $backupdir.$foldername."/mysql.sql";
             $r=passthru($bkcommand);
			 
			 echo "mysql user restored successfully.. \n ";
			 
			 /////////////////////////////////////////////// Update Mysql Table start ////////////////////////////////////////////////
				$fp=fopen($backupdir.$foldername."/mysql.sql","r");
				$usernamelist=array();
				$dblist=array();
				static $DB_User_Name="";
				static $DB_DB_Name="";
				// static $DB_count=0;

				while(!feof($fp))
				{
				$line=fgets($fp);
					if(preg_match("/^GRANT USAGE ON/",$line))
					{
						$line1=str_replace("GRANT USAGE ON *.* TO","",$line);
						$split_line=explode("@",$line1);
						// $usernamelist[]=str_replace("'","",$split_line[0]);
						$DB_User_Name=trim(str_replace("'","",$split_line[0]));
						
					}
					if(preg_match("/^GRANT ALL PRIVILEGES ON/",$line))
					{
					$line2=explode(" ",trim(str_replace("GRANT ALL PRIVILEGES ON","",$line)));	
					if(stripslashes(str_replace("`","",str_replace("`.*","",$line2[0])))==$DB_DB_Name)
					continue;
					$DB_DB_Name=trim(stripslashes(str_replace("`","",str_replace("`.*","",$line2[0]))));
					
					
						$numrows = $zdbh->prepare("SELECT * FROM x_mysql_users WHERE mu_name_vc=:mu_name_vc AND mu_deleted_ts IS NULL");
						$numrows->bindParam(':mu_name_vc',$DB_User_Name );
						$numrows->execute();
						if ($numrows->fetchColumn() == 0) {

						$numrows_db = $zdbh->prepare("SELECT * FROM x_mysql_databases WHERE my_name_vc=:database AND my_acc_fk=:userid And my_deleted_ts IS NULL");
						$numrows_db->bindParam(':database', $DB_DB_Name );
						$numrows_db->bindParam(':userid', $userid);
						$numrows_db->execute();
						$result_db = $numrows_db->fetch();
						$database_db=$result_db['my_id_pk'];

						$sql1 = $zdbh->prepare("INSERT INTO x_mysql_users (
						mu_acc_fk,
						mu_name_vc,
						mu_database_fk,
						mu_pass_vc,
						mu_access_vc,
						mu_created_ts) VALUES (
						:userid,
						:username,
						:database,
						:password,
						:access,
						:time)");
						$sql1->bindParam(':userid', $userid);
						$sql1->bindParam(':username', $DB_User_Name);
						$sql1->bindParam(':database', $database_db);
						$user_password="******";
						$sql1->bindParam(':password', $user_password);
						$access="%";
						$sql1->bindParam(':access', $access);
						$time = time();
						$sql1->bindParam(':time', $time);
						$sql1->execute();

						$numrows_db = $zdbh->prepare("SELECT * FROM x_mysql_users WHERE mu_name_vc=:database AND mu_acc_fk=:userid And mu_deleted_ts IS NULL");
						$numrows_db->bindParam(':database', $DB_User_Name);
						$numrows_db->bindParam(':userid', $userid);
						$numrows_db->execute();
						$result_db = $numrows_db->fetch();
						$myuserid=$result_db['mu_id_pk'];


						$sql2 = $zdbh->prepare("
						INSERT INTO x_mysql_dbmap (
						mm_acc_fk,
						mm_user_fk,
						mm_database_fk) VALUES (
						:uid,
						:myuserid,
						:dbid
						)");
						$sql2->bindParam(':uid', $userid);
						$sql2->bindParam(':myuserid', $myuserid);
						$sql2->bindParam(':dbid', $database_db);
						$sql2->execute();

						}else
						{
							
						$numrows_db = $zdbh->prepare("SELECT * FROM x_mysql_databases WHERE my_name_vc=:database AND my_acc_fk=:userid And my_deleted_ts IS NULL");
						$numrows_db->bindParam(':database', $DB_DB_Name );
						$numrows_db->bindParam(':userid', $userid);
						$numrows_db->execute();
						$result_db = $numrows_db->fetch();
						$database_db=$result_db['my_id_pk'];
						
						$numrows_db = $zdbh->prepare("SELECT * FROM x_mysql_users WHERE mu_name_vc=:database AND mu_acc_fk=:userid And mu_deleted_ts IS NULL");
						$numrows_db->bindParam(':database', $DB_User_Name);
						$numrows_db->bindParam(':userid', $userid);
						$numrows_db->execute();
						$result_db = $numrows_db->fetch();
						$myuserid=$result_db['mu_id_pk'];

				

						$sql2 = $zdbh->prepare("
						INSERT INTO x_mysql_dbmap (
						mm_acc_fk,
						mm_user_fk,
						mm_database_fk) VALUES (
						:uid,
						:myuserid,
						:dbid
						)");
						$sql2->bindParam(':uid', $userid);
						$sql2->bindParam(':myuserid', $myuserid);
						$sql2->bindParam(':dbid', $database_db);
						$sql2->execute();	
							
					}

					
					}
				
				
				}
			
				
				
				
				fclose($fp);
				
				$del= $zdbh->prepare("DELETE a
									FROM x_mysql_dbmap as a, x_mysql_dbmap as b
									WHERE (a.mm_acc_fk  = b.mm_acc_fk )
									AND (a.mm_user_fk  = b.mm_user_fk )
									AND (a.mm_database_fk  = b.mm_database_fk )
									AND a.mm_id_pk < b.mm_id_pk");
			
						$del->execute();
			} 
			 /* ///////////////////////////// mysql users working code end //////////////////////////////// */
			/* ///////////////////////////// Upload all files into our domain start ///////////////////////////  */
			$deshomedir = ctrl_options::GetSystemOption('hosted_dir') . $username."/public_html/";
			
			echo "Backup Files restore starting .. \n ";
			
			$srchomedir=$backupdir.$foldername."/homedir/public_html/{,.}*";
		
			$execcopy="mv -f ".$srchomedir." ".$deshomedir." ";
			
			$r=passthru($execcopy); 
			
			$cmd_own=" chown -R apache:apache ".$deshomedir." ";
			passthru($cmd_own);
			
			echo "Backup Files restored successfully.. \n ";
			 ///////////////////////////// Upload all files into our domain End /////////////////////////// */
			/* ///////////////////////////// Main Domain Upload and insert a DB start /////////////////////////// */
			$Domain_file = fopen($mainfilepath,"r");
			$in_array_check=array();
			while(! feof($Domain_file))
			{
				  static $flag="";
				  $doamin="";
				  $rootdirectorypath="";
				  $addon_file_path="";
				  $line=fgets($Domain_file);

					if(trim($line)!="---" && trim($line)!="" )
					{
						if(strpos($line,"_domains:"))
						{
							$split_line=explode("_",$line);
							$flag=$split_line[0];
							continue;
						}
						if(strpos($line,"main_domain:")!==false)
						{
						$maindomain_split=explode(":",$line);
							$flag="main";
							$maindomain=$maindomain_split[count($maindomain_split)-1];
						}
						if(trim($flag)=="main" )
						{
						// main and addon 
							$domain_split=explode(":",$line);
							$domain=trim($domain_split[count($domain_split)-1]);
						}else if(trim($flag)=="addon")
						{
							$domain_split=explode(":",$line);
							$domain=trim($domain_split[0]);
							$in_array_check[]=trim($domain_split[count($domain_split)-1]);
							$addon_file_path=trim($domain_split[count($domain_split)-1]);
						}else
						{
							// parked ans sub 
							$domain_split=explode("-",$line);
							$domain=trim($domain_split[count($domain_split)-1]);
						}
						
						 if($flag=="sub" && in_array($domain,$in_array_check))
						{
						//	continue;
						} 

							 if(trim($flag)=="addon")
						{
						
							
							if(file_exists($backupdir.$foldername."/userdata/".$addon_file_path))
							{
							$Inner_Domain_file = fopen($backupdir.$foldername."/userdata/".$addon_file_path,"r");
							while(! feof($Inner_Domain_file))
							{
							$filepathline=fgets($Inner_Domain_file);
							if(strpos($filepathline,"documentroot:")!==false)
							{
							$split_root=explode(":",$filepathline);
							$rootdirectorypath=trim($split_root[count($split_root)-1]);
							break;	
							}
							}
							fclose($Inner_Domain_file);
							}	
							
							
						}
						else
						{
							if(file_exists($backupdir.$foldername."/userdata/".$domain))
							{
							$Inner_Domain_file = fopen($backupdir.$foldername."/userdata/".$domain,"r");
							while(! feof($Inner_Domain_file))
							{
							$filepathline=fgets($Inner_Domain_file);
							if(strpos($filepathline,"documentroot:")!==false)
							{
							$split_root=explode(":",$filepathline);
							$rootdirectorypath=trim($split_root[count($split_root)-1]);
							break;	
							}
							}
							fclose($Inner_Domain_file);
							}	
						}
						//echo $domain."---->".$flag."---->".$rootdirectorypath."<br/>";
						
						/* ////////////////////////// Domain Data Insert Start /////////////////// */
						
							echo "Domain restore starting .. \n ";
							$maindomainname="";				
							$domain_name=$domain;
							$domain_type=$flag;
							$destination="";
							
							$h_file = fopen($backupdir.$foldername."/homedir_paths","r");
							$h_filename="";
							$h_path=trim(fgets($h_file));								
							fclose($h_file);
							//set destination and move the list of files into public_html/
							$rtrimpath=str_replace($h_path,"",$rootdirectorypath);

							if(strpos($rtrimpath,"public_html"))
							{
							$destination=str_replace("/public_html","",$rtrimpath);
							if($destination=="")
							{
							$destination="/public_html";
								
							}

							}else
							{
								// not moved the the folder str_replace public_html destination 
								// $destination=str_replace("public_html","",$rtrimpath);
								
								$pb_dir=ctrl_options::GetSystemOption('hosted_dir') . $username."/public_html/";
								$t=explode("/",$rtrimpath);
								$dir_name=$t[1];
								if(!file_exists($pb_dir.$dir_name."/"))
								{
									$cmdmk=	" cd ".$pb_dir." && mkdir ".$dir_name;
									passthru($cmdmk);
								}
							//move the folder and update the DB
							
							
								$srchomedir=$backupdir.$foldername."/homedir".$rtrimpath."/{,.}*";
								$deshomedir = ctrl_options::GetSystemOption('hosted_dir') . $username."/public_html/".$dir_name."/";
								$execcopy="mv -f ".$srchomedir." ".$deshomedir." ";
							
								$r=passthru($execcopy); 
								$cmd_own=" chown -R apache:apache ".$deshomedir." ";
								passthru($cmd_own);
								$destination=str_replace("/public_html","",$rtrimpath);						
								$destination="/public_html/".ltrim($destination,"/");
		
							}
							 if($flag=="parked")
							{
							$destination="";
							}
							
							// echo "detination:".$destination."<br/>";

							$domaintypeselect = array( 
							"main" => "1",
							"addon" => "1",				
							"sub" => "2", 
							"parked" => "3" ); 
							$vh_type=$domaintypeselect[$domain_type];
							$vh_active_in=0;
							array_push($inserted_domain_name,$domain_name);
							$sql = "SELECT COUNT(*) FROM x_vhosts WHERE vh_name_vc='".$domain_name."' And vh_deleted_ts IS NULL";
							if ($numrows = $zdbh->query($sql)) {
							if ($numrows->fetchColumn() <> 0) {
							// Update the domain path only 
							$sql = $zdbh->prepare("update x_vhosts set vh_directory_vc=:destination,vh_active_in=:vh_active_in,vh_type_in=:vh_type
								where vh_name_vc=:domain");
								
							$sql->bindParam(':destination', $destination);
							$sql->bindParam(':vh_active_in', $vh_active_in);
							$sql->bindParam(':vh_type', $vh_type);
							$sql->bindParam(':domain', $domain_name);
							$sql->execute();

							//echo ""
							$gsql=$zdbh->prepare("select vh_id_pk from x_vhosts where vh_name_vc=:domainName AND vh_acc_fk=:userid AND vh_deleted_ts is NULL");

							$gsql->bindParam(':domainName', $domain_name);
							$gsql->bindParam(':userid', $userid);
							$gsql->execute();
							$res=$gsql->fetch();
							$domainID=$res['vh_id_pk'];
							//	echo "DomainId:".$domainID."<br/>";
							$records_list = ctrl_options::GetSystemOption('dns_hasupdates');
							$record_array = explode(',', $records_list);
							if (!in_array($domainID, $record_array)) {
							if (empty($records_list)) {
							$records_list .= $domainID;
							} else {
							$records_list .= ',' . $domainID;
							}
							$sql = "UPDATE x_settings SET so_value_tx=:newlist WHERE so_name_vc='dns_hasupdates'";
							$sql = $zdbh->prepare($sql);
							$sql->bindParam(':newlist', $records_list);
							$sql->execute();
							}
							$sql = $zdbh->prepare("UPDATE x_settings
							SET so_value_tx='true'
							WHERE so_name_vc='apache_changed'");
							$sql->execute();

							}else
							{
							// Add the Domain path in vhost and 
							$sql = $zdbh->prepare("INSERT INTO x_vhosts (vh_acc_fk,
								vh_name_vc,
								vh_directory_vc,
								vh_type_in,vh_active_in,
								vh_created_ts) VALUES (
								:userid,
								:domain,
								:destination,
								:vh_type,
								:vh_active_in,
								:time)");      //  CLEANER FUNCTION ON $domain and $homedirectory_to_use (Think I got it?)
							$time = time();
							$sql->bindParam(':time', $time);
							$sql->bindParam(':userid', $userid);
							$sql->bindParam(':vh_type', $vh_type);
							$sql->bindParam(':domain', $domain_name);
							$sql->bindParam(':vh_active_in', $vh_active_in);
							$sql->bindParam(':destination', $destination);
							$sql->execute();
							$domainName=$domain_name;
																						$mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
																						include('cnf/db.php');
																						$z_db_user = $user;
																						$z_db_pass = $pass;
																						try {
																						$mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
																						} catch (PDOException $e) {
																						echo $e;
																						}
																						$numrows_do = $mail_db->prepare("SELECT domain FROM domain WHERE domain=:domain");
																						$numrows_do->bindParam(':domain', $domainName);
																						$numrows_do->execute();
																						$result_do = $numrows_do->fetch();
																						if (!$result_do) {
																						$sql_do = $mail_db->prepare("INSERT INTO domain (  domain,
																						description,
																						aliases,
																						mailboxes,
																						maxquota,
																						quota,
																						transport,
																						backupmx,
																						created,
																						modified,
																						active) VALUES (
																						:domain,
																						'',
																						0,
																						0,
																						0,
																						0,
																						'',
																						0,
																						NOW(),
																						NOW(),
																						'1')");
																						$sql_do->bindParam(':domain', $domainName);
																						$sql_do->execute();
																						}
							//	$currentuser = ctrl_users::GetUserDetail();		
							if (!fs_director::CheckForEmptyValue(ctrl_options::GetSystemOption('server_ip'))) {
							$targetIP = ctrl_options::GetSystemOption('server_ip');
							} else {
							$targetIP = $_SERVER["SERVER_ADDR"]; //This needs checking on windows 7 we may need to use LOCAL_ADDR :- Sam Mottley
							}
							$gsql=$zdbh->prepare("select vh_id_pk from x_vhosts where vh_name_vc=:domainName AND vh_acc_fk=:userid AND vh_deleted_ts is NULL");
							$gsql->bindParam(':userid', $userid);
							$gsql->bindParam(':domainName', $domainName);
							$gsql->execute();
							$res=$gsql->fetch();
							$domainID=$res['vh_id_pk'];
						if($vh_type=="1" || $vh_type=="3" )
						{
							$qsql=$zdbh->prepare("select * from x_dns_create");
							$qsql->execute();
							while($get_dns=$qsql->fetch()){

							$dc_target_vc=str_replace(':IP:',$targetIP,$get_dns['dc_target_vc']);
							$dc_target_vc=str_replace(':DOMAIN:', $domainName, $dc_target_vc);
							if($get_dns['dc_priority_in']==NULL || $get_dns['dc_priority_in']==''){
							$get_dns['dc_priority_in']=0;
							}
							if($get_dns['dc_weight_in']==NULL || $get_dns['dc_weight_in']==''){
							$get_dns['dc_weight_in']=0;
							}
							if($get_dns['dc_port_in']==NULL || $get_dns['dc_port_in']==''){
							$get_dns['dc_port_in']=0;
							}
							$sql = $zdbh->prepare("INSERT INTO x_dns (dn_acc_fk,
							dn_name_vc,
							dn_vhost_fk,
							dn_type_vc,
							dn_host_vc,
							dn_ttl_in,
							dn_target_vc,
							dn_priority_in,
							dn_weight_in,
							dn_port_in,
							dn_created_ts) VALUES (
							:userid,
							:domainName,
							:domainID,
							:type_new,
							:hostName_new,
							:ttl_new,
							:target_new,
							:priority_new,
							:weight_new,
							:port_new,
							:time)"
							);
							$sql->bindParam(':userid', $userid);
							$sql->bindParam(':domainName', $domainName);
							$sql->bindParam(':domainID', $domainID);
							$sql->bindParam(':type_new', $get_dns['dc_type_vc']);
							$sql->bindParam(':hostName_new', $get_dns['dc_host_vc']);
							$sql->bindParam(':ttl_new', $get_dns['dc_ttl_in']);
							$sql->bindParam(':target_new', $dc_target_vc);
							$sql->bindParam(':priority_new', $get_dns['dc_priority_in']);
							$sql->bindParam(':weight_new', $get_dns['dc_weight_in']);
							$sql->bindParam(':port_new', $get_dns['dc_port_in']);
							$time = time();
							$sql->bindParam(':time', $time);
							$sql->execute();
							unset($sql);
							}
						}else if($vh_type=="2")
						{
							//subdomain entry will need to add hear 
							/*  ////////////////////////////////////////// Subdomain code started hear /////////////////////////////////////////////// */
								if (!fs_director::CheckForEmptyValue(ctrl_options::GetSystemOption('server_ip'))) 
								{
									$targetIP = ctrl_options::GetSystemOption('server_ip');
								} 
								else 
								{
									$targetIP = $_SERVER["SERVER_ADDR"];
								}
								 $user_id=$userid;
								 $split_domain=explode(".",$domainName);
								 $subDomainName=$split_domain[0];
								 unset($split_domain[0]);
								 $maindomain=implode(".",$split_domain);
								
								$gsql=$zdbh->prepare("select vh_id_pk from x_vhosts where vh_name_vc=:domainName AND vh_acc_fk=:userid AND vh_deleted_ts is NULL");
								$gsql->bindParam(':userid', $user_id);
								$gsql->bindParam(':domainName', $maindomain);
								$gsql->execute();
								$res=$gsql->fetch();
								$domainID=$res['vh_id_pk'];		
								$dsql=$zdbh->prepare("select count(*) as rcd_cnt from x_dns where dn_acc_fk=:userid AND dn_name_vc=:domainName AND dn_vhost_fk=:domainID AND dn_type_vc='A' AND dn_host_vc=:subDomain AND dn_target_vc=:target_new AND dn_deleted_ts is NULL");		
								$dsql->bindParam(':userid', $user_id);
								$dsql->bindParam(':domainName', $maindomain);
								$dsql->bindParam(':domainID', $domainID);
								$dsql->bindParam(':subDomain', $subDomainName);
								$dsql->bindParam(':target_new', $targetIP);
								$dsql->execute();
								$dres=$dsql->fetch();
								if($dres['rcd_cnt']==0){
								$sql = $zdbh->prepare("INSERT INTO x_dns (dn_acc_fk,
								dn_name_vc,
								dn_vhost_fk,
								dn_type_vc,
								dn_host_vc,
								dn_ttl_in,
								dn_target_vc,
								dn_priority_in,
								dn_weight_in,
								dn_port_in,
								dn_created_ts) VALUES (
								:userid,
								:domainName,
								:domainID,
								'A',
								:hostName_new,
								'86400',
								:target_new,
								'0',
								'0',
								'0',
								:time)"
								);
								$sql->bindParam(':userid', $user_id);

								$sql->bindParam(':domainName', $maindomain);
								$sql->bindParam(':domainID', $domainID);
								$sql->bindParam(':hostName_new', $subDomainName);
								$sql->bindParam(':target_new', $targetIP);
								$time = time();
								$sql->bindParam(':time', $time);
								$sql->execute();
								unset($sql);
								}
							/* /////////////////////////////////////////   Subdomain code End hear ///////////////////////////////////////////////////   */
						}
							//	echo "DomainId:".$domainID."<br/>";
							$records_list = ctrl_options::GetSystemOption('dns_hasupdates');
							$record_array = explode(',', $records_list);
							if (!in_array($domainID, $record_array)) {
							if (empty($records_list)) {
							$records_list .= $domainID;
							} else {
							$records_list .= ',' . $domainID;
							}
							$sql = "UPDATE x_settings SET so_value_tx=:newlist WHERE so_name_vc='dns_hasupdates'";
							$sql = $zdbh->prepare($sql);
							$sql->bindParam(':newlist', $records_list);
							$sql->execute();
							}
							$sql = $zdbh->prepare("UPDATE x_settings
							SET so_value_tx='true'
							WHERE so_name_vc='apache_changed'");
							$sql->execute();
							}
							}
							  


							echo "Domain restored successfully.. \n ";
						
						/* ////////////////////////// Domain Data Insert End /////////////////// */
						/* ////////////////////////////////// Mail Functionality Starting //////////////////////// */

										if(file_exists($backupdir.$foldername."/homedir/mail/".$domain."/"))
										{
										echo $domain." - Email restore starting .. \n "; 
										$deshomedir = "/var/sentora/vmail/";
										$srchomedir=$backupdir.$foldername."/homedir/mail/".$domain."/";
										$execcopy="cp -Ru ".$srchomedir." ".$deshomedir." ";
										$r=passthru($execcopy); 
										$change_permisssion="chmod -R 774 "."/var/sentora/vmail/".$domain."/";
										$r1=passthru($change_permisssion);

										$path = "/var/sentora/vmail/".$domain."/";

										$getarray = array();

										// directory handle
										$dir = dir($path);

										while (false !== ($entry = $dir->read())) {
										if ($entry != '.' && $entry != '..') {
										if (is_dir($path . '/' .$entry)) {
										$getarray[] = $entry; 
										}
										}
										}

										foreach($getarray as $key => $value)
										{
										//$getfname=explode(":",$value);
										$maindomainname=$domain;
										$fname=trim($value);
										$fulladdress = strtolower(str_replace(' ', '', $fname . "@" . $maindomainname));
										$address=$fname;
										$location=strtolower(str_replace(' ', '', $maindomainname . "/" . $fname."/"));
										$sql = "SELECT COUNT(*) FROM x_mailboxes WHERE mb_address_vc='".$fulladdress."' And mb_deleted_ts IS NULL";
										if ($numrows = $zdbh->query($sql)) {
										if ($numrows->fetchColumn() == 0) {
										$sql = "INSERT INTO x_mailboxes (mb_acc_fk,
										mb_address_vc,
										mb_created_ts,mb_quota) VALUES (
										:userid,
										:fulladdress,
										:time,'2000')";
										$time = time();
										$sql = $zdbh->prepare($sql);
										$sql->bindParam(':time', $time);
										$sql->bindParam(':userid', $userid);
										$sql->bindParam(':fulladdress', $fulladdress);
										$sql->execute();

										$numrows = $mail_db->prepare("SELECT domain FROM domain WHERE domain=:domain");
										$numrows->bindParam(':domain', $maindomainname);
										$numrows->execute();
										$result = $numrows->fetch();
										if (!$result) {
										$sql = $mail_db->prepare("INSERT INTO domain (  domain,
										description,
										aliases,
										mailboxes,
										maxquota,
										quota,
										transport,
										backupmx,
										created,
										modified,
										active) VALUES (
										:domain,
										'',
										0,
										0,
										0,
										0,
										'',
										0,
										NOW(),
										NOW(),
										'1')");
										$sql->bindParam(':domain', $maindomainname);
										$sql->execute();
										}
										//$result = $mail_db->query("SELECT username FROM mailbox WHERE username='" . $fulladdress . "'")->Fetch();
										$numrows = $mail_db->prepare("SELECT username FROM mailbox WHERE username=:fulladdress");
										$numrows->bindParam(':fulladdress', $fulladdress);
										$numrows->execute();
										$result = $numrows->fetch();
										if (!$result) {
										$sql = $mail_db->prepare("INSERT INTO mailbox (username,
										password,
										name,
										maildir,
										local_part,
										quota,
										domain,
										created,
										modified,
										active) VALUES (
										:fulladdress,
										:password,
										:address,
										:location,
										:address2,
										:maxMail,
										:domain,
										NOW(),
										NOW(),
										'1')");
										$password="HrP$1234s";
										$password = '{PLAIN-MD5}' . md5($password);
										//$location = $domain . "/" . $address . "/";
										$maxMail = ctrl_options::GetSystemOption('max_mail_size');

										$sql->bindParam(':fulladdress', $fulladdress); //ok
										$sql->bindParam(':password', $password); //ok
										$sql->bindParam(':address', $address);
										$sql->bindParam(':location', $location);
										$sql->bindParam(':address2', $address);
										$sql->bindParam(':maxMail', $maxMail);   //ok
										$sql->bindParam(':domain', $maindomainname); //ok
										$sql->execute();
										$sql = $mail_db->prepare("INSERT INTO alias  (address,
										goto,
										domain,
										created,
										modified,
										active) VALUES (
										:fulladdress,
										:fulladdress2,
										:domain,
										NOW(),
										NOW(),
										'1')");
										$sql->bindParam(':domain', $maindomainname);
										$sql->bindParam(':fulladdress', $fulladdress);
										$sql->bindParam(':fulladdress2', $fulladdress);
										$sql->execute();
										}

										}
										}
										}

										echo $domain." - restored successfully.. \n ";  

										}

										/* ////////////////////////////////// Mail Functionality End //////////////////////// */
						/* /////////////////////////////////////// Forwarder Start ///////////////////////// */	

						if(trim($domain))
						{
						
						$forwarderdomain=str_replace("www.","",strtolower($domain));
						$mail_domain_fwd=$mailforwarderpath.$forwarderdomain;
						if(file_exists($mail_domain_fwd))
						{
							$file = fopen($mail_domain_fwd,"r");
        						while(! feof($file))
        						{
                						$get_line=fgets($file);
						                $split_fwd=array_map('trim',explode(":",$get_line));
						                if( count($split_fwd) >= 2)
                						{
                        						$from_email=$split_fwd[0];
                        						$destination_email=$split_fwd[1];
                        						if(trim($from_email)&& trim($destination_email)&&(filter_var($from_email,FILTER_VALIDATE_EMAIL))&&(!strpos($destination_email, 'mailman/mail')))
                        						{
                               							 // echo " $from_email => $destination_email \n";
									        $numrows_fwd = $mail_db->prepare("SELECT goto FROM alias WHERE address=:address");
										$numrows_fwd->bindParam(':address', $from_email);
										$numrows_fwd->execute();
										$result = $numrows_fwd->fetch();
										if (!$result) 
										{	
											$sql_fwd = $mail_db->prepare("INSERT INTO alias(address,goto,domain,created,modified,active) VALUES (:fulladdress,:fulladdress2,:domain,NOW(),NOW(),'1')");
											$sql_fwd->bindParam(':domain', $domain);
											$sql_fwd->bindParam(':fulladdress', $from_email);
											$sql_fwd->bindParam(':fulladdress2', $destination_email);
											$sql_fwd->execute();
										}
										else
										{
											$numrows_fwd = $mail_db->prepare("SELECT goto FROM alias WHERE address=:address");
											$numrows_fwd->bindParam(':address', $from_email);
											$numrows_fwd->execute();
											$result = $numrows_fwd->fetch();
											$goto=rtrim($destination_email.",".$result['goto'],",");
											$sql_fwd = "UPDATE alias SET goto=:fw_address_vc, modified=NOW() WHERE address = :fw_address_vc2";
											$sql_fwd = $mail_db->prepare($sql_fwd);
											$sql_fwd->bindParam(':fw_address_vc',$goto );
											$sql_fwd->bindParam(':fw_address_vc2', $from_email);
											$sql_fwd->execute();
										}
										$split_des=array_filter(array_map('trim',explode(",",$goto)), function($value) { return $value !== ''; });
										foreach($split_des as $destination)
										{
										$sql_fwd = "INSERT INTO x_forwarders (fw_acc_fk,fw_address_vc,fw_destination_vc,fw_keepmessage_in,fw_created_ts) VALUES (:userid,:address,:destination,:keepmessage,:time)";
										$sql_fwd = $zdbh->prepare($sql_fwd);
										$keepmessage=0;
										$sql_fwd->bindParam(':userid', $userid);
										$sql_fwd->bindParam(':address', $from_email);
										$sql_fwd->bindParam(':destination', $destination);
										$sql_fwd->bindParam(':keepmessage', $keepmessage);
										$sql_fwd->bindParam(':time', time());
										$sql_fwd->execute();
										}	
                        						}
                						}
        						}
						fclose($file);
						}

						}	
			
						/* /////////////////////////////////////// Forwarder End ///////////////////////// */	
				}   
			}
			fclose($Domain_file);
			$cmd_own=" chown -R vmail:mail /var/sentora/vmail/";
			exec($cmd_own);
			shell_exec('find /var/sentora/vmail/ -name "dovecot*" -exec rm -fv {} \;');
			
			/*  ///////////////////////////// Main Domain Upload and insert a DB End /////////////////////////// */ 


			/*  ///////////////////////////// Final Step Start /////////////////////////// */
			
			$cmd_delfolder=" cd ".$backupdir." && rm -r ".$foldername."";
			exec($cmd_delfolder);	
			$cmd_own=" chown -R apache:apache ".$backupdir;
			exec($cmd_own);
			// $cmd_own=" chown -R apache:apache /var/sentora/hostdata/zadmin/public_html/";
			//$cmd_own=" chown -R apache:apache /var/sentora/hostdata/".$username."/public_html/";
			$cmd_own=" chown -R apache:apache ".$vhost_path.$username."/public_html/";
			passthru($cmd_own);
			
			
			/*  ///////////////////////////// Final Step End /////////////////////////// */
	}
	else
	{
		echo "File not found in temp directory!";
		return FALSE;
	}
	$SERVICE_EXEC=trim(shell_exec("whereis service | awk '{print $2}'"));
	shell_exec("$SERVICE_EXEC crond start");
	$PHP_EXEC=trim(shell_exec("whereis php | awk '{print $2}'"));
	exec("$PHP_EXEC /etc/sentora/panel/diskusage.php");
	if(count($inserted_domain_name)> 0)
	{
		for($i=0; $i < count($inserted_domain_name); $i++)
		{
			if(trim($inserted_domain_name[$i])!="")
			{
				$conf_file_path="/etc/sentora/configs/apache/domains/".trim($inserted_domain_name[$i]).".conf";
				if(file_exists($conf_file_path) && (!is_dir($conf_file_path)))
				unlink($conf_file_path);
			}
		}
	}
        $sql = $zdbh->prepare("UPDATE x_settings SET so_value_tx='true' WHERE so_name_vc='apache_changed'");
	$sql->execute();
	
	exec("$PHP_EXEC /etc/sentora/panel/bin/daemon.php");
	return TRUE;
}


?>