Current File : //etc/zpanel/panel/modules/ssl/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 $del;
	static $validemail;
    static $badpointing;
    
	static function getCreatedDomain()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return self::ListDomain($currentuser['userid']);
    }
	
	static public function doSslList()
    {
        global $zdbh;
        global $controller;

        $currentuser = ctrl_users::GetUserDetail();
		$check_ssl = "SELECT * FROM x_ssl WHERE ssl_status=0 AND ssl_delete IS NULL AND userid=:userid";
		$numcheck = $zdbh->prepare($check_ssl);
		$numcheck->bindParam(':userid', $currentuser['userid']);
		$numcheck->execute();
		$check_num = $numcheck->fetchColumn();
		
		if ($check_num > 0) {
			$check_ssl = $zdbh->prepare($check_ssl);
            $check_ssl->bindParam(':userid', $currentuser['userid']);
            $check_ssl->execute();
			while ($row_domain = $check_ssl->fetch()) {
				echo "<h2>Note: Still your SSL Certificate for ".$row_domain['ssl_doamin']." installation is Processing.. Please Wait...</h2>";
			}
		} 
		
		$sql = "SELECT * FROM x_ssl WHERE ssl_status=1 AND ssl_delete IS NULL AND userid=:userid";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);
        $numrows->execute();
		
		if ($numrows->fetchColumn() > 0) {
		
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':userid', $currentuser['userid']);
            $res = array();
            $sql->execute();
			
			$line .= "<h2>" . ui_language::translate("Current SSl Certificate") . "</h2>";
			$line .='<form action="./?module=ssl&action=ConfirmDeleteSsl" method="post">';
			$line .= "<table>";
			$line .= '<tr><th>Domain</th></tr>';
			while ($rowdomain = $sql->fetch()) {
                $listdomain = $rowdomain['ssl_doamin'];
				$listid = $rowdomain['ssl_no'];		
				$line .= '<tr><td>'.$listdomain.'</td><td><button class="button-loader delete btn btn-danger" type="submit" id="button" name="inDelete_'.$listid.'" id="inDelete_'.$listid.'" value="inDelete_'.$listid.'" >Delete</button></td>';
		
				$file = fopen("/var/log/letsencrypt/$listdomain.log", "r");
				$op = fgets($file);
				$op = str_replace("\n",'',$op); 
				if($op != 'completed'){
					$line .='<td><a href="javascript:void(0);" target="_blank" onClick="showLog();">Check Log</a></td></tr><tr><td Id="show_log"></td></tr>';
			
				}
				else
				{
					$line .='</tr>';
				}
				fclose($file);
				$line .="";
				$op = '';
			}
			$line .= '</table>';
			$line .='</form>';
			echo $line;
			exit;
        } else {
			echo "You currently do not have any SSl Certificate. Create a SSl Certificate using the form below.";
			exit;
        }
    }
	
	static function doshowLogcontent()
	{
	
		$listdomain=$_POST['listdomain'];
		echo file_get_contents("/var/log/letsencrypt/letsencrypt.log");
		fclose($file);
	exit;
	}
 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 ListDomain($uid)
    {
        global $zdbh;
        global $controller;
			
        $currentuser = ctrl_users::GetUserDetail($uid);
		$sql = "SELECT * FROM x_ssl WHERE ssl_delete IS NULL AND userid=:userid";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);
        $numrows->execute();
		
        if ($numrows->fetchColumn() > 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':userid', $currentuser['userid']);
            $res = array();
            $sql->execute();
			
            while ($rowdomain = $sql->fetch()) {
                $res[] = array('list' => $rowdomain['ssl_doamin'], 
							   'subid' => $rowdomain['ssl_no']);		
            }
            return $res;
        } else {
            return false;
        }
    }
	
	static function doConfirmDeleteSsl()
    {
        global $controller;
       
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListDomain($currentuser['userid']) as $row) {
		
            if (isset($formvars['inDelete_' . $row['subid'] . ''])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Delete&id=' . $row['subid'] . '&domain=' . $row['list']);
                exit;
            }
        }
        return false;
    }
		static function commandcreation($in)
	{
	$service_port = 4444;
	$address = gethostbyname('localhost');
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($socket === false) {
		self::$error= TRUE;
		return FALSE;
	} 
        $result = socket_connect($socket, $address, $service_port);
        if ($result === false) {
			self::$error= TRUE;
			return FALSE;
        } 
				socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 2000, "usec" =>0));
                $out = '';
                socket_write($socket, $in, strlen($in));
				socket_close($socket);
				sleep(1);
	}
	
	static function changepermissionstart($java_file_path){
	self::commandcreation("command permissionstarttomcat $java_file_path");
	return;
	}
	static function changepermissionend($java_file_path){
	 self::commandcreation("command permissionendtomcat $java_file_path");
	
	return;
	}
	static function deploy($java_file_path){
	self::commandcreation("command deploytomcat $java_file_path");
	return;
	}
	static function tomcatrestart()
	{
	self::commandcreation("command restarttomcat");
	return;
	}
	
	static function getisDeleteDomain()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == 'Delete');
    }
	
	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 doDeleteSslDomain()
    {
		print_r($_POST);
		echo $_POST['inDelete'];
        global $controller;
        if (isset($_POST['inDelete'])) {
            if (self::ExecuteDeleteSslDomain($_POST['inDelete'])) {
                self::$del = TRUE;
                return true;
            }
        }
        return false;
    }
	
	static function ExecuteDeleteSslDomain($id)
    {
        global $zdbh;
        $sql = $zdbh->prepare("UPDATE x_ssl
							   SET ssl_delete=:time
							   WHERE ssl_no=:id");
        $time = time();
        $sql->bindParam(':time', $time);
        $sql->bindParam(':id', $id);
        $sql->execute();
  
		
		$sql = $zdbh->prepare("SELECT ssl_doamin FROM x_ssl WHERE ssl_no=:id");
		$sql->bindParam(':id', $id);
		$sql->execute();
		$row = $sql->fetch();
		// $domain = $row['ssl_doamin'];	
		
		$sql = $zdbh->prepare("SELECT * FROM x_java_version");
		$sql->execute();
		$row_java = $sql->fetch();
		$java_file_path=$row_java['x_file_path'];     

		self::changepermissionstart($java_file_path);
		self::deploy($java_file_path);
		self::changepermissionend($java_file_path);
		self::$ok= TRUE;
		self::tomcatrestart();
				
			/*==============================Socket==============================*/
			/* $service_port = 4444 ;
				$address = gethostbyname('localhost');
				$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				$result = socket_connect($socket, $address, $service_port);
				
				$in="command deleteSSL $domain";
				$out = '';
				socket_write($socket, $in, strlen($in));
				  $output = "" ;
		
                		 while(true)
                		{
                		sleep(5);
                		$out = socket_read($socket, 2048);
                		$output .= $out ;
                		if ($out)
						{
						socket_close($socket);
						self::SslConfig();
						break ;
						}
                		}
                		echo $output;
                   		*/
						
				/*==============================END==============================*/
				      $retval = TRUE;
        return $retval;
    }
	
	
    static function doCreateSSL()
    {
	
		global $controller;
		print_r($_POST); 
		if (isset($_POST['inDomain'])) {
            if (self::ExecuteCreateSSL($_POST['inDomain'],$_POST['wwwoption'],$_POST['httpscheck'])) {
                self::$ok = TRUE;
                return true;
            }
			else {
            return false;
        }
        }
		
        return;
	}
	
	static function ExecuteCreateSSL($domain,$wwwoption,$httpscheck)
    {
		
        global $zdbh;
		global $controller;
        $retval = FALSE;
		$currentuser = ctrl_users::GetUserDetail();
		
			$sql = $zdbh->prepare("SELECT ac_email_vc FROM x_accounts WHERE ac_id_pk=:id AND ac_deleted_ts IS NULL");
			$sql->bindParam(':id', $currentuser['userid']);
			$sql->execute();
			$row = $sql->fetch();
			$email = $row['ac_email_vc'];
			echo $email;
		
		if (!self::IsValidEmail($email)) {
            self::$validemail = true;
            return false;
        }

        if (!fs_director::CheckForEmptyValue(self::CheckCreateForErrors($domain))) {
		
            // If all has gone well we need to now create the domain in the database...
           
			$time = time();
			$uid = $currentuser['userid'];
			$sql = $zdbh->prepare("INSERT INTO x_ssl (userid, ssl_email, ssl_doamin, ssl_created, ssl_status, ssl_httpscheck) VALUES ($uid, '".$email."','".$domain."','".$time."', 0,'".$httpscheck."')");
			$sql->execute();
            $retval = TRUE;
			exit;
			return $retval;
		}
        
    }
	
	static function doSslSock()
    {
		global $controller;
		print_r($_POST); 
			if (isset($_POST['inDomain'])) {
				if (self::ExecuteSslSock($_POST['inDomain'],$_POST['wwwoption'],$_POST['httpscheck'])) {
					self::$ok = TRUE;
					return true;
				}
				else {
				return false;
			}
			}
        return;
	}
	
	
	
	
	static function ExecuteSslSock($domain,$wwwoption,$httpscheck)
    {
        global $zdbh;
        global $controller;
        $retval = FALSE;
		$currentuser = ctrl_users::GetUserDetail();
		if (!fs_director::CheckForEmptyValue(self::CheckCreateForErrors($domain))) {
			
			$sql = $zdbh->prepare("SELECT ac_email_vc FROM x_accounts WHERE ac_id_pk=:id AND ac_deleted_ts IS NULL");
			$sql->bindParam(':id', $currentuser['userid']);
			$sql->execute();
			$row = $sql->fetch();
			$email = $row['ac_email_vc'];
			
				/*==============================Socket==============================*/
						$host_dir =ctrl_options::GetSystemOption('hosted_dir');	
				$sql_vhost = $zdbh->prepare("SELECT vh_directory_vc FROM x_vhosts WHERE  vh_name_vc=:vh_name_vc AND vh_acc_fk=:id AND vh_deleted_ts IS NULL");
			$sql_vhost->bindParam(':vh_name_vc', $domain);
			$sql_vhost->bindParam(':id', $currentuser['userid']);
			$sql_vhost->execute();
			$row_vhost = $sql_vhost->fetch();
			$v_path = $row_vhost['vh_directory_vc'];
			$file_path=$host_dir .$currentuser['username'].$v_path;  	
			
				$service_port = 4444 ;
				$address = gethostbyname('localhost');
				$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				//$accept = socket_accept($socket);
				$result = socket_connect($socket, $address, $service_port);
				//socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" =>0));
				$in="command installjavaSSL $domain $email $wwwoption $file_path";
				$out = '';
				socket_write($socket, $in, strlen($in));
				$output = "" ;
				echo "DONE";
				//$retval = TRUE;
				exit;
		}
			exit;

				/*==============================END==============================*/
		
	}
			
	/*====================================================================================================*/
	static function SslConfig()
    {
        global $zdbh;
        global $controller;
        $retval = FALSE;
		
			$line="";
     		$vhconfigfile = '/etc/httpd/conf.d/ssl.conf';

			$sql1 = "SELECT COUNT(*) FROM x_ssl WHERE ssl_delete IS NULL";
			$numrows = $zdbh->query($sql1);
			$count = $numrows->fetchColumn();
			
		if ($count > 0) {
		
			$line  = fs_filehandler::NewLine();
			$line .= "#". fs_filehandler::NewLine();
			$line .= "LoadModule ssl_module modules/mod_ssl.so". fs_filehandler::NewLine();
			$line .= "Listen 443". fs_filehandler::NewLine();
			$line .= "SSLProtocol all -SSLv2 -SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2". fs_filehandler::NewLine();
			$line .= "SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES:!RC4". fs_filehandler::NewLine();
			$line .= "SSLPassPhraseDialog  builtin". fs_filehandler::NewLine();		
			$line .= "SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)". fs_filehandler::NewLine();
			$line .= "SSLSessionCacheTimeout  300". fs_filehandler::NewLine();
			$line .= "Mutex default". fs_filehandler::NewLine();
			$line .= "SSLRandomSeed startup file:/dev/urandom  256". fs_filehandler::NewLine();
			$line .= "SSLRandomSeed connect builtin". fs_filehandler::NewLine();
			$line .= "##". fs_filehandler::NewLine();
		
			
		
			$currentuser = ctrl_users::GetUserDetail();
		//	$sql = $zdbh->prepare("SELECT * FROM x_vhosts WHERE vh_enabled_in=1 AND vh_deleted_ts IS NULL AND vh_name_vc IN (select ssl_doamin from x_ssl where ssl_delete IS NULL) ORDER BY vh_name_vc ASC");
			// $sql->bindParam(':userid', $currentuser['userid']);
			$sql = $zdbh->prepare("SELECT a.*,b.ac_user_vc FROM x_vhosts a,x_accounts b  WHERE a.vh_enabled_in=1 AND a.vh_deleted_ts IS NULL AND a.vh_acc_fk=b.ac_id_pk AND a.vh_name_vc IN (select ssl_doamin from x_ssl where ssl_delete IS NULL) ORDER BY a.vh_name_vc ASC");
			$sql->execute();
			$first = 1;
			
			while($row = $sql->fetch()) {  
				
				$domain_name = $row['vh_name_vc'];
				$getcurrentuser = $row['ac_user_vc'];
				$vh_directory_vc = $row['vh_directory_vc'];
				if($first == 1) {
					$line .= "<VirtualHost _default_:443>". fs_filehandler::NewLine();
				}
				else {
					$line .= "<VirtualHost *:443>". fs_filehandler::NewLine();
				}
				$line .= fs_filehandler::NewLine();
				$line .="ServerAlias www.".$domain_name."". fs_filehandler::NewLine();
				$line .="ServerName ".$domain_name."". fs_filehandler::NewLine();
				//$line .='DocumentRoot "/var/sentora/hostdata/'.$dc_root.'/public_html/"'. fs_filehandler::NewLine();
				
				$phpVersion="";
				$sql_php = "SELECT * FROM x_phpversion_upgrade WHERE x_client_id=:userid ";
				$numrows_php = $zdbh->prepare($sql_php);
				$numrows_php->bindParam(':userid', $row['vh_acc_fk']);
				echo $numrows_php->execute();
				if ($numrows_php->fetchColumn() > 0) {
				$numrows_php1 = $zdbh->prepare($sql_php);
				$numrows_php1->bindParam(':userid', $row['vh_acc_fk']);
				$numrows_php1->execute();
				$res=$numrows_php1->fetch();
				$phpVersion=$res['x_php_version'];
				}else
				{
					if(version_compare(phpversion(),"5.5")==1)
					{
						$phpVersion="php56";
					}else
					{
						$phpVersion="php53";
					}
				
				}
			
				$RootDir = '"' . ctrl_options::GetSystemOption('hosted_dir') . $getcurrentuser . $vh_directory_vc. '"';
				$line .= 'DocumentRoot ' . $RootDir . fs_filehandler::NewLine();
				$checkversion="";
				if(version_compare(phpversion(),"5.5")==1)
				{
				$checkversion="php56";
				}else
				{
				$checkversion="php53";
				}
				if($phpVersion!=$checkversion)
				{
				$line .= '<FilesMatch \.php$>'.fs_filehandler::NewLine();
				$line .= 'SetHandler fcgid-script'.fs_filehandler::NewLine();
				$line .= '</FilesMatch>'.fs_filehandler::NewLine();
				}
				$line .= '<Directory ' . $RootDir . '>' . fs_filehandler::NewLine();
				
				//$line .='<Directory "/var/sentora/hostdata/'.$dc_root.'/public_html/">'. fs_filehandler::NewLine();
				if($phpVersion===$checkversion)
				{
				$line .= "  Options +FollowSymLinks -Indexes" . fs_filehandler::NewLine();
				}else
				{
				  $line .= "  Options +FollowSymLinks -Indexes +ExecCGI" . fs_filehandler::NewLine();
				  $line .= "  AddHandler fcgid-script .php" . fs_filehandler::NewLine();
				  $line .= "  FCGIWrapper /var/www/php-fcgi-scripts/".$phpVersion."/php-fcgi-starter .php" . fs_filehandler::NewLine();
				}
				
				$line .="AllowOverride All". fs_filehandler::NewLine();
				$line .="Require all granted". fs_filehandler::NewLine();
				$line .="</Directory>". fs_filehandler::NewLine();
				$line .="DirectoryIndex index.html index.htm index.php index.asp index.aspx index.jsp index.jspa index.shtml index.shtm". fs_filehandler::NewLine();
				$line .= "ErrorLog logs/ssl_error_log". fs_filehandler::NewLine();
				$line .= "TransferLog logs/ssl_access_log". fs_filehandler::NewLine();
				$line .= "LogLevel warn". fs_filehandler::NewLine();
				$line .= "SSLEngine on". fs_filehandler::NewLine();
				$line .= "SSLProtocol all -SSLv2 -SSLv3". fs_filehandler::NewLine();
				$line .= "SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES". fs_filehandler::NewLine();
				$line .= "SSLCertificateFile /etc/letsencrypt/live/".$domain_name."/cert.pem". fs_filehandler::NewLine();
				$line .= "SSLCertificateKeyFile /etc/letsencrypt/live/".$domain_name."/privkey.pem". fs_filehandler::NewLine();
				$line .= "SSLCertificateChainFile /etc/letsencrypt/live/".$domain_name."/chain.pem". fs_filehandler::NewLine();
				$line .= '<Files ~ "\.(cgi|shtml|phtml|php3?)$">'. fs_filehandler::NewLine();
				$line .= "SSLOptions +StdEnvVars". fs_filehandler::NewLine();
				$line .= "</Files>". fs_filehandler::NewLine();
				$line .= '<Directory "/var/www/cgi-bin">'. fs_filehandler::NewLine();
				$line .= "SSLOptions +StdEnvVars". fs_filehandler::NewLine();
				$line .= "</Directory>". fs_filehandler::NewLine();
				$line .= 'BrowserMatch "MSIE [2-5]" \\'. fs_filehandler::NewLine();
				$line .= "nokeepalive ssl-unclean-shutdown \\". fs_filehandler::NewLine();
				$line .= "downgrade-1.0 force-response-1.0". fs_filehandler::NewLine();
				$line .= "CustomLog logs/ssl_request_log \\". fs_filehandler::NewLine();
				$line .= '"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"'. fs_filehandler::NewLine();
				$line .= "</VirtualHost>". fs_filehandler::NewLine();
				$line .= fs_filehandler::NewLine();
		
				$vhconfigfile = '/etc/httpd/conf.d/ssl.conf';
			
				$first++;
			}	
			fs_filehandler::UpdateFile($vhconfigfile, 0777, $line);
		}
	else {
		$line  = fs_filehandler::NewLine();
		$line .= "#kesavan". fs_filehandler::NewLine();
		$line .= "# This is the Apache server configuration file providing SSL support." . fs_filehandler::NewLine();
		$line .= "# It contains the configuration directives to instruct the server how to" . fs_filehandler::NewLine();
		$line .= "# serve pages over an https connection. For detailing information about these ". fs_filehandler::NewLine();
		$line .= "# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>". fs_filehandler::NewLine();
		$line .= "# ". fs_filehandler::NewLine();
		$line .= "# Do NOT simply read the instructions in here without understanding". fs_filehandler::NewLine();
		$line .= "# what they do.  They're here only as hints or reminders.  If you are unsure". fs_filehandler::NewLine();
		$line .= "# consult the online docs. You have been warned.". fs_filehandler::NewLine();
		$line .= "#". fs_filehandler::NewLine();

		$line .= "LoadModule ssl_module modules/mod_ssl.so". fs_filehandler::NewLine();

		$line .= "#". fs_filehandler::NewLine();
		$line .= "# When we also provide SSL we have to listen to the". fs_filehandler::NewLine();
		$line .= "# the HTTPS port in addition." . fs_filehandler::NewLine();
		$line .= "#". fs_filehandler::NewLine();
		$line .= "Listen 443". fs_filehandler::NewLine();

		$line .= "##". fs_filehandler::NewLine();
		$line .= "##  SSL Global Context". fs_filehandler::NewLine();
		$line .= "##". fs_filehandler::NewLine();
		$line .= "##  All SSL configuration in this context applies both to". fs_filehandler::NewLine();
		$line .= "##  the main server and all SSL-enabled virtual hosts.". fs_filehandler::NewLine();
		$line .= "##". fs_filehandler::NewLine();

		$line .= "#   Pass Phrase Dialog:" . fs_filehandler::NewLine();
		$line .= "#   Configure the pass phrase gathering process.". fs_filehandler::NewLine();
		$line .= "#   The filtering dialog program (`builtin' is a internal". fs_filehandler::NewLine();
		$line .= "#   terminal dialog) has to provide the pass phrase on stdout.". fs_filehandler::NewLine();
		$line .= "SSLPassPhraseDialog  builtin". fs_filehandler::NewLine();

		$line .= "#   Inter-Process Session Cache:". fs_filehandler::NewLine();
		$line .= "#   Configure the SSL Session Cache: First the mechanism". fs_filehandler::NewLine();
		$line .= "#   to use and second the expiring timeout (in seconds).". fs_filehandler::NewLine();
		$line .= "SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)". fs_filehandler::NewLine();
		$line .= "SSLSessionCacheTimeout  300". fs_filehandler::NewLine();

		$line .= "#   Semaphore:". fs_filehandler::NewLine();
		$line .= "#   Configure the path to the mutual exclusion semaphore the". fs_filehandler::NewLine();
		$line .= "#   SSL engine uses internally for inter-process synchronization.". fs_filehandler::NewLine();
		$line .= "#SSLMutex default". fs_filehandler::NewLine();

		$line .= "#   Pseudo Random Number Generator (PRNG):". fs_filehandler::NewLine();
		$line .= "#   Configure one or more sources to seed the PRNG of the". fs_filehandler::NewLine();
		$line .= "#   SSL library. The seed data should be of good random quality.". fs_filehandler::NewLine();
		$line .= "#   WARNING! On some platforms /dev/random blocks if not enough entropy". fs_filehandler::NewLine();
		$line .= "#   is available. This means you then cannot use the /dev/random device". fs_filehandler::NewLine();
		$line .= "#   because it would lead to very long connection times (as long as". fs_filehandler::NewLine();
		$line .= "#   it requires to make more entropy available). But usually those". fs_filehandler::NewLine();
		$line .= "#   platforms additionally provide a /dev/urandom device which doesn't". fs_filehandler::NewLine();
		$line .= "#   block. So, if available, use this one instead. Read the mod_ssl User". fs_filehandler::NewLine();
		$line .= "#   Manual for more details.". fs_filehandler::NewLine();
		$line .= "SSLRandomSeed startup file:/dev/urandom  256". fs_filehandler::NewLine();
		$line .= "SSLRandomSeed connect builtin". fs_filehandler::NewLine();
		$line .= "#SSLRandomSeed startup file:/dev/random  512". fs_filehandler::NewLine();
		$line .= "#SSLRandomSeed connect file:/dev/random  512". fs_filehandler::NewLine();
		$line .= "#SSLRandomSeed connect file:/dev/urandom 512". fs_filehandler::NewLine();

		$line .= "#". fs_filehandler::NewLine();
		$line .= '# Use "SSLCryptoDevice" to enable any supported hardware'. fs_filehandler::NewLine();
		$line .= '# accelerators. Use "openssl engine -v" to list supported'. fs_filehandler::NewLine();
		$line .= "# engine names.  NOTE: If you enable an accelerator and the". fs_filehandler::NewLine();
		$line .= "# server does not start, consult the error logs and ensure". fs_filehandler::NewLine();
		$line .= "# your accelerator is functioning properly.". fs_filehandler::NewLine();
		$line .= "#". fs_filehandler::NewLine();
		$line .= "SSLCryptoDevice builtin". fs_filehandler::NewLine();
		$line .= "#SSLCryptoDevice ubsec". fs_filehandler::NewLine();

		$line .= "##". fs_filehandler::NewLine();
		$line .= "## SSL Virtual Host Context". fs_filehandler::NewLine();
		$line .= "##". fs_filehandler::NewLine();
		$line .= "<VirtualHost _default_:443>". fs_filehandler::NewLine();
		$line .= "# General setup for the virtual host, inherited from global configuration". fs_filehandler::NewLine();
		$line .= '#DocumentRoot "/var/www/html"'. fs_filehandler::NewLine();
		$line .= "#ServerName www.example.com:443". fs_filehandler::NewLine();

		$line .= "# Use separate log files for the SSL virtual host; note that LogLevel". fs_filehandler::NewLine();
		$line .= "# is not inherited from httpd.conf.". fs_filehandler::NewLine();
		$line .= "ErrorLog logs/ssl_error_log". fs_filehandler::NewLine();
		$line .= "TransferLog logs/ssl_access_log". fs_filehandler::NewLine();
		$line .= "LogLevel warn". fs_filehandler::NewLine();

		$line .= "#   SSL Engine Switch:". fs_filehandler::NewLine();
		$line .= "#   Enable/Disable SSL for this virtual host.". fs_filehandler::NewLine();
		$line .= "SSLEngine on". fs_filehandler::NewLine();

		$line .= "#   SSL Protocol support:". fs_filehandler::NewLine();
		$line .= "# List the enable protocol levels with which clients will be able to". fs_filehandler::NewLine();
		$line .= "# connect.  Disable SSLv2 access by default:". fs_filehandler::NewLine();
		$line .= "SSLProtocol all -SSLv2". fs_filehandler::NewLine();

		$line .= "#   SSL Cipher Suite:". fs_filehandler::NewLine();
		$line .= "# List the ciphers that the client is permitted to negotiate.". fs_filehandler::NewLine();
		$line .= "# See the mod_ssl documentation for a complete list.". fs_filehandler::NewLine();
		$line .= "#SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES". fs_filehandler::NewLine();

		$line .= "#   Server Certificate:". fs_filehandler::NewLine();
		$line .= "# Point SSLCertificateFile at a PEM encoded certificate.  If". fs_filehandler::NewLine();
		$line .= "# the certificate is encrypted, then you will be prompted for a". fs_filehandler::NewLine();
		$line .= "# pass phrase.  Note that a kill -HUP will prompt again.  A new". fs_filehandler::NewLine();
		$line .= "# certificate can be generated using the genkey(1) command.". fs_filehandler::NewLine();
		$line .= "SSLCertificateFile /etc/pki/tls/certs/localhost.crt". fs_filehandler::NewLine();
				   
		$line .= "#   Server Private Key:". fs_filehandler::NewLine();
		$line .= "#   If the key is not combined with the certificate, use this". fs_filehandler::NewLine();
		$line .= "#   directive to point at the key file.  Keep in mind that if". fs_filehandler::NewLine();
		$line .= "#   you've both a RSA and a DSA private key you can configure". fs_filehandler::NewLine();
		$line .= "#   both in parallel (to also allow the use of DSA ciphers, etc.)". fs_filehandler::NewLine();
		$line .= "SSLCertificateKeyFile /etc/pki/tls/private/localhost.key". fs_filehandler::NewLine();

		$line .= "#   Server Certificate Chain:". fs_filehandler::NewLine();
		$line .= "#   Point SSLCertificateChainFile at a file containing the". fs_filehandler::NewLine();
		$line .= "#   concatenation of PEM encoded CA certificates which form the". fs_filehandler::NewLine();
		$line .= "#   certificate chain for the server certificate. Alternatively". fs_filehandler::NewLine();
		$line .= "#   the referenced file can be the same as SSLCertificateFile". fs_filehandler::NewLine();
		$line .= "#   when the CA certificates are directly appended to the server". fs_filehandler::NewLine();
		$line .= "#   certificate for convinience.". fs_filehandler::NewLine();
		$line .= "#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt". fs_filehandler::NewLine();

		$line .= "#   Certificate Authority (CA):". fs_filehandler::NewLine();
		$line .= "#   Set the CA certificate verification path where to find CA". fs_filehandler::NewLine();
		$line .= "#   certificates for client authentication or alternatively one". fs_filehandler::NewLine();
		$line .= "#   huge file containing all of them (file must be PEM encoded)". fs_filehandler::NewLine();
		$line .= "#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt". fs_filehandler::NewLine();

		$line .= "#   Client Authentication (Type):". fs_filehandler::NewLine();
		$line .= "#   Client certificate verification type and depth.  Types are". fs_filehandler::NewLine();
		$line .= "#   none, optional, require and optional_no_ca.  Depth is a". fs_filehandler::NewLine();
		$line .= "#   number which specifies how deeply to verify the certificate". fs_filehandler::NewLine();
		$line .= "#   issuer chain before deciding the certificate is not valid.". fs_filehandler::NewLine();
		$line .= "#SSLVerifyClient require". fs_filehandler::NewLine();
		$line .= "#SSLVerifyDepth  10". fs_filehandler::NewLine();

		$line .= "#   Access Control:". fs_filehandler::NewLine();
		$line .= "#   With SSLRequire you can do per-directory access control based". fs_filehandler::NewLine();
		$line .= "#   on arbitrary complex boolean expressions containing server". fs_filehandler::NewLine();
		$line .= "#   variable checks and other lookup directives.  The syntax is a". fs_filehandler::NewLine();
		$line .= "#   mixture between C and Perl.  See the mod_ssl documentation". fs_filehandler::NewLine();
		$line .= "#   for more details.". fs_filehandler::NewLine();
		$line .= "#<Location />". fs_filehandler::NewLine();
		$line .= "#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ ". fs_filehandler::NewLine();
		$line .= '#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." '. fs_filehandler::NewLine();
		$line .= '#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} '. fs_filehandler::NewLine();
		$line .= '#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 '. fs_filehandler::NewLine();
		$line .= '#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) '. fs_filehandler::NewLine();
		$line .= '#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/'. fs_filehandler::NewLine();
		$line .= '#</Location>'. fs_filehandler::NewLine();

		$line .= '#   SSL Engine Options:'. fs_filehandler::NewLine();
		$line .= '#   Set various options for the SSL engine.'. fs_filehandler::NewLine();
		$line .= '#   o FakeBasicAuth:'. fs_filehandler::NewLine();
		$line .= '#     Translate the client X.509 into a Basic Authorisation.  This means that'. fs_filehandler::NewLine();
		$line .= '#     the standard Auth/DBMAuth methods can be used for access control.  The'. fs_filehandler::NewLine();
		$line .= "#     user name is the `one line' version of the client's X.509 certificate.". fs_filehandler::NewLine();
		$line .= '#     Note that no password is obtained from the user. Every entry in the user'. fs_filehandler::NewLine();
		$line .= '#     file needs this password: xxj31ZMTZzkVA.'. fs_filehandler::NewLine();
		$line .= "#   o ExportCertData:". fs_filehandler::NewLine();
		$line .= "#     This exports two additional environment variables: SSL_CLIENT_CERT and". fs_filehandler::NewLine();
		$line .= '#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the'. fs_filehandler::NewLine();
		$line .= '#     server (always existing) and the client (only existing when client'. fs_filehandler::NewLine();
		$line .= '#     authentication is used). This can be used to import the certificates'. fs_filehandler::NewLine();
		$line .= '#     into CGI scripts.'. fs_filehandler::NewLine();
		$line .= '#   o StdEnvVars:'. fs_filehandler::NewLine();
		$line .= "#     This exports the standard SSL/TLS related 'SSL_*' environment variables.". fs_filehandler::NewLine();
		$line .= '#     Per default this exportation is switched off for performance reasons,'. fs_filehandler::NewLine();
		$line .= '#     because the extraction step is an expensive operation and is usually'. fs_filehandler::NewLine();
		$line .= '#     useless for serving static content. So one usually enables the'. fs_filehandler::NewLine();
		$line .= '#     exportation for CGI and SSI requests only.'. fs_filehandler::NewLine();
		$line .= '#   o StrictRequire:'. fs_filehandler::NewLine();
		$line .= '#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even'. fs_filehandler::NewLine();
		$line .= '#     under a "Satisfy any" situation, i.e. when it applies access is denied'. fs_filehandler::NewLine();
		$line .= '#     and no other module can change it.'. fs_filehandler::NewLine();
		$line .= '#   o OptRenegotiate:'. fs_filehandler::NewLine();
		$line .= '#     This enables optimized SSL connection renegotiation handling when SSL'. fs_filehandler::NewLine();
		$line .= '#     directives are used in per-directory context.'. fs_filehandler::NewLine();
		$line .= '#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire'. fs_filehandler::NewLine();
		$line .= '<Files ~ "\.(cgi|shtml|phtml|php3?)$">'. fs_filehandler::NewLine();
		$line .= "SSLOptions +StdEnvVars". fs_filehandler::NewLine();
		$line .= "</Files>". fs_filehandler::NewLine();
		$line .= '<Directory "/var/www/cgi-bin">'. fs_filehandler::NewLine();
		$line .= "SSLOptions +StdEnvVars". fs_filehandler::NewLine();
		$line .= "</Directory>". fs_filehandler::NewLine();

		$line .= '#   SSL Protocol Adjustments:'. fs_filehandler::NewLine();
		$line .= "#   The safe and default but still SSL/TLS standard compliant shutdown". fs_filehandler::NewLine();
		$line .= "#   approach is that mod_ssl sends the close notify alert but doesn't wait for". fs_filehandler::NewLine();
		$line .= "#   the close notify alert from client. When you need a different shutdown". fs_filehandler::NewLine();
		$line .= "#   approach you can use one of the following variables:". fs_filehandler::NewLine();
		$line .= "#   o ssl-unclean-shutdown:". fs_filehandler::NewLine();
		$line .= "#     This forces an unclean shutdown when the connection is closed, i.e. no". fs_filehandler::NewLine();
		$line .= "#     SSL close notify alert is send or allowed to received.  This violates". fs_filehandler::NewLine();
		$line .= "#     the SSL/TLS standard but is needed for some brain-dead browsers. Use". fs_filehandler::NewLine();
		$line .= "#     this when you receive I/O errors because of the standard approach where". fs_filehandler::NewLine();
		$line .= "#     mod_ssl sends the close notify alert.". fs_filehandler::NewLine();
		$line .= "#   o ssl-accurate-shutdown:". fs_filehandler::NewLine();
		$line .= "#     This forces an accurate shutdown when the connection is closed, i.e. a". fs_filehandler::NewLine();
		$line .= "#     SSL close notify alert is send and mod_ssl waits for the close notify". fs_filehandler::NewLine();
		$line .= "#     alert of the client. This is 100% SSL/TLS standard compliant, but in". fs_filehandler::NewLine();
		$line .= "#     practice often causes hanging connections with brain-dead browsers. Use". fs_filehandler::NewLine();
		$line .= "#     this only for browsers where you know that their SSL implementation". fs_filehandler::NewLine();
		$line .= "#     works correctly. ". fs_filehandler::NewLine();
		$line .= "#   Notice: Most problems of broken clients are also related to the HTTP". fs_filehandler::NewLine();
		$line .= "#   keep-alive facility, so you usually additionally want to disable". fs_filehandler::NewLine();
		$line .= '#   keep-alive for those clients, too. Use variable "nokeepalive" for this.'. fs_filehandler::NewLine();
		$line .= "#   Similarly, one has to force some clients to use HTTP/1.0 to workaround". fs_filehandler::NewLine();
		$line .= '#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and'. fs_filehandler::NewLine();
		$line .= '#   "force-response-1.0" for this.'. fs_filehandler::NewLine();
		$line .= 'BrowserMatch "MSIE [2-5]" \\'. fs_filehandler::NewLine();
		$line .= "nokeepalive ssl-unclean-shutdown \\". fs_filehandler::NewLine();
		$line .= "downgrade-1.0 force-response-1.0". fs_filehandler::NewLine();
		$line .= fs_filehandler::NewLine();
				
		$line .= "CustomLog logs/ssl_request_log \\". fs_filehandler::NewLine();
		$line .= '"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"'. fs_filehandler::NewLine();
		$line .= "</VirtualHost>". fs_filehandler::NewLine();
		$line .= fs_filehandler::NewLine();
		
			$vhconfigfile = '/etc/httpd/conf.d/ssl.conf';
			fs_filehandler::UpdateFile($vhconfigfile, 0777, $line);
	} 
	
	    $sql = $zdbh->prepare("UPDATE x_settings SET so_value_tx='true' WHERE so_name_vc='apache_changed'");
        $sql->execute();
		$retval = TRUE;
		exit;
		
		return $retval;
	}
			/*=============================================================*/
			
 

	static function CheckCreateForErrors($domain)
    {
	
        global $zdbh;
        global $controller;
        // 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 domain is pointing to this ip or not
        $ip = ctrl_options::GetSystemOption('server_ip');
        $recordresult = dns_get_record($domain , DNS_A);
        foreach($recordresult as $keys=>$values)
        {
            if($values['ip'] != $ip)
            { 
			/* echo "server ".$ip."a".$values['ip'];
            self::$badpointing = TRUE;
            return FALSE;
			exit;
			break; */
			echo "BADPOINTING";
			exit;
            }
        }
        
			$sock_err=0;
			$service_port = 4444 ;
			$address = gethostbyname('localhost');
			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if ($socket === false) {
			echo "SOCKETERR";
			$sock_err=1;
			} 
			$result = socket_connect($socket, $address, $service_port);
			if ($result === false) {
			echo "SOCKETERR";
			$sock_err=1;
			}
			socket_close($socket);
			if($sock_err==1)
			exit;
		
        // 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 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 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 ListDomains($uid)
    {
        global $zdbh;
        $currentuser = ctrl_users::GetUserDetail($uid);
        $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:userid AND vh_enabled_in=1 AND vh_deleted_ts IS NULL AND vh_name_vc NOT IN (select ssl_doamin from x_ssl where ssl_delete IS NULL And userid=:userid) ORDER BY vh_name_vc ASC";
		//$sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:userid AND vh_enabled_in=1 AND vh_deleted_ts IS NULL AND vh_name_vc IN(SELECT ssl_doamin FROM x_ssl WHERE ssl_delete IS NOT NULL) ORDER BY vh_name_vc ASC";
		//$sql = "SELECT x_vhosts.*,x_ssl.ssl_doamin FROM x_vhosts LEFT OUTER JOIN x_ssl ON x_vhosts.vh_name_vc = x_ssl.ssl_doamin";
        //$numrows = $zdbh->query($sql);
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);
        $numrows->execute();
		$domaincount = $numrows->fetchColumn();
        if ($domaincount > 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':userid', $currentuser['userid']);
            $res = array();
            $sql->execute();
            while ($rowdomains = $sql->fetch()) {
                $res[] = array('domain' => ui_language::translate($rowdomains['vh_name_vc']));
            }
            return $res;
        } else {
            return false;
        }
    }
	
	
    static function getDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return self::ListDomains($currentuser['userid']);
    }
	
	static function getEmailList()
    {
        $currentuser = ctrl_users::GetUserDetail();
		return $currentuser['email'];
       // return self::ListEmail($currentuser['userid']);
    }
	
    
    static function getQuotaLimit()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return ($currentuser['mailboxquota'] < 0) or //-1 = unlimited
                ($currentuser['mailboxquota'] > ctrl_users::GetQuotaUsages('mailboxes', $currentuser['userid']));
    }

    
	static function getResult()
    {
        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::$badpointing)) {
            return ui_sysmessage::shout(ui_language::translate("Your Domain name is not pointing to the IP"), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate("Your Domain name is not registred 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::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("SSL Certificate created successfully."), "zannounceok");
        }
		if (!fs_director::CheckForEmptyValue(self::$del)) {
            return ui_sysmessage::shout(ui_language::translate("SSL Certificate deleted successfully."), "zannounceok");
        }
		if (!fs_director::CheckForEmptyValue(self::$validemail)) {
            return ui_sysmessage::shout(ui_language::translate("Your email address is not valid."), "zannounceerror");
        }
        return "";
    }
 	
}