Current File : //etc/zpanel/panel/modules/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 $dirnotexists;
    	static $ok;
    	static $okk;
	static $ok_switch;
	static $tryagain;
	static $ans_switch="";
    	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 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" => 100, "usec" =>0));
		$in="command DaemonCall ";
		socket_write($socket, $in, strlen($in));		
		socket_close($socket);
    	}
	
	static function getisadmin()
	{
		global $controller;
        	$currentuser = ctrl_users::GetUserDetail();
        	if ($currentuser['usergroup'] == "Administrators" || $currentuser['usergroup'] == "Resellers") {
        	    	return true;
        	} else {
        	    	return false;
        	}
		 
	}
	static function getParticular_User()
	{
	 
	}
 	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 getDomainDirss()
    	{
		$currentuser = ctrl_users::GetUserDetail();
        	$res = array();
        	$res = self::ListDomains($currentuser['userid']);
		return $res;
        	$destination = "/" . str_replace(".", "_", $domain);
		$vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . $destination . "/";
	}
	
    	static function ListDomains($uid = 0)
    	{ 
        	global $zdbh;
        	if ($uid == 0 || $uid == 1 ) {
            		$sql = "SELECT * FROM x_vhosts WHERE vh_deleted_ts IS NULL AND vh_type_in=1 ORDER BY vh_name_vc ASC";
            		$numrows = $zdbh->prepare($sql);
        	} else {
            		$sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:uid AND vh_deleted_ts IS NULL AND vh_type_in=1 AND 
			       vh_id_pk NOT IN (SELECT x_domain_id FROM x_main_domain WHERE x_user_id=:uid ) ORDER BY vh_name_vc ASC";
            		$numrows = $zdbh->prepare($sql);
            		$numrows->bindParam(':uid', $uid);
        	}
        	//$numrows = $zdbh->query($sql);
        	$numrows->execute();
        	if ($numrows->fetchColumn() <> 0) {
            		if ($uid == 0 || $uid == 1) {
                		$sql = $zdbh->prepare($sql);
            		} else {
                		$sql = $zdbh->prepare($sql);
                		$sql->bindParam(':uid', $uid);
            		}
            		$res = array();
            		$sql->execute();
            		while ($rowdomains = $sql->fetch()) {
				$create_select='<select id="client_manage_'.$rowdomains['vh_id_pk'].'" name="client_manage_'.$rowdomains['vh_id_pk'].'">';
				$sqluse = "SELECT * FROM x_accounts WHERE ac_enabled_in=1 AND ac_deleted_ts IS NULL";
				$sqluse = $zdbh->prepare($sqluse);
				$sqluse->execute();	
				while ($listusers = $sqluse->fetch()) {
					$flagselected='';
					if($rowdomains['vh_acc_fk']==$listusers['ac_id_pk'])
					{
						$flagselected='Selected="Selected"';	 
					}
					$create_select.='<option value="'.$listusers['ac_id_pk'].'"  '.$flagselected.'>'.$listusers['ac_user_vc'].'</option>';
				}
				$create_select.='</select>';
				
                		array_push($res, array(
                    			'uid' => $rowdomains['vh_acc_fk'],
                    			'name' => $rowdomains['vh_name_vc'],
                    			'directory' => $rowdomains['vh_directory_vc'],
					'listusers' => $create_select,
                    			'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 nandhini
		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 ExecuteDeleteDomain($id)
    	{
		global $zdbh;
		try
		{
			$service_domain_port = 4444 ;
			$address_domain = gethostbyname('localhost');
			$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if ($socket_domain === false)
			{
				socket_close($socket_domain);
				self::$tryagain=true;
				return false;
			}
			else 
			{
			$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
					if ($result === false) 
					{		
						socket_close($socket_domain);
						self::$tryagain=true;
						return false;
						
					}

			}
		}
		catch(Exception $e)
		{
							self::$tryagain=true;
							return false;
		}
		socket_close($socket_domain);
		runtime_hook::Execute('OnBeforeDeleteDomain');
		$sql = $zdbh->prepare("UPDATE x_vhosts
					   SET ip_deleted=:ip_deleted,vh_deleted_ts=:time
					   WHERE vh_id_pk=:id");
		$sql->bindParam(':id', $id);
			$ip_deleted =self::get_client_ip();
		$time = time();
		$sql->bindParam(':ip_deleted', $ip_deleted);
			 $sql->bindParam(':time', $time);
		$sql->execute();
		// deleting subdomains starts		
		$sql= $zdbh->prepare("SELECT vh_name_vc FROM x_vhosts WHERE vh_id_pk=:id");		
		$sql->bindParam(':id', $id);		
		$sql->execute();		
		//$domainname= $zdbh->query($sql);		
		$row_count = $sql->rowCount();		
		if($row_count >0)		
		{		
		    	$rows = $sql->fetch();		
		    	$domainname= $rows['vh_name_vc'];		
		    	$ip_deleted =self::get_client_ip();
			$sql= $zdbh->prepare("UPDATE x_vhosts set ip_deleted=:ip_deleted,vh_deleted_ts=:time where vh_name_vc LIKE '%.".$domainname."' AND  vh_type_in =2");		
			$sql->bindParam(':ip_deleted', $ip_deleted);
		    	$sql->bindParam(':time', $time);		
		    	$sql->execute();		
		}		
		//deleting subdomain ends		
		//deleting add on email starts		
		$sql= $zdbh->prepare("UPDATE x_mailboxes set mb_deleted_ts=:time where mb_address_vc LIKE '%@".$domainname."' ");		
		$sql->bindParam(':time', $time);		
		$sql->execute();		
	      	$sql= $zdbh->prepare("UPDATE x_mailboxes set mb_deleted_ts=:time where mb_address_vc LIKE '%@%.".$domainname."' ");		
		$sql->bindParam(':time', $time);		
		$sql->execute(); 
		$sql = $zdbh->prepare("update x_mailboxes as m
					INNER JOIN x_vhosts as v
					set m.mb_deleted_ts=:time
					where (v.vh_id_pk=m.vh_uni_id) AND v.vh_deleted_ts IS NOT NULL");
		/* //////////////////////////////////////  Java File Path Added //////////////////////////////////////  */
		
		try
		{
					$sql_tomcat = $zdbh->prepare("SELECT * FROM x_java_version");
					$sql_tomcat->execute();
					$row_tomcat= $sql_tomcat->fetch();
					// $java_file_path=$row_java['x_file_path'];
					$java_domain_name=trim($domainname);
					$tomcat_path=$row_tomcat['x_file_path'];
					$service_domain_port = 4444 ;
					$address_domain = gethostbyname('localhost');
					$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
					if ($socket_domain === false)
					{
						self::$tryagain=true;
						return false;
					}
					else 
					{
					$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
							if ($result === false) 
							{		
								self::$tryagain=true;
								return false;
							}
							else 
							{
							socket_set_option($socket_domain, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1000, "usec" =>0));
							$in="command Java_Remove_Domain $java_domain_name $tomcat_path";
							socket_write($socket_domain, $in, strlen($in));		
							socket_close($socket_domain);
							}
					}
		}
		catch(Exception $e)
		{
			self::$tryagain=true;
			return false;
			
		}		
		/* //////////////////////////////////////  Java File Path End //////////////////////////////////////  */	
			
		self::SetWriteApacheConfigTrue();
		$retval = TRUE;
		runtime_hook::Execute('OnAfterDeleteDomain');
		self::SetCallDaemon();
		return $retval;
    	}

    	static function ExecuteAddDomain($uid, $domain, $dir, $destination, $autohome)
    	{
		//echo $uid."-->".$domain."-->". $dir."-->". $destination."-->". $autohome."\n"; exit;
        	global $zdbh;
		global $controller;
		try
		{
			$service_domain_port = 4444 ;
			$address_domain = gethostbyname('localhost');
			$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if ($socket_domain === false)
			{
				socket_close($socket_domain);
				self::$tryagain=true;
				return false;
			}
			else 
			{
			$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
					if ($result === false) 
					{		
						socket_close($socket_domain);
						self::$tryagain=true;
						return false;
						
					}

			}
		}
		catch(Exception $e)
		{
							self::$tryagain=true;
							return false;
		}
		socket_close($socket_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();
		}
		// }
        	$retval = FALSE;
        	runtime_hook::Execute('OnBeforeAddDomain');
        	$currentuser = ctrl_users::GetUserDetail($uid);
        	$domain = strtolower(str_replace(' ', '', $domain));
        	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."/";
				fs_director::CreateDirectory($vhost_path);
				fs_director::SetFileSystemPermissions($vhost_path, 0755);
				//fs_director::setFileSystemPermissionSecure($vhost_path);
				//** Existing Home Directory **//
				/*shell_exec("/usr/bin/find $vhost_path -type f -exec chmod 644 {} \;");
				echo "/usr/bin/find $vhost_path -type f -exec chmod 644 {} \;";
                                shell_exec("/usr/bin/find $vhost_path -type d -exec chmod 755 {} \;");
				echo "/usr/bin/find $vhost_path -type d -exec chmod 755 {} \;";*/
			}
			elseif($autohome == 3)
			{
				$destination = "/" . $dir;
				$vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username']  . $destination . "/";
				$vhost_path = trim($vhost_path);
				if(file_exists($vhost_path) && is_dir($vhost_path))
				{
					fs_director::setFileSystemPermissionSecure($vhost_path);
					//shell_exec("chmod -R 0755 $vhost_path;chown apache:apache $vhost_path;");
					//shell_exec("/usr/bin/find $vhost_path -type f -exec chmod 644 {} \;");
					//shell_exec("/usr/bin/find $vhost_path -type d -exec chmod 755 {} \;");
					// 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;
					}
				}
			}
			else 
			{
				$destination = "/" . $destination;
				$vhost_path = ctrl_options::GetSystemOption('hosted_dir').$currentuser['username'].$destination."/";
				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 DomainOwnership $vhost_path";
						
					$out = '';
					socket_write($socket, $in, strlen($in));
					$output = "" ;
						
					$out = socket_read($socket, 2048);
					$output .= $out ;
					if ($out == "hai")
					{
						socket_close($socket);
						fs_director::SetFileSystemPermissions($vhost_path, 0755);
					}
				}
				catch(Exception $e)
				{
                                        self::$tryagain=true;
                                        return false;
                        	}
	
			}
			// 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
			//if() {
			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_active_in,
								 vh_created_ts) VALUES (
								 :userid,
								 :domain,
								 :destination,
								 1,1,
								 :time)"); //CLEANER FUNCTION ON $domain and $homedirectory_to_use (Think I got it?)
			$time = time();
			$sql->bindParam(':time', $time);
			$sql->bindParam(':userid', $currentuser['userid']);
			$sql->bindParam(':domain', $domain);
			$sql->bindParam(':destination', $destination);
			$sql->execute();
			$last_insert_domain_id = $zdbh->lastInsertId();
				
			/*$mod_sql = $zdbh->prepare("SELECT * FROM x_vhosts WHERE vh_name_vc=:domain AND ");
			$mod_sql->bindParam(':domain', $domain);
			$mod_sql->execute();
			$modrow = $mod_sql->fetch();*/
			$sql = "INSERT INTO x_modsecurity (x_domain_id,x_mod_status) VALUES ($last_insert_domain_id,'ModOn')";
			$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->bindParam(':modid', $last_insert_domain_id);
			$kesav = $modsec_sql->execute();
				
			self::auto_dns($domain);
			// 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 . "");
					@exec("C:/Sentora/bin/zpss/setroute.exe www." . $domain . "");
				}
			}
                	/* //////////////////////////////////////  Java File Path Added //////////////////////////////////////  */
                try
                {
					$sql_tomcat = $zdbh->prepare("SELECT * FROM x_java_version");
					$sql_tomcat->execute();
					$row_tomcat= $sql_tomcat->fetch();
					// $java_file_path=$row_java['x_file_path'];
					$java_domain_name=$domain;
					$java_domain_full_path=$vhost_path;
					$tomcat_path=$row_tomcat['x_file_path'];
					$service_domain_port = 4444 ;
					$address_domain = gethostbyname('localhost');
					$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
					if ($socket_domain === false)
					{

					}
					else 
					{
					$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
							if ($result === false) 
							{			
							}
							else 
							{
							socket_set_option($socket_domain, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1000, "usec" =>0));
							$in="command Java_Add_Domain $java_domain_name $java_domain_full_path $tomcat_path";
							socket_write($socket_domain, $in, strlen($in));		
							socket_close($socket_domain);
							}
					}
                }
                catch(Exception $e)
                {
                    
                }
                    /* //////////////////////////////////////  Java File Path End //////////////////////////////////////  */
                
			//echo $kesav; exit;
			fs_director::SetFileSystemPermissionSecure($vhost_path);
			self::SetWriteApacheConfigTrue();
			$retval = TRUE;
			runtime_hook::Execute('OnAfterAddDomain');
			self::SetCallDaemon();
			self::$okk = true;
			return $retval;
		}
	}
	
    	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;
			}
		}
		// Check to make sure user not adding a subdomain and blocks stealing of subdomains....
		// Get shared domain list
		$SharedDomains = array();
		$a = explode(',', ctrl_options::GetSystemOption('shared_domains'));
		foreach ($a as $b) {
			$SharedDomains[] = $b;
		}
		if (substr_count($domain, ".") > 1) {
			$part = explode('.', $domain);
			foreach ($part as $check) {
				if (!in_array($check, $SharedDomains)) {
					if (strlen($check) > 3) {
						$sql = $zdbh->prepare("SELECT * FROM x_vhosts WHERE vh_name_vc LIKE :check AND vh_type_in !=2 AND vh_deleted_ts IS NULL");
						$checkSql = '%' . $check . '%';
						$sql->bindParam(':check', $checkSql);
						$sql->execute();
						while ($rowcheckdomains = $sql->fetch()) {
							$subpart = explode('.', $rowcheckdomains['vh_name_vc']);
							foreach ($subpart as $subcheck) {
								if (strlen($subcheck) > 3) {
									if ($subcheck == $check) {
										if (substr($domain, -7) == substr($rowcheckdomains['vh_name_vc'], -7)) {
											self::$nosub = 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();
    	}

    	static function IsvalidIP($ip)
    	{
        	return preg_match("^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^", $ip) == 1;
    	}

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

    /**
     * Webinterface sudo methods.
     */
    	static function getDomainList()
    	{
		$currentuser = ctrl_users::GetUserDetail();
		$res = array();
		$domains = self::ListDomains($currentuser['userid']);
		if (!fs_director::CheckForEmptyValue($domains)) {
		    	foreach ($domains as $row) {
				$status = self::getDomainStatusHTML($row['active'], $row['id']);
				$res[] = array('name' => $row['name'],
				    	'directory' => $row['directory'],
				    	'active' => $row['active'],
				    	'status' => $status,
					'listusers'=>$row['listusers'],
				    	'id' => $row['id']);
			}
		    	return $res;
		} else {
		    	return false;
		}
    	}

    	static function getCreateDomain()
    	{
        	$currentuser = ctrl_users::GetUserDetail();
        	return ($currentuser['domainquota'] < 0) or //-1 = unlimited
                ($currentuser['domainquota'] > ctrl_users::GetQuotaUsages('domains', $currentuser['userid']));
    	}

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

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

   	/*static function doDeleteDomain()
    	{
        	global $controller;
        	runtime_csfr::Protect();
        	$formvars = $controller->GetAllControllerRequests('FORM');
		if (isset($formvars['inDelete'])) {
			if (self::ExecuteDeleteDomain($formvars['inDelete'])) {
				self::$ok = TRUE;
				return true;
			}
		}	 	 
        	return false;
    	}*/


	static function doDeleteDomain()
    	{
        	global $controller;
        	global $zdbh;
        	runtime_csfr::Protect();
        	$formvars = $controller->GetAllControllerRequests('FORM');
		 
		if ( array_key_exists("inDelete",$formvars) && isset($formvars['inDelete']) )
		{
			$addon_id=self::n_sanitize($formvars['inDelete']);
			if (self::ExecuteDeleteDomain($addon_id)) 
			{					
				$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::$ok = TRUE;
				self::$deleteok = TRUE;
				return true;
			}
		}	 	 
		return false;
    	}
    
    	static function n_sanitize($data)
    	{
        	$data = trim($data);
        	$data = stripslashes($data);
        	$data = htmlspecialchars($data);
        	return $data;
    	}
	
	static function doEditDomain()
    	{
		global $controller;
        	runtime_csfr::Protect();
        	$currentuser = ctrl_users::GetUserDetail();
        	$formvars = $controller->GetAllControllerRequests('FORM');
        	foreach (self::ListDomains($currentuser['userid']) as $row) {
            		if (isset($formvars['inDelete_' . $row['id']])) {
                		header("location: ./?module=" . $controller->GetCurrentModule() . '&show=Delete&other=' . $row['id']);
                		exit;
            		}
            		if (isset($formvars['inEdit_' . $row['id']])) {
                		header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Edit&other=' . $row['id']);
               		 	exit;
            		}
        	}
        	return true;
	}
	
    	static function doConfirmDeleteDomain()
    	{
        	global $controller;
		global $zdbh;
		$formvars = $controller->GetAllControllerRequests('FORM');
		if(isset($formvars['flagswitchuser']) && $formvars['flagswitchuser']!="")
	 	{
			$getvals=explode("|",$formvars['flagswitchuser']);
			$domain_id=$getvals[0];
			$user_id=$getvals[1];
			$user_name=$getvals[2];				
		
			// getting Old Details for move the files
			$sql = $zdbh->prepare(" Select * from x_vhosts where vh_id_pk='".$domain_id."'");
        		$sql->execute();
			$colget=$sql->fetch();
			$old_directory=$colget['vh_directory_vc'];
			$old_user_id=$colget['vh_acc_fk'];
			$old_domain_name=$colget['vh_name_vc'];
		
			$sql = $zdbh->prepare(" Select * from x_accounts where ac_id_pk='".$old_user_id."'");
        		$sql->execute();
			$colget=$sql->fetch();
			$old_username=$colget['ac_user_vc'];
		
                	$hosted_dir=ctrl_options::GetOption('hosted_dir');	
			passthru(" touch $hosted_dir".$user_name."/public_html/;");
		
			$src_path="";
			$dest_path="";
			if($old_directory=="/")
			{
				$src_path=$hosted_dir.$old_username."/public_html";
				$dest_path=$hosted_dir.$user_name."/public_html/";
			}
			else
			{
				$src_path=$hosted_dir.$old_username."/public_html".$old_directory;
				$dest_path=$hosted_dir.$user_name."/public_html/";	
			}	
			$cmd="mv -f ".$src_path."  ".$dest_path;
			passthru($cmd);
		
			// ///////////////////////// Update the new user id Start //////////////////////////////
		
			/* update the virtual host domain */
			$sql = $zdbh->prepare(" update x_vhosts set vh_acc_fk='".$user_id."' WHERE vh_id_pk='".$domain_id."'");
        		$sql->execute();
		
			/* update the dns record */
			
			$sql = $zdbh->prepare(" update x_dns set dn_acc_fk='".$user_id."' WHERE dn_name_vc='".$old_domain_name."'");
        		$sql->execute();
		
			/* Update the mailbox details */
		
			$sql = $zdbh->prepare(" update x_mailboxes set mb_acc_fk='".$user_id."' WHERE mb_address_vc LIKE '%".$old_domain_name."%'");
        		$sql->execute();
		
		
			// /////////////////////////////////// Update the new user id  End ///////////////////////////////////
			
			//passthru("mv -f /var/sentora/hostdata/zadmin/public_html/ajiththht_in /var/sentora/hostdata/reselleruser/public_html/");
	
			// /////////////////////////////////// update the  httpd-vhost file Start ///////////////////////////////////
			$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();
			}
			// ////////////////////////////// update the  httpd-vhost file End ///////////////////////////////////
		
			passthru("php /etc/sentora/panel/bin/daemon.php");	
		
			self::$ok_switch = TRUE;
			return true;
		 
	 	}
	 	else
	 	{
        		runtime_csfr::Protect();
        		$currentuser = ctrl_users::GetUserDetail();
        		$formvars = $controller->GetAllControllerRequests('FORM');
        		foreach (self::ListDomains($currentuser['userid']) as $row) {
            			if (isset($formvars['inDelete_' . $row['id'] . ''])) {
                			header("location: ./?module=" . $controller->GetCurrentModule() . "&show=Delete&id=" . $row['id'] . "&domain=" . $row['name'] . "");
                			exit;
            			}
        		}		
        		return false;
	 	}
	 
	}

    	static function getisDeleteDomain()
    	{
        	global $controller;
        	$urlvars = $controller->GetAllControllerRequests('URL');
        	return (isset($urlvars['show'])) && ($urlvars['show'] == "Delete");
    	}
	
	static function getisEditDomain()
    	{
        	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 getEditID()
    	{
        	global $controller;
        	$id = $controller->GetControllerRequest('URL', 'other');
        	return ($id) ? $id : '';
    	}
	
	static function getEditCurrentDomain()
    	{
        	global $controller;
        	if ($controller->GetControllerRequest('URL', 'other')) {
            		$current = self::ListCurrentDomain($controller->GetControllerRequest('URL', 'other'));
            		return $current[0]['currentdomain'];
        	} else {
            		return '';
        	}
    	}
	
	static function ListCurrentDomain($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 doUpdateDomain()
	{
		global $controller;
		runtime_csfr::Protect();
		$currentuser = ctrl_users::GetUserDetail();
		$formvars = $controller->GetAllControllerRequests('FORM');
		if (self::ExecuteUpdateDomain($formvars['inSave'], $formvars['inDir'], $formvars['inDestination']))
		self::$updateok = true;	
		//self::$ok = true;
		return true;
	}
	
	static function ExecuteUpdateDomain($mid, $indir, $path)
    	{
		global $zdbh;
		global $controller;
		$currentuser = ctrl_users::GetUserDetail();
		$path = trim($path);
		try
		{
			$service_domain_port = 4444 ;
			$address_domain = gethostbyname('localhost');
			$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if ($socket_domain === false)
			{
				socket_close($socket_domain);
				self::$tryagain=true;
				return false;
			}
			else 
			{
			$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
					if ($result === false) 
					{		
						socket_close($socket_domain);
						self::$tryagain=true;
						return false;
						
					}

			}
		}
		catch(Exception $e)
		{
				self::$tryagain=true;
				return false;
		}
		socket_close($socket_domain);
		if($path == "")
		{
			$destination = "/" . $indir;
		}
		else
		{
			$destination = "/" . $path;
		}
		
			$vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . $destination . "/";
		//echo $destination; exit;
		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();
		$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();
		}
				try
		{
			/* //////////////////////////////////////  Java File Path Added //////////////////////////////////////  */
					$vhost_path = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . $destination . "/";
					$sql_tomcat = $zdbh->prepare("SELECT * FROM x_java_version");
					$sql_tomcat->execute();
					$row_tomcat= $sql_tomcat->fetch();
					// $java_file_path=$row_java['x_file_path'];
					$java_domain_full_path=$vhost_path;
					$tomcat_path=$row_tomcat['x_file_path'];
				    $vhost_numrows = $zdbh->prepare("select vh_name_vc FROM x_vhosts WHERE vh_id_pk=:mid");
					$vhost_numrows->bindParam(':mid', $mid);
					$vhost_numrows->execute();
					$get_vhosts=$vhost_numrows->fetch();
					$java_domain_name=$get_vhosts['vh_name_vc'];
					$service_domain_port = 4444 ;
					$address_domain = gethostbyname('localhost');
					$socket_domain = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
					if ($socket_domain === false)
					{
						self::$tryagain=true;
						return false;
					}
					else 
					{
					$result = socket_connect($socket_domain, $address_domain, $service_domain_port);
							if ($result === false) 
							{		
								self::$tryagain=true;
								return false;
							}
							else 
							{
							socket_set_option($socket_domain, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1000, "usec" =>0));
							$in="command Java_Update_Domain $java_domain_name $vhost_path $tomcat_path";
							socket_write($socket_domain, $in, strlen($in));		
							socket_close($socket_domain);
							}
					}
					/* //////////////////////////////////////  Java File Path End //////////////////////////////////////  */
		}
		catch(Exception $e)
		{
			self::$tryagain=true;
			return false;
			
		}
		self::SetWriteApacheConfigTrue();
		self::$ok = true;
		self::SetCallDaemon();
		return;
		
	}
	
	static function getUserName($uid)
    	{
		$currentuser = ctrl_users::GetUserDetail($uid);
		return $currentuser['username'];
    	}
	
    	static function getCurrentDomain()
    	{
        	global $controller;
        	$domain = $controller->GetControllerRequest('URL', 'domain');
        	return ($domain) ? $domain : '';
    	}

    	static function getDomainUsagepChart()
    	{
        	$currentuser = ctrl_users::GetUserDetail();
        	$maximum = $currentuser['domainquota'];
        	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('domains', $currentuser['userid']) - 1;
            		$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 getDomainStatusHTML($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('Please wait We are creating domain in apache level.  This can take maximum 2 mins after that it will be live.') . '">'
                    		. '<img src="/modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/help_small.png" border="0" /></a>';
        	}
    	}

    	static function getResult()
    	{
		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::$dirnotexists)) {
            		return ui_sysmessage::shout(ui_language::translate("Directory does not exists. Kindly create a Directory try after that."), "zannounceerror");
        	}
        	if (!fs_director::CheckForEmptyValue(self::$blank)) {
            		return ui_sysmessage::shout(ui_language::translate("Your Domain can not 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::$nosub)) {
            		return ui_sysmessage::shout(ui_language::translate("You cannot add a Sub-Domain here. Please use the Subdomain manager to add Sub-Domains."), "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::$okk)) {
                        return ui_sysmessage::shout(ui_language::translate("Addon Domain has been created successfully."), "zannounceok");
                }
		if (!fs_director::CheckForEmptyValue(self::$deleteok)) 
		{
			return ui_sysmessage::shout(ui_language::translate("Addon 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");
        	}
		/* if (!fs_director::CheckForEmptyValue(self::$okk)) {
            		return ui_sysmessage::shout(ui_language::translate("Addon Domain successfully Created."), "zannounceok");
        	} */
        	if (!fs_director::CheckForEmptyValue(self::$ok_switch)) {
            		return ui_sysmessage::shout(ui_language::translate("Domain switch over the user successfully."), "Domain Ok");
        	}		
        	return;
    	}
 
	static function auto_dns($domainName)
	{
		global $zdbh;
        	$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', $currentuser['userid']);
        	$gsql->bindParam(':domainName', $domainName);
		$gsql->execute();
		$res=$gsql->fetch();
		$domainID=$res['vh_id_pk'];
		$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', $currentuser['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);
		}
		$uid = $currentuser['userid'];
		self::DKIMConfig($uid,$domainName,$domainID);
		$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();
		}			
		return;
	}
	
	static function remove_space($str)
        {
                $str = trim(preg_replace('/\s+/','', $str));
                return $str;
        }

        static function trim_space($str)
        {
                $str = trim(preg_replace('/\s+/',' ', $str));
                return $str;
        }
        
        static function getspfip()
        {
                global $controller;
                global $zdbh;
                $main_cf_path           ="/etc/postfix/main.cf";
                $postfix_ip_detail      = "";
                $smtp_bind              = "smtp_bind_address";
                $smtp_bind_len          = strlen($smtp_bind);
                $data                   = shell_exec("eval grep '$smtp_bind' ".$main_cf_path );
                if(strlen(self::remove_space($data)) > 0 )
                {
                        $ip_array       = array_filter(explode("\n",$data));
                        $count_d        = count($ip_array);
                        for($i = 0; $i < $count_d; $i++)
                        {
                                $str = self::remove_space($ip_array[$i]);
                                if(strlen($str) > $smtp_bind_len )
                                {
                                        if (stripos($str,$smtp_bind) !== false )
                                        {
                                                if(strtolower($str[0] =="s"))
                                                {
                                                        $exp = explode("=",$str);
                                                        $postfix_ip =$exp[1];
                                                        if(filter_var($postfix_ip,FILTER_VALIDATE_IP ))
                                                        {
                                                                $postfix_ip_detail      = $postfix_ip;
                                                        }
                                                }
                                        }
                                }
                        }
                }
                $n_postfix_ip   = self::remove_space($postfix_ip_detail);
                $original_ip    =  ctrl_options::GetSystemOption('server_ip');
                if(filter_var($n_postfix_ip,FILTER_VALIDATE_IP ))
                {
                        $stmt3 = $zdbh->prepare("select public_ip from x_serverip where priv_ip =:privip and ip_deleted IS NULL ");
                        $stmt3->bindParam(':privip', $n_postfix_ip);
                        $stmt3->execute();
                        $row_count3 = $stmt3->rowCount();
                        if($row_count3 >0)
                        {
                                $rows=$stmt3->fetch();
                                $original_ip = $rows['public_ip'];
                        }
                }
                return $original_ip;
        }
	
	static function DKIMConfig($uid,$domainName,$domainID)
    	{
        	global $zdbh;
        	global $controller;
	
        	$retval = FALSE;
		$currentuser = ctrl_users::GetUserDetail($uid);
		/*==============================SOCKET FOR DKIM==============================*/
		$domain=$domainName;
		$spfip = self::getspfip();
		$time = time();
		$type_newspf = "TXT";
		$defspf = "@";
		$ip = ctrl_options::GetSystemOption('server_ip');
		$targetspf ="v=spf1 a mx mx:".$domain." ip4:".$spfip." ~all";
		$sql1="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 (
								   '".$uid."','"
								   .$domainName."','"
								   .$domainID."','"
								   .$type_newspf."','"
								   .$defspf."','3600','"
								   .$targetspf."','0','0','0','"
								   .$time."')";
		$sql2 = $zdbh->prepare($sql1);
		$sql2->execute();
		$type_newspf = "TXT";
		$defspf = "_dmarc";
		$targetspf ="v=DMARC1; p=none;";
		$sql_dmarc="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 (
									   '".$uid."','"
									   .$domainName."','"
									   .$domainID."','"
									   .$type_newspf."','"
									   .$defspf."','3600','"
									   .$targetspf."','0','0','0','"
									   .$time."')";
		$sql_dmarc_exe = $zdbh->prepare($sql_dmarc);
		$sql_dmarc_exe->execute();
		try
		{
			$service_port = 4444 ;
			$address = gethostbyname('localhost');
			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			$result = socket_connect($socket, $address, $service_port);
			
			$in="command installDKIM $domainName";
			$out = '';
			socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 100, "usec" =>0));
			socket_write($socket, $in, strlen($in));
			$output = "" ;
			$out = socket_read($socket, 2048);
			$output .= $out ;
			if ($out)
			{
				socket_close($socket);
				if(file_exists("/etc/opendkim/keys/".$domainName."/default.txt"))
				{
					$myfile = fopen("/etc/opendkim/keys/".$domainName."/default.txt", "r") ;
					$line = fread($myfile,filesize("/etc/opendkim/keys/$domainName/default.txt"));
					fclose($myfile);
					$data=explode('"',$line);
					$join =$data[1].$data[3];
					$target=str_replace(" ","",$join);
					$time = time();
					$type_new = "TXT";
					$def = "default._domainkey";
						
					$sql="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 (
								   '".$uid."','"
								   .$domainName."','"
								   .$domainID."','"
								   .$type_new."','"
								   .$def."','3600','"
								   .$target."','0','0','0','"
								   .$time."')";
																
					$sql1 = $zdbh->prepare($sql);
					$sql1->execute();
					$retval = TRUE;
					
				}
				
			}
			//echo $output;
		}
		catch(Exception $e)
		{
				
		}
                   		
		/*==============================END==============================*/
		echo "DKIM \n";
		return $retval;
	}		
    /**
     * Webinterface sudo methods.
     */	 
}