Current File : //root/panel/modules/sub_domains/code/controller.ext.php
<?php

/**
 * @copyright 2014-2015 Sentora Project (http://www.sentora.org/) 
 * Sentora is a GPL fork of the ZPanel Project whose original header follows:
 *
 * ZPanel - A Cross-Platform Open-Source Web Hosting Control panel.
 *
 * @package ZPanel
 * @version $Id$
 * @author Bobby Allen - ballen@bobbyallen.me
 * @copyright (c) 2008-2014 ZPanel Group - http://www.zpanelcp.com/
 * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3
 *
 * This program (ZPanel) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class module_controller extends ctrl_module
{

    static $complete;
    static $error;
    static $writeerror;
    static $nosub;
    static $alreadyexists;
    static $badname;
    static $blank;
    static $ok;
    static $tryagain;
    static $dirnotexists;
    static $successok;
    static $deleteok;
    static $updateok;
    /**
     * The 'worker' methods.
     */
    static function get_client_ip() {
	$ipaddress = '';
	if (getenv('HTTP_CLIENT_IP'))
	    $ipaddress = getenv('HTTP_CLIENT_IP');
	else if(getenv('HTTP_X_FORWARDED_FOR'))
	    $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
	else if(getenv('HTTP_X_FORWARDED'))
	$ipaddress = getenv('HTTP_X_FORWARDED');
	else if(getenv('HTTP_FORWARDED_FOR'))
	    $ipaddress = getenv('HTTP_FORWARDED_FOR');
	else if(getenv('HTTP_FORWARDED'))
	    $ipaddress = getenv('HTTP_FORWARDED');
	else if(getenv('REMOTE_ADDR'))
	    $ipaddress = getenv('REMOTE_ADDR');
	else
	    $ipaddress = 'UNKNOWN';
	return $ipaddress;
    }
		
    static function ListSubDomains($uid)
    {
        global $zdbh;
        $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:uid AND vh_deleted_ts IS NULL AND vh_type_in=2 ORDER BY vh_name_vc ASC";
        //$numrows = $zdbh->query($sql);
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':uid', $uid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':uid', $uid);
            $res = array();
            $sql->execute();
            while ($rowdomains = $sql->fetch()) {
                array_push($res, array('subname' => $rowdomains['vh_name_vc'],
                    'subdirectory' => $rowdomains['vh_directory_vc'],
                    'subactive' => $rowdomains['vh_active_in'],
                    'subid' => $rowdomains['vh_id_pk']));
            }
            return $res;
        } else {
            return false;
        }
    }

    static function ListDomains($uid)
    {
        global $zdbh;
        $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:uid AND vh_deleted_ts IS NULL AND vh_type_in=1 ORDER BY vh_name_vc ASC";
        //$numrows = $zdbh->query($sql);
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':uid', $uid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':uid', $uid);
            $res = array();
            $sql->execute();
            while ($rowdomains = $sql->fetch()) {
                array_push($res, array('name' => $rowdomains['vh_name_vc'],
                    'directory' => $rowdomains['vh_directory_vc'],
                    'active' => $rowdomains['vh_active_in'],
                    'id' => $rowdomains['vh_id_pk']));
            }
            return $res;
        } else {
            return false;
        }
    }
   
    static function ListDomainDirs($uid)
    {
        global $controller;
        $currentuser = ctrl_users::GetUserDetail($uid);
        $res = array();
        $handle = @opendir(ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username']); // by nandhini
        $chkdir = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username']; // by nandhiniii
        if (!$handle) { 
            # Log an error as the folder cannot be opened...
        } else {
            while ($file = @readdir($handle)) {
                if ($file != "." && $file != ".." && $file != "_errorpages") {
                    if (is_dir($chkdir . $file)) {
                        array_push($res, array('domains' => $file));
                    }
                }
            }
            closedir($handle);
        }
        return $res;
    }
 
    static function SetCallDaemon()
    {
    
	$service_port = 4445 ;
        $address = gethostbyname('localhost');
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($socket === false)
	{
		/* 
		echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
		self::$tryagain=true;
		return false;
		*/
	} 
        //  echo "Attempting to connect to '$address' on port '$service_port'...";
        $result = socket_connect($socket, $address, $service_port);
        if ($result === false) 
	{
        /* 
		echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
		self::$tryagain=true;
		return false;
		*/
		}
		socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" =>0));
		$in="command DaemonCall ";
		socket_write($socket, $in, strlen($in));		
		socket_close($socket);
  
  	}
	
	static function getUserName($uid)
    {
		$currentuser = ctrl_users::GetUserDetail($uid);
		return $currentuser['username'];
    }
	
	static function doUpdateSubDomain()
	{
		global $controller;
		runtime_csfr::Protect();
		$currentuser = ctrl_users::GetUserDetail();
		$formvars = $controller->GetAllControllerRequests('FORM');
		if (self::ExecuteUpdateSubDomain($formvars['inSave'], $formvars['inDir'], $formvars['inDestination']))
			self::$ok = true;
		return true;
	}
	
	static function ExecuteUpdateSubDomain($mid, $indir, $path)
    {
        global $zdbh;
        global $controller;
		$currentuser = ctrl_users::GetUserDetail();
		if($path == "")
		{
			$destination = "/" . $indir;
		}
		else
		{
			$destination = "/" . $path;
		}
		
        $vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . $destination . "/"; //by nandhini
				
		if(file_exists($vhost_path) && is_dir($vhost_path))
		{
			shell_exec("chmod -R 0777 $vhost_path;chown apache:apache $vhost_path;");
			// Continue to next process
		}
		else
		{
			try
			{
				$service_port = 4444;
				$address = gethostbyname('localhost');
				$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				if ($socket === false) 
				{
					//echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
					self::$tryagain=true;
					return false;
				}
				   //echo "Attempting to connect to '$address' on port '$service_port'...";
				   $result = socket_connect($socket, $address, $service_port);
				if ($result === false) 
				{
				   //echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
				   self::$tryagain=true;
				   return false;
				}
			   
				socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 5, "usec" =>0));
				$in = "command DomainPermission $vhost_path";
			
				$out = '';
				socket_write($socket, $in, strlen($in));
				$output = "" ;
			
				$out = socket_read($socket, 2048);
				$output .= $out ;
				
				if ($out == "file_not_exists")
				{
					socket_close($socket);
					self::$dirnotexists = TRUE;
					return FALSE;
				}
			}
			catch(Exception $e)
			{
					self::$tryagain=true;
					return false;
			}
		}
		
		$numrows = $zdbh->prepare("update x_vhosts SET vh_directory_vc=:path WHERE vh_id_pk=:mid");
		$numrows->bindParam(':mid', $mid);
		$numrows->bindParam(':path', $destination);
		$numrows->execute();
		
		/*----------------------------------------File Write-------------------------------------------------*/
		fs_director::CreateDirectory($vhost_path . "/_errorpages/");
				$errorpages = ctrl_options::GetSystemOption('static_dir') . "/errorpages/";
				if (is_dir($errorpages)) {
					if ($handle = @opendir($errorpages)) {
						while (($file = @readdir($handle)) !== false) {
							if ($file != "." && $file != "..") {
								$page = explode(".", $file);
								if (!fs_director::CheckForEmptyValue(self::CheckErrorDocument($page[0]))) {
									fs_filehandler::CopyFile($errorpages . $file, $vhost_path . '/_errorpages/' . $file);
								}
							}
						}
						closedir($handle);
					}
				}
			
            // Lets copy the default welcome page across...
		if ((!file_exists($vhost_path . "/index.html")) && (!file_exists($vhost_path . "/index.php")) && (!file_exists($vhost_path . "/index.htm"))) {
                fs_filehandler::CopyFileSafe(ctrl_options::GetSystemOption('static_dir') . "pages/welcome.html", $vhost_path . "/index.html");
            fs_filehandler::CopyFileSafe( ctrl_options::GetSystemOption('sentora_root'). "etc/styles/CstyleX-master/images/favicon.ico", $vhost_path . "/favicon.ico");
	    fs_filehandler::CopyFileSafe(ctrl_options::GetSystemOption('sentora_root') . "etc/styles/CstyleX-master/images/hostingrajalogo.jpg", $vhost_path . "/hostingrajalogo.jpg");
		}
		
		/*----------------------------------------File Write END-------------------------------------------------*/
		$records_list = ctrl_options::GetSystemOption('Domain_directory_change');
        $record_array = explode(',', $records_list);
        if (!in_array($mid, $record_array)) {
            if (empty($records_list)) {
                $records_list .= $mid;
            } else {
                $records_list .= ',' . $mid;
            }
            $sql = "UPDATE x_settings SET so_value_tx=:newlist WHERE so_name_vc='Domain_directory_change'";
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':newlist', $records_list);
            $sql->execute();
		}
		self::SetWriteApacheConfigTrue();
		self::$updateok = true;
		self::SetCallDaemon();
		return;
		
	}
	
	
	static function getEditID()
    {
        global $controller;
        $id = $controller->GetControllerRequest('URL', 'other');
        return ($id) ? $id : '';
    }
	
	static function getEditCurrentSubDomain()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentSubDomain($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['currentdomain'];
        } else {
            return '';
        }
    }
	
	static function ListCurrentSubDomain($mid)
    {
		global $zdbh;
		global $controller;
		$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;
		}
		
		$sql = "SELECT * FROM x_vhosts WHERE vh_id_pk=:mid AND vh_deleted_ts IS NULL ORDER BY vh_name_vc ASC";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':mid', $mid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':mid', $mid);
            $res = array();
            $sql->execute();
			$rowdomain = $sql->fetch();
			$res[] = array('currentdomain' => $rowdomain['vh_name_vc']);
		}
		return $res;
	}
	
	 static function gethelpicon()
	{
		global $zdbh;
		global $controller;
		$temp=$controller->GetControllerRequest('URL','module') ;
		$val = '/assets/one.txt';
		$val1 = '/modules/';
	   $name=file_get_contents("modules/$temp/assets/helpicon.txt");
	   return $name;
	}

    static function ExecuteDeleteSubDomain($id)
    {
        global $zdbh;
	    global $controller;
        runtime_hook::Execute('OnBeforeDeleteSubDomain');
		$ip_deleted =self::get_client_ip();
        $sql = $zdbh->prepare("UPDATE x_vhosts SET ip_deleted=:ip_deleted,vh_deleted_ts=:time WHERE vh_id_pk=:id");
		$sql->bindParam(':ip_deleted', $ip_deleted);
        $time = time();
        $sql->bindParam(':time', $time);
        $sql->bindParam(':id', $id);
        $sql->execute();
		$sql= $zdbh->prepare("SELECT vh_name_vc FROM x_vhosts WHERE vh_id_pk=:id");
		$sql->bindParam(':id', $id);
		$sql->execute();
		$row_count = $sql->rowCount();
		
		if($row_count >0)
		{
			$rows = $sql->fetch();
		  	$domainname= $rows['vh_name_vc'];
		  	$sql= $zdbh->prepare("UPDATE x_mailboxes set ip_deleted=:ip_deleted,mb_deleted_ts=:time where mb_address_vc LIKE '%@".$domainname."'");
		   	$sql->bindParam(':ip_deleted', $ip_deleted);
		  	$sql->bindParam(':time', $time);
		  	$sql->execute();
		}
			
	/*	if (!fs_director::CheckForEmptyValue(ctrl_options::GetSystemOption('server_ip'))) 
		{
			$targetIP = ctrl_options::GetSystemOption('server_ip');
		} 
		else 
		{
			$targetIP = $_SERVER["SERVER_ADDR"];
		}
	*/
		/*----kanishka---*/
                $csql = $zdbh->prepare("SELECT * FROM x_vhosts as v JOIN x_changeip as c ON v.vh_acc_fk=c.ci_acc_fk WHERE v.vh_id_pk=:id");
                $csql->bindParam(':id', $id);
                $csql->execute();
                $crows = $csql->fetch();

                $targetIP = $crows['ci_ip'];
                /*------kanishka---*/
	
		$currentuser = ctrl_users::GetUserDetail($uid);
		$user_id=$currentuser['userid'];
					 
		$gsql=$zdbh->prepare("select * from x_vhosts WHERE vh_id_pk=:id");
		$gsql->bindParam(':id', $id);
		$gsql->execute();
		$res=$gsql->fetch();
		$subdomainfullname=$res['vh_name_vc'];
		$acc_id=$res['vh_acc_fk'];
		$subdomain_split=explode(".",$subdomainfullname);
		$subDomainName=$subdomain_split[0];
		unset($subdomain_split[0]);
		$domainName=implode(".",$subdomain_split);
		$time = time();
				//	echo  "UPDATE x_dns set dn_deleted_ts='".$time ."' where dn_acc_fk='".$user_id ."' AND dn_name_vc='".$domainName ."' AND dn_type_vc='A' AND dn_host_vc='".$subDomainName ."'AND dn_target_vc='".$targetIP ."'";
		
		$dsql=$zdbh->prepare("UPDATE x_dns set dn_deleted_ts=:time where dn_acc_fk=:userid AND dn_name_vc=:domainName  AND dn_type_vc='A' AND dn_host_vc=:subDomain AND dn_target_vc=:target_new ");		
				   
		$dsql->bindParam(':time', $time);
		$dsql->bindParam(':userid', $user_id);
		$dsql->bindParam(':domainName', $domainName);
		$dsql->bindParam(':subDomain', $subDomainName);
		$dsql->bindParam(':target_new', $targetIP);
		$dsql->execute();
					
		$dsql=$zdbh->prepare("UPDATE x_dns set dn_deleted_ts=:time where dn_acc_fk=:userid AND dn_name_vc=:domainName  AND dn_type_vc='A' AND dn_host_vc=:subDomain AND dn_target_vc=:target_new ");		
		$dsql->bindParam(':time', $time);
		$dsql->bindParam(':userid', $user_id);
		$dsql->bindParam(':domainName', $domainName);
		$serv_alias="www.".$subDomainName;
		$dsql->bindParam(':subDomain',$serv_alias );
		$dsql->bindParam(':target_new', $targetIP);
		$dsql->execute();
					
		$gsql=$zdbh->prepare("select * from x_vhosts WHERE vh_name_vc=:id AND vh_deleted_ts IS NULL");
		$gsql->bindParam(':id', $domainName);
		$gsql->execute();
		$res=$gsql->fetch();
		$domainID=$res['vh_id_pk'];
		$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();
				
        self::SetWriteApacheConfigTrue();
        $retval = TRUE;
        runtime_hook::Execute('OnAfterDeleteSubDomain');
		self::SetCallDaemon();
		/*
		 * Code added By Sangeeth on 22.08.18 
		 * This code is added for Deleting softaculous domain
		 * Code start here
		 */
		$current_username = $currentuser['username'];
		$sql = $zdbh->prepare("SELECT v.vh_name_vc FROM x_vhosts as v JOIN x_main_domain as d ON v.vh_id_pk=x_domain_id WHERE d.x_user_id=$user_id");
		$sql->execute();
		$res = $sql->fetch();
		$maindomain = $res['vh_name_vc'];

		$php_service = trim(shell_exec("whereis php | awk '{print $2}'"));
		$api_key =trim(shell_exec("grep api_key .soft_hr.txt | awk '{print $2}'"));
		$api_pass=trim(shell_exec("grep api_pass .soft_hr.txt | awk '{print $2}'"));
		$soft_username = str_replace(".","_",$maindomain);
		$soft_username = str_replace("-","_", $soft_username);
		$soft_domain_create_res=trim(shell_exec("$php_service /scripts/DeleteSoftaculousDomain.php $api_key $api_pass $domainname $soft_username"));
		/*if(empty($soft_user_create_res['done'])){
			self::$soft_user = true;
		}*/

		/*
		 * Code added By Sangeeth on 16.08.18 
		 * This code is added for Deleting softaculous domain
		 * Code End here
		 */
        return $retval;
    }

    public function ExecuteAddSubDomain($uid, $domain, $dir, $destination, $autohome,$maindomain)
    {
        global $zdbh;
        $retval = FALSE;
        runtime_hook::Execute('OnBeforeAddSubDomain');
        $currentuser = ctrl_users::GetUserDetail($uid);
		$current_username = $currentuser['username'];
        $domain = strtolower(str_replace(' ', '', $domain));
		$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;
		}
		// Adding PostFix Mailboxes
		// if (!fs_director::CheckForEmptyValue(self::$create)) {
		//$result = $mail_db->query("SELECT domain FROM domain WHERE domain='" . $domain . "'")->Fetch();
		$numrows_mail = $mail_db->prepare("SELECT domain FROM domain WHERE domain=:domain");
		$numrows_mail->bindParam(':domain', $domain);
		$numrows_mail->execute();
		$result_mail= $numrows_mail->fetch();
		if (!$result_mail) {
			$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', $domain);
			$sql->execute();
		}
		// }
        if (!fs_director::CheckForEmptyValue(self::CheckCreateForErrors($domain))) {
            //** New Home Directory **//
            if ($autohome == 1) 
			{
                $destination = "/" . str_replace(".", "_", $domain);
                $vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] .  $destination . "/"; // by nandhini
                fs_director::CreateDirectory($vhost_path);
                //** Existing Home Directory **//
            } 
			elseif($autohome == 3)
			{
				$destination = "/" . $dir;
				$vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . $destination . "/"; // by nandhini
				$vhost_path = trim($vhost_path);
				/*if(file_exists($vhost_path) && is_dir($vhost_path))
				{
					// Continue to next process
				}
				else
				{*/
				try
				{
					$service_port = 4444;
					$address = gethostbyname('localhost');
					$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
					if ($socket === false) 
					{
						//echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
						self::$tryagain=true;
						return false;
					}
					   //echo "Attempting to connect to '$address' on port '$service_port'...";
					   $result = socket_connect($socket, $address, $service_port);
					if ($result === false) 
					{
					   //echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
					   self::$tryagain=true;
					   return false;
					}
				   
					socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 5, "usec" =>0));
					$in = "command DomainPermission $vhost_path";
				
					$out = '';
					socket_write($socket, $in, strlen($in));
					$output = "" ;
				
					$out = socket_read($socket, 2048);
					$output .= $out ;
					//echo $out; exit;
					if ($out == "file_not_exists")
					{
						socket_close($socket);
						self::$dirnotexists = TRUE;
						return FALSE;
					}
				}
				catch(Exception $e)
				{
					self::$tryagain=true;
					return false;
				}
				//}
			}
			else 
			{
                $destination = "/" . $destination;
                $vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username']  . $destination . "/"; // by nandhini
            }
            // Error documents:- Error pages are added automatically if they are found in the _errorpages directory
            // and if they are a valid error code, and saved in the proper format, i.e. <error_number>.html
            fs_director::CreateDirectory($vhost_path . "/_errorpages/");
            $errorpages = ctrl_options::GetSystemOption('static_dir') . "/errorpages/";
            if (is_dir($errorpages)) {
                if ($handle = @opendir($errorpages)) {
                    while (($file = @readdir($handle)) !== false) {
                        if ($file != "." && $file != "..") {
                            $page = explode(".", $file);
                            if (!fs_director::CheckForEmptyValue(self::CheckErrorDocument($page[0]))) {
                                fs_filehandler::CopyFile($errorpages . $file, $vhost_path . '/_errorpages/' . $file);
                            }
                        }
                    }
                    closedir($handle);
                }
            }
            // Lets copy the default welcome page across...
            if ((!file_exists($vhost_path . "/index.html")) && (!file_exists($vhost_path . "/index.php")) && (!file_exists($vhost_path . "/index.htm"))) {
                fs_filehandler::CopyFileSafe(ctrl_options::GetSystemOption('static_dir') . "pages/welcome.html", $vhost_path . "/index.html");
              fs_filehandler::CopyFileSafe( ctrl_options::GetSystemOption('sentora_root'). "etc/styles/CstyleX-master/images/favicon.ico", $vhost_path . "/favicon.ico");
            fs_filehandler::CopyFileSafe(ctrl_options::GetSystemOption('sentora_root') . "etc/styles/CstyleX-master/images/hostingrajalogo.jpg", $vhost_path . "/hostingrajalogo.jpg");

		}
            // If all has gone well we need to now create the domain in the database...
            $sql = $zdbh->prepare("INSERT INTO x_vhosts (vh_acc_fk,
														 vh_name_vc,
														 vh_directory_vc,
														 vh_type_in,
														 vh_created_ts) VALUES (
														 :userid,
														 :domain,
														 :destination,
														 2,
														 :time)"); //CLEANER FUNCTION ON $domain and $homedirectory_to_use (Think I got it?)
            $sql->bindParam(':userid', $currentuser['userid']);
            $sql->bindParam(':domain', $domain);
            $sql->bindParam(':destination', $destination);
            $time = time();
            $sql->bindParam(':time', $time);
            $sql->execute();
            
			$mod_sql = $zdbh->prepare("SELECT * FROM x_vhosts WHERE vh_name_vc=:domain");
			$mod_sql->bindParam(':domain', $domain);
			$mod_sql->execute();
			$modrow = $mod_sql->fetch();
			
			$modsec_sql = $zdbh->prepare("INSERT INTO x_modsecurity (x_domain_id,x_mod_status) VALUES (:modid,'ModOn')");
			$modsec_sql->bindParam(':modid', $modrow['vh_id_pk']);
			$modsec_sql->execute();
			
			/*Code Added By Kesav For Default PHPversion Start*/
			
			$php_userid = $modrow['vh_id_pk'];
			$sql_update = "INSERT INTO x_phpversion_upgrade (x_php_version,x_flag,x_update_time,x_client_id) VALUES (:x_php_version,:x_flag,:x_update_time,:userid)";
			$numphp = $zdbh->prepare($sql_update);
			$numphp->bindParam(':userid',$php_userid );
			$update_version = "php56";
			$numphp->bindParam(':x_php_version', $update_version);
			$time=time();
			$flag="On";
			$numphp->bindParam(':x_flag', $flag);
			$numphp->bindParam(':x_update_time', $time);
			$numphp->execute();

			/*Code Added By Kesav For Default PHPversion Start*/
			
            # Only run if the Server platform is Windows.
            if (sys_versions::ShowOSPlatformVersion() == 'Windows') {
                if (ctrl_options::GetSystemOption('disable_hostsen') == 'false') {
                    # Lets add the hostname to the HOSTS file so that the server can view the domain immediately...
                    @exec("C:/Sentora/bin/zpss/setroute.exe " . $domain . "");
                }
            }
			/* /////////////////////////////////////// Automatic DNS configuration  Start //////////////////////////////////////////////////// */
	/*		if (!fs_director::CheckForEmptyValue(ctrl_options::GetSystemOption('server_ip'))) {
				$targetIP = ctrl_options::GetSystemOption('server_ip');
			} else {
				$targetIP = $_SERVER["SERVER_ADDR"];
			}
	
	 /*--kanishka--*/
                $domainName =$maindomain;
                $csql = $zdbh->prepare("SELECT * FROM x_vhosts as v JOIN x_changeip as c ON v.vh_acc_fk=c.ci_acc_fk WHERE v.vh_acc_fk=:userid AND v.vh_name_vc=:domainName AND v.vh_deleted_ts is NULL");
                $csql->bindParam(':domainName', $domainName);
                $csql->bindParam(':userid', $currentuser['userid']);
                $csql->execute();
                $crows = $csql->fetch();

                $targetIP = $crows['ci_ip'];
        /*---kanishka--*/

			
			$user_id=$currentuser['userid'];
			$domainName =$maindomain;
			$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', $domainName);
			$gsql->execute();
			$res=$gsql->fetch();
			$domainID=$res['vh_id_pk'];		
			$arr = explode(".", $domain);
			$subDomainName=$arr[0];
			$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', $domainName);
			$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', $domainName);
				$sql->bindParam(':domainID', $domainID);
				$sql->bindParam(':hostName_new', $subDomainName);
				$sql->bindParam(':target_new', $targetIP);
				$time = time();
				$sql->bindParam(':time', $time);
				$sql->execute();
				unset($sql);

				$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', $domainName);
				$sql->bindParam(':domainID', $domainID);
				$serv_alias="www.".$subDomainName;
				$sql->bindParam(':hostName_new',$serv_alias);
				$sql->bindParam(':target_new', $targetIP);
				$time = time();
				$sql->bindParam(':time', $time);
				$sql->execute();
				unset($sql);
			
				$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();
			self::SetWriteApacheConfigTrue();
            $retval = TRUE;
            runtime_hook::Execute('OnAfterAddSubDomain');
            self::SetCallDaemon();
			/* ///////////// Automatic DNS configuration  End ////////////////////// */
            /*
			 * Code added By Sangeeth on 22.08.18 
			 * This code is added for creating softaculous domain
			 * Code start here
			 */
			$ftp_db = ctrl_options::GetSystemOption('ftp_db');
			include('cnf/db.php');
			$z_db_user = $user;
			$z_db_pass = $pass;
			try {
				$ftp_db = new db_driver("mysql:host=" . $host . ";dbname=$ftp_db", $z_db_user, $z_db_pass);
				} catch (PDOException $e) {

			}
			$sql = $ftp_db->prepare("SELECT passwd FROM ftpuser where userid=:username");
			$sql->bindParam(':username', $current_username);
			$sql->execute();
			$res = $sql->fetch();
			$current_user_password = $res['passwd'];

			$php_service = trim(shell_exec("whereis php | awk '{print $2}'"));
			$api_key =trim(shell_exec("grep api_key .soft_hr.txt | awk '{print $2}'"));
			$api_pass=trim(shell_exec("grep api_pass .soft_hr.txt | awk '{print $2}'"));
			$soft_username = str_replace(".","_",$maindomain);
			$soft_username = str_replace("-","_", $soft_username);
			/*if($destination== "/") {
				$ftp_path = "/public_html";
			} else {
				$ftp_path = "/public_html".$destination;
			}*/
			$username="sanghi";
			$password="ijuHr@2018";
			$soft_domain_create_res = trim(shell_exec("$php_service /scripts/CreateSoftaculousDomain.php $api_key $api_pass $domain $current_username $current_user_password $soft_username $destination"));
			/*if(empty($soft_user_create_res['done'])){
				self::$soft_user = true;
			}*

			/*
			 * Code added By Sangeeth on 22.08.18 
			 * This code is added for creating softaculous domain
			 * Code End here
			 */
            return $retval;
        }
    }
    
	////////////////////////////////my code////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////

	/*$sql = $zdbh->prepare("INSERT INTO x_vhosts (vh_acc_fk,
														 vh_name_vc,
														 vh_directory_vc,
														 vh_type_in,
														 vh_created_ts) VALUES (
														 :userid,
														 :domain,
														 :destination,
														 2,
														 :time)"); //CLEANER FUNCTION ON $domain and $homedirectory_to_use (Think I got it?)
            $sql->bindParam(':userid', $currentuser['userid']);
            $sql->bindParam(':domain', $domain);
            $sql->bindParam(':destination', $destination);
            $time = time();
            $sql->bindParam(':time', $time);
            $sql->execute();
	*/

	////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////

    static function CheckCreateForErrors($domain)
    {
        global $zdbh;
        // Check for spaces and remove if found...
        $domain = strtolower(str_replace(' ', '', $domain));
        // Check to make sure the domain is not blank before we go any further...
        if ($domain == '') {
            self::$blank = TRUE;
            return FALSE;
        }
        // Check for invalid characters in the domain...
        if (!self::IsValidDomainName($domain)) {
            self::$badname = TRUE;
            return FALSE;
        }
        // Check to make sure the domain is in the correct format before we go any further...
        if (strpos($domain, 'www.') === 0) {
            self::$error = TRUE;
            return FALSE;
        }
        // Check to see if the domain already exists in Sentora somewhere and redirect if it does....
        $sql = "SELECT COUNT(*) FROM x_vhosts WHERE vh_name_vc=:domain AND vh_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':domain', $domain);

        if ($numrows->execute()) {
            if ($numrows->fetchColumn() > 0) {
                self::$alreadyexists = TRUE;
                return FALSE;
            }
        }
        return TRUE;
    }

    static function CheckErrorDocument($error)
    {
        $errordocs = array(100, 101, 102, 200, 201, 202, 203, 204, 205, 206, 207,
            300, 301, 302, 303, 304, 305, 306, 307, 400, 401, 402,
            403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413,
            414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424,
            425, 426, 500, 501, 502, 503, 504, 505, 506, 507, 508,
            509, 510);
        return in_array($error, $errordocs);
    }

    static function IsValidDomainName($a)
    {
        if (stristr($a, '.')) {
            $part = explode(".", $a);
            foreach ($part as $check) {
                if (!preg_match('/^[a-z\d][a-z\d-]{0,62}$/i', $check) || preg_match('/-$/', $check)) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    static function IsValidEmail($email)
    {
        return preg_match('/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i', $email) == 1;
    }

    static function SetWriteApacheConfigTrue()
    {
        global $zdbh;
        $sql = $zdbh->prepare("UPDATE x_settings
								SET so_value_tx='true'
								WHERE so_name_vc='apache_changed'");
        $sql->execute();
    }

    /**
     * End 'worker' methods.
     */

    /**
     * Webinterface sudo methods.
     */
    static function getSubDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $res = array();
        $subdomains = self::ListSubDomains($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($subdomains)) {
            foreach ($subdomains as $row) {
                $status = self::getSubDomainStatusHTML($row['subactive'], $row['subid']);
                $res[] = array('subname' => $row['subname'],
                    'subdirectory' => $row['subdirectory'],
                    'subactive' => $row['subactive'],
                    'substatus' => $status,
                    'subid' => $row['subid']);
            }
            return $res;
        } else {
            return false;
        }
    }

    static function getDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $domains = self::ListDomains($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($domains)) {
            return $domains;
        } else {
            return false;
        }
    }
	
	static function doEditSubDomain()
    {
		global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListSubDomains($currentuser['userid']) as $row) {
            if (isset($formvars['inDelete_' . $row['subid'] . ''])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Delete&id=' . $row['subid'] . '&domain=' . $row['subname']);
                exit;
            }
            if (isset($formvars['inEdit_' . $row['subid']])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Edit&other=' . $row['subid']);
                exit;
            }
        }
        return true;
	}
	
    static function getCreateSubDomain()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return ($currentuser['subdomainquota'] < 0) or //-1 = unlimited
                ($currentuser['subdomainquota'] > ctrl_users::GetQuotaUsages('subdomains', $currentuser['userid']));
    }

    static function getSubDomainDirsList()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $domaindirectories = self::ListDomainDirs($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($domaindirectories)) {
            return $domaindirectories;
        } else {
            return false;
        }
    }

    static function doCreateSubDomain()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        if (self::ExecuteAddSubDomain($currentuser['userid'], $formvars['inSub'] . "." . $formvars['inDomain'], $formvars['inDir'], $formvars['inDestination'], $formvars['inAutoHome'],$formvars['inDomain'])) {
            // self::$ok = TRUE;
	    self::$successok=TRUE;
            return true;
        } else {
            return false;
        }
        return;
    }

    static function n_sanitize($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
	
    static function doDeleteSubDomain()
    {
		global $zdbh;
        global $controller;
        runtime_csfr::Protect();
//PP      $currentuser = ctrl_users::GetUserDetail();  assignment never used
        $formvars = $controller->GetAllControllerRequests('FORM');
        if (isset($formvars['inDelete'])) {
            if (self::ExecuteDeleteSubDomain($formvars['inDelete'])) {
			$addon_id=self::n_sanitize($formvars['inDelete']);
			$currentuser = ctrl_users::GetUserDetail();
                        $suid = $currentuser['userid'];	
			$stmt2 = $zdbh->prepare("select vh_id,vh_mail  from x_autorespond where vh_acc_fk =:nuid and vh_did =:ndid and vh_deleted IS NULL ");
                        $stmt2->bindParam(':nuid',$suid);
                        $stmt2->bindParam(':ndid',$addon_id);
                        $stmt2->execute();
                        $row_count2 = $stmt2->rowCount();
                        if($row_count2 > 0 )
                        {
                            while($rows = $stmt2->fetch())
                            {
                                $auto_email1 = $rows['vh_mail'];
                                if($auto_email1 != "")
                                {
                                    $auto_file_path = "/var/spool/autoresponse/responses/".$auto_email1;
                                    if (file_exists($auto_file_path)) 
                                    {

                                        if(unlink($auto_file_path))
                                        {
                                        
                                        }
                                    }
                                }
                            }
                            date_default_timezone_set("UTC");
                            $current_time = date("Y-m-d H:i:s");
                            $current_str_time =  strtotime($current_time);
                            $stmt4 =$zdbh->prepare("update x_autorespond set vh_deleted =:str_time  where  vh_did =:vhid  and vh_acc_fk =:sid ");
                            $stmt4->bindParam(':str_time',$current_str_time);
                            $stmt4->bindParam(':sid',$suid);
                            $stmt4->bindParam(':vhid',$addon_id);
                            $stmt4->execute();   
                            /*********$affected_rows = $stmt4->rowCount(); *************/
                                                      
                        }
					
					
                self::$deleteok = TRUE;
                return true;
            }
        }
        return false;
    }

    static function doConfirmDeleteSubDomain()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListSubDomains($currentuser['userid']) as $row) {
            if (isset($formvars['inDelete_' . $row['subid'] . ''])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Delete&id=' . $row['subid'] . '&domain=' . $row['subname']);
                exit;
            }
        }
        return false;
    }

    static function getisDeleteDomain()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == 'Delete');
    }
	
	static function getisEditSubDomain()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Edit");
    }
	
	
    static function getCurrentID()
    {
        global $controller;
        $id = $controller->GetControllerRequest('URL', 'id');
        return ($id) ? $id : '';
    }

    static function getCurrentDomain()
    {
        global $controller;
        $domain = $controller->GetControllerRequest('URL', 'domain');
        return ($domain) ? $domain : '';
    }

    static function getSubDomainUsagepChart()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $maximum = $currentuser['subdomainquota'];
        if ($maximum < 0) { //-1 = unlimited
            return '<img src="' . ui_tpl_assetfolderpath::Template() . 'img/misc/unlimited.png" alt="' . ui_language::translate('Unlimited') . '"/>';
        } else {
            $used = ctrl_users::GetQuotaUsages('subdomains', $currentuser['userid']);
            $free = max($maximum - $used, 0);
            return '<img src="etc/lib/pChart2/sentora/z3DPie.php?score=' . $free . '::' . $used
                    . '&labels=Free: ' . $free . '::Used: ' . $used
                    . '&legendfont=verdana&legendfontsize=8&imagesize=240::190&chartsize=120::90&radius=100&legendsize=150::160"'
                    . ' alt="' . ui_language::translate('Pie chart') . '"/>';
        }
    }

    static function getSubDomainStatusHTML($int, $id)
    {
        global $controller;
        if ($int == 1) {
            return '<td><font color="green">' . ui_language::translate('Live') . '</font></td>'
                    . '<td></td>';
        } else {
            return '<td><font color="orange">' . ui_language::translate("Pending") . '</font></td>'
                    . '<td><a href="#" class="help_small" id="help_small_' . $id . '_a"'
                    . 'title="' . ui_language::translate('Your domain will become active at the next scheduled update.  This can take up to one hour.') . '">'
                    . '<img src="/modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/help_small.png" border="0" /></a></td>';
        }
    }

    static function getResult()
    {
	if (!fs_director::CheckForEmptyValue(self::$dirnotexists)) {
            return ui_sysmessage::shout(ui_language::translate("Directory does not exists. Kindly create a Directory and try again."), "zannounceerror");
        }
         if (!fs_director::CheckForEmptyValue(self::$tryagain)) {
			return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> Please try again Later. Server service not available."), "Error");
		}
		if (!fs_director::CheckForEmptyValue(self::$blank)) {
            return ui_sysmessage::shout(ui_language::translate("Your Domain can't be empty. Please enter a valid Domain Name and try again."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$badname)) {
            return ui_sysmessage::shout(ui_language::translate("Your Domain name is not valid. Please enter a valid Domain Name: i.e. 'domain.com'"), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate("The domain already appears to exist on this server."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$error)) {
            return ui_sysmessage::shout(ui_language::translate("Please remove 'www'. The 'www' will automatically work with all Domains / Subdomains."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$writeerror)) {
            return ui_sysmessage::shout(ui_language::translate("There was a problem writting to the virtual host container file. Please contact your administrator and report this error. Your domain will not function until this error is corrected."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$successok)) {
            return ui_sysmessage::shout(ui_language::translate("Sub Domain has been created successfully."), "zannounceok");
        }
        if (!fs_director::CheckForEmptyValue(self::$deleteok)) {
            return ui_sysmessage::shout(ui_language::translate("Sub Domain has been deleted successfully."), "zannounceok");
        }
        if (!fs_director::CheckForEmptyValue(self::$updateok)) {
            return ui_sysmessage::shout(ui_language::translate("Directory has been changed successfully."), "zannounceok");
        }

	if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("Changes to your domain web hosting has been saved successfully."), "zannounceok");
        }
        return;
    }

    /**
     * Webinterface sudo methods.
     */
}