Current File : //etc/zpanel/panel/modules/emailspamcheck/code/controller.ext.php
<?php
/**
 *
 * Apache Log Viewer for ZPanel 10.1.0
 * Version : 101
 * Author :  Aderemi Adewale (modpluz @ ZPanel Forums)
 * Email : goremmy@gmail.com
 */
$spfDkim = new module_controller;
$spfDkim->GetDkimRecord('hostingraja.info');
class module_controller {

    static $logfile;
    static $error;
    static $ok;
    static $password;
    static $alreadyexists;
    static $validemail;
    static $noaddress;
    static $editmailbox;
    static $update;
    static $delete;
    static $create;
    static $badpassword;
    static $f_quota;
    static $final_result;

    /**
     * The 'worker' methods.
     */



   /* Load CSS and JS files */
    static function getInit() {
        global $controller;
        $line = '<link rel="stylesheet" type="text/css" href="modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/logviewer.css">';
        $line .= '<script type="text/javascript" src="modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/logviewer.js"></script>';
        return $line;
    }



    static function getCSFR_Tag() {
        return runtime_csfr::Token();
    }

    static function getModuleName() {
        $module_name = ui_module::GetModuleName();
        return $module_name;
    }

    static function getModuleIcon() {
        global $controller;
        $module_icon = "/modules/" . $controller->GetControllerRequest('URL', 'module') . "/assets/icon.png";
        return $module_icon;
    }

 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 getModuleDesc() {
        $message = ui_language::translate(ui_module::GetModuleDescription());
        return $message;
    }
    /*
     * Sangeeth Code Start
     * Getting Domain List
     */
    
    static function getDomains() {
        global $zdbh,$controller;
        
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
		
        $sql = "SELECT vh_directory_vc,vh_name_vc,vh_id_pk FROM x_vhosts WHERE vh_acc_fk=:user_id AND vh_deleted_ts IS NULL AND vh_type_in IN (1,2) ORDER BY vh_name_vc ASC";
        $bindArray = array(':user_id' => $currentuser['userid']);                                        
        $zdbh->bindQuery($sql, $bindArray);
        $rows = $zdbh->returnRows(); 

        if (count($rows) > 0) {
            $res = array();
            foreach($rows as $row) {
                $selected_yn = '';
                if(isset($formvars['domain_id'])){
                    $selected_yn = ($formvars['domain_id'] == $row['vh_id_pk']) ? 'selected="selected"':'';
                }
            
                array_push($res, array(
                    'selected' => $selected_yn,
                    'name' => $row['vh_name_vc'],
                    'id' => $row['vh_id_pk'],
                ));
            }
            return $res;
        } else {
            return false;
        }
    }
    /*
     * add mail Box function
     */
    static function doCheckSpamMail() {
        global $controller;
        runtime_csfr::Protect();
        $currentuser 	= ctrl_users::GetUserDetail();
        $formvars 	= $controller->GetAllControllerRequests('FORM');
	$mail_addr	= "checkmail";
	$password ="qaz!Xsw*eD@0987";
	$quota= "10";
	$domain = $formvars['domain_id'];
        //if (self::ExecuteAddMailbox($currentuser['userid'], $formvars['inAddress'], $formvars['inDomain'], $formvars['inPassword'],$formvars['inQuota']))
	if (self::ExecuteAddMailbox($currentuser['userid'], $mail_addr, $domain, $password, $quota))
            self::$ok = true;
    }
    /*
     * execute add mail Box function
     */
    static function ExecuteAddMailbox($uid, $address, $domain, $password,$quota) {
	global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail($uid);
        $uid = $currentuser['userid'];
        /*$query = "SELECT * from x_password_strength WHERE ps_user_vc='$uid'";
        $res = $zdbh->prepare($query);
        $res->execute();
        $results = $res->rowCount();*/
        if (fs_director::CheckForEmptyValue(self::CheckCreateForErrors($address, $domain, $password,$quota))) {
            return false;
        }
        runtime_hook::Execute('OnBeforeCreateMailbox');
        /*if($results == 0) {
           if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password)) {
                self::$badpassword = true;
                return false;
           }
        */ $address = strtolower(str_replace(' ', '', $address));
    	   $fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
           self::$create = true;
           // Include mail server specific file here.
           //$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
	   $MailServerFile = ctrl_options::GetSystemOption('sentora_root') .'modules/mailboxes/code/' . ctrl_options::GetSystemOption('mailserver_php');
           if (file_exists($MailServerFile))
           	include($MailServerFile);

            $sql = "INSERT INTO x_mailboxes (mb_acc_fk,
						 mb_address_vc,mb_quota,
						 mb_created_ts) VALUES (
						 :userid,
						 :fulladdress,
						 :mb_quota,
						 :time)";
            $time = time();
	    $sql = $zdbh->prepare($sql);
            $sql->bindParam(':time', $time);
            $sql->bindParam(':userid', $currentuser['userid']);
            $sql->bindParam(':mb_quota',$quota);
            $sql->bindParam(':fulladdress', $fulladdress);

            $sql->execute();
            runtime_hook::Execute('OnAfterCreateMailbox');
	    $result = self::SendTestMailtoGmail($domain, $fulladdress, $password);
            self::$ok = true;
            self::$final_result=$result; 
	    return true;
            //return $result;
        /*}
        while($rows=$res->fetch())
        {
            $values= ($rows['ps_eaenabled_in'] == 0 ) ? "0" : "1";
            if($values == 0)
            {
                if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password))
             	{
             		self::$badpassword = true;
             		return false;
           	}
        	$address = strtolower(str_replace(' ', '', $address));
        	$fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
        	self::$create = true;
        	// Include mail server specific file here.
        	//$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
		$MailServerFile = ctrl_options::GetSystemOption('sentora_root') .'modules/mailboxes/code/' . ctrl_options::GetSystemOption('mailserver_php');
        	if (file_exists($MailServerFile))
            		include($MailServerFile);

        	$sql = "INSERT INTO x_mailboxes (mb_acc_fk,
							 mb_address_vc,mb_quota,
							 mb_created_ts) VALUES (
							 :userid,
							 :fulladdress,
							 :mb_quota,
							 :time)";
        	$time = time();
		$sql = $zdbh->prepare($sql);
        	$sql->bindParam(':time', $time);
        	$sql->bindParam(':userid', $currentuser['userid']);
                $sql->bindParam(':mb_quota',$quota);
        	$sql->bindParam(':fulladdress', $fulladdress);

        	$sql->execute();
        	runtime_hook::Execute('OnAfterCreateMailbox');
		self::SendTestMailtoGmail($domain, $fulladdress, $password);
                //echo $sendmail_res;exit;
        	self::$ok = true;
        	return true;
            }
            else
               if($values == "1")
               {
            		$address = strtolower(str_replace(' ', '', $address));
            		$fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
            		self::$create = true;
            		// Include mail server specific file here.
            		//$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
			$MailServerFile = ctrl_options::GetSystemOption('sentora_root') .'modules/mailboxes/code/' . ctrl_options::GetSystemOption('mailserver_php');
            		if (file_exists($MailServerFile))
            			include($MailServerFile);

            		$sql = "INSERT INTO x_mailboxes (mb_acc_fk,
								 mb_address_vc,mb_quota,
								 mb_created_ts) VALUES (
								 :userid,
								 :fulladdress,
								 :mb_quota,
								 :time)";
            		$time = time();
            		$sql = $zdbh->prepare($sql);
            		$sql->bindParam(':time', $time);
            		$sql->bindParam(':userid', $currentuser['userid']);
            		$sql->bindParam(':mb_quota',$quota);
            		$sql->bindParam(':fulladdress', $fulladdress);

            		$sql->execute();
			runtime_hook::Execute('OnAfterCreateMailbox');
			self::SendTestMailtoGmail($domain, $fulladdress, $password);
			//echo $sendmail_res;exit;
			self::$ok = true;
            		return true;
    		}
	}*/
    }
    /*
     * show result
     */
    static function getShowFullLog() {
	if(self::$final_result) {
		$line 		= "<pre style='white-space: pre-wrap;'>";
		$res 		= self::$final_result;
		$folder 	= $res['FOLDER'];
		$spf_res 	= $res['SPF_RESULT'];
		$dkim_res 	= $res['DKIM_RESULT'];
		$dmarc_res	= $res['DMARC_RESULT'];
		$smtp_res	= $res['SMTP_RESULT'];
		
		$line   .= "EMAIL RECEIVED IN : ".$folder."\n\n";
		if($spf_res != 'SPF_PASS') {
			$spf_res = explode('=>',$spf_res);
			$spf_ret = $spf_res[0];
			$spf_rec = $spf_res[1];
			if($spf_ret =='SPF_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL') {
				$spf_res = "SPF STATUS: FAIL.\n SPF record is not updated properly. Please try to add the following record in your name server.\n".$spf_rec."\n\n";
			} else {
				$spf_res = "SPF STATUS: FAIL.\n SPF record was updated successfully. It will take 2-24 hours to propogate\n\n";
			}
			$line	.= $spf_res;
		} else {
			$line 	.= "SPF RESULT: PASS\n\n";
		}
		if($dkim_res != 'DKIM_PASS') {
                        $dkim_res = explode('=>',$dkim_res);
                        $dkim_ret = $dkim_res[0];
                        $dkim_rec = $dkim_res[1];
			if($dkim_ret =='DKIM_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL') {
                                $dkim_res = "DKIM STATUS: FAIL.\n DKIM record is not updated properly. Please try to add the following record in your name server.\n".$dkim_rec."\n\n";
                        } else {
                                $dkim_res = "DKIM STATUS: FAIL.\n DKIM record was updated successfully. It will take 2-24 hours to propogate\n\n";
                        }
                        $line   .= $dkim_res;
                } else {
                        $line   .= "DKIM RESULT: PASS\n\n";
                } 
                $line   .= "DMARC RESULT: ".$dmarc_res."\n\n";
		$line	.= "SMTP BANNER RESULT: ".$smtp_res."\n\n";
		$line 	.="</pre>";
		//return "<pre>".print_r(self::$final_result)."</pre>"; 
		return $line;
	} else {
		return "";
	}
    }
    /*
     * sending mail to gmail
     */
    static function SendTestMailtoGmail($dom, $email, $password)
    {
	global $controller;
	//echo "Check Email send with detaisl $dom, $email, $password \n";
	ob_start();
	$mx_ma = dns_get_record($dom, DNS_MX);
	$mx_mail = $mx_ma[0]['target'];
	//$mx_mail = $dom;
	$php_mailer = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/class.phpmailer.php' ;
	$smtp_class = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/class.smtp.php';
	require_once($php_mailer);
	require_once($smtp_class);
	$mail = new PHPMailer(); // create a new object
	$mail->IsSMTP(); // enable SMTP
	$mail->SMTPDebug =  true; // debugging: 1 = errors and messages, 2 = messages only
	$mail->SMTPAuth = true; // authentication enabled
	//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
	$mail->SMTPSecure = ''; // secure transfer enabled REQUIRED for Gmail
	$mail->Host = $mx_mail;
	$mail->Port = 587; // or 25
	$mail->IsHTML(true);
	#$mail->SMTPSecure = 'tls';
	$mail->Username = $email;
	$mail->Password = 'qaz!Xsw*eD@0987';
	$mail->SetFrom($email);
	$date = date("Y-m-d H:i:s");
	$Subject = "Test Mail From HRPANEL - Checking Mail sending for the site $dom on $date";
	$mail->Subject = $Subject;
	$mail->Body    = 'Hi this is Mail sending checking mail from HRPANEL.';
	$mail->AddAddress("aisa.hostingraja@gmail.com");
	if(!$mail->Send()) {
		$return = "EMAIL_SENT_FAILED_TO_GMAIL.==>".$mail->ErrorInfo;
		return $return;
	} else {
		echo "SMTP Email send \n";
		sleep(10);
		$mail_subject = $Subject;
		$inbox_or_spam = "spam";
		//$mail_subject = 'Test Mail From HRPANEL - Checking Mail sending for the site hostingraja.info on 2018-03-05 11:11:14';
		//$mail_subject = 'Test Mail From HRPANEL - Checking Mail sending for the site hostingraja.info on 2018-03-06 16:34:47';
		$result=array();
		$result = self::CheckGmailSpam($mail_subject, $inbox_or_spam);
		$i=1;
		while(!$result && $i<=5) {
			$result = self::CheckGmailSpam($mail_subject, $inbox_or_spam);	
			$i++;
		} 
		self::ExecuteDeleteMailbox($email);
                $dns_nameserver_check = self::getDnsNameServerRecord($dom);
		if($dns_nameserver_check == 'NOT_POINTING_WITH_US') {
			$return_msg 	= "_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL";
		} else {
			$return_msg	= "_TXT_RECORD_UPDATED_SUCCESSFULLY";
		}	
		if($result['SPF_RESULT'] == 'SPF_FAIL') {
			//$spf_record = self::getSpfRecord($dom);
			$spf_record 	= self::addSpfTxtRecord($dom);
			$spf_record    	= explode("=>",$spf_record);
			$spf_record    	= $spf_record[1];
			//$return 	= "SPF_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL=>".$spf_record;
			$spf_return 	= "SPF".$return_msg."=>".$spf_record;
			echo $spf_return;//exit;
		} else {
			$spf_return = "SPF_PASS";
		} 
		if($result['DKIM_RESULT'] == 'DKIM_FAIL') {
			//$dkim_record 	= self::getDkimRecord($dom);
			$dkim_record	= self::addDkimTxtRecord($dom);
			$dkim_record	= explode("=>",$dkim_record);
			$dkim_record	= $dkim_record[1];
			//$return 	= "DKIM_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL=>".$dkim_record;
			$dkim_return         = "DKIM".$return_msg."=>".$dkim_record;
			echo $dkim_return;//exit;
		} else {
			$dkim_return = "DKIM_PASS";
		}
		if($result['DMARC_RESULT'] == 'DMARC_FAIL') {
			//$dkim_record = self::getDkimRecord($dom);
			//$return = "DKIM_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL=>".$dkim_record;
			$dmarc_return = "FAIL";
		} else {
			$dmarc_return = "PASS";
		}
		$smtp_banner_check = self::smtpBannerCheck();
		if($smtp_banner_check != 'SMTP_BANNER_PROPERLY_CONFIGURED') {
			$add_smtp_banner_res = self::addSmtpBanner();
			if($add_smtp_banner_res == 'SMTP_BANNER_SUCCESSFULLY_CONFIGURED') {
				$smtp_return = 'SMTP BANNER SUCCESSFULLY CONFIGURED';
			} else {
				$smtp_return 	= '';
			}
		} else {
			$smtp_return = "PASS";
		}
		//return "EMAIL_SEND_TO_CLIENT_SUCCESSFULLY.==>".$Subject;
		$return = array("FOLDER"=>$result['FOLDER'], "SPF_RESULT"=>$spf_return, "DKIM_RESULT"=>$dkim_return, "DMARC_RESULT"=>$dmarc_return,"SMTP_RESULT"=>$smtp_return);
		return $return;
	}
    }
    /*
     * smtp banner configuration checking
     */
    static function smtpBannerCheck()
    {
            $whereis_grep       = trim(shell_exec('whereis grep | awk \'{print $2}\''));
            $smtpd_banner_check = $whereis_grep.' "smtpd_banner" /etc/postfix/main.cf | awk \'{print $3}\'';
            $smtpd_banner_value = trim(shell_exec($smtpd_banner_check));
            if($smtpd_banner_value == 'ESMTP')
            {
                $return = "SMTP_BANNER_NOT_PROPERLY_CONFIGURED";
            }
            else if($smtpd_banner_value === '$myhostname')
            {
                $return = "SMTP_BANNER_PROPERLY_CONFIGURED";
            }
            else
            {
                $return = "SMTP_BANNER_NOT_PROPERLY_CONFIGURED";
            }
            return $return;
    }

    static function addSmtpBanner()
    {
          //  $whereis_sed         = trim(shell_exec('whereis sed | awk \'{print $2}\''));
          //  $add_smtp_banner_cmd = $whereis_sed.' -i "s/^\(smtpd_banner\).*/\1 = \$myhostname ESMTP Postfix/" /etc/postfix/main.cf';
          //  shell_exec($add_smtp_banner_cmd);
          //  shell_exec('service postfix restart');
	  self::commandcreation("command addSmtpBanner");  
          return "SMTP_BANNER_SUCCESSFULLY_CONFIGURED";
    }
    /*
     * socket connection
     */
    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);
    }  	

    /*
     * getting spf and dkim results from gmail
     */
    static function CheckGmailSpam($mail_subject, $inbox_or_spam) {
	//$inbox_or_spam = "inbox";
	define('AISA_GMAIL_PASSWORD','Aisa.hostingraja@20171!');
	$mail_subject = trim($mail_subject);
	if($inbox_or_spam == 'spam') {
		$hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Spam';
	} else {
		$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
	}
	//$hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Spam';
	//$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
	$username = 'aisa.hostingraja@gmail.com';
	$password = AISA_GMAIL_PASSWORD;
	/* try to connect */
	$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
	/* grab emails */
	$emails = imap_search($inbox, 'All');
	//$mailboxes = imap_list($inbox, $hostname, '*');
	$spf_result = "";
	$dkim_result = "";
	$dmarc_result = "";
	if($emails) {
		/* put the newest emails on top */
		rsort($emails);
		/* for every email... */
		$output = '';
		$count = 1;
		$spam_mail = false;
		$return = array();
		foreach($emails as $email_number) {
			/* get information specific to this email */
			$overview = imap_fetch_overview($inbox,$email_number,0);
			$message = imap_fetchbody($inbox,$email_number,0);
			$email_subject = trim($overview[0]->subject);
			if($email_subject == $mail_subject) {
				$spam_mail	= true;
				$folder		= strtoupper($inbox_or_spam);
				$spf_result     = self::spfCheck($message);
				$dkim_result    = self::dkimCheck($message);
				$dmarc_result   = self::dmarcCheck($message);
				$return = array("FOLDER"=>$folder,"SPF_RESULT"=>$spf_result,"DKIM_RESULT"=>$dkim_result,"DMARC_RESULT"=>$dmarc_result);
				break;
			}
			//$header = preg_replace("/=(\r?)\n/", '', imap_fetchbody($inbox, $email_number,0));
			//print_r($header);exit;
		}
		if(!$spam_mail && $inbox_or_spam == 'spam') {
			$return = self::CheckGmailSpam($mail_subject, 'inbox');
			return $return;
		}

		//$return = array("SPF_RESULT"=>$spf_result,"DKIM_RESULT"=>$dkim_result,"DMARC_RESULT"=>$dmarc_result);
		return $return;
	}
    }  
    /*
     * get spf result
     */
    static function spfCheck($message) {
    	$spf = strpos($message,"spf=");
        if($spf) {
     		$spf_result = substr($message,$spf+4,4);
                if($spf_result == "pass" ) {
                    $spf_return = "SPF_PASS";
                } else if($spf_result == "neut") {
                    $spf_return = "SPF_NEUTRAL";
                } else {
                    $spf_return = "SPF_FAIL";
                }
                return $spf_return;
         } else {
                return "SPF_NOT_FOUND";
         }
    }
    /*
     * get dkim result
     */
     static function dkimCheck($message) {
            $dkim = strpos($message,"dkim=");
            if($dkim) {
                $dkim_result = substr($message,$dkim+5,4);
                if($dkim_result == "pass") {
                    $dkim_return = "DKIM_PASS";
                } else if($dkim_result == "neut") {
                    $dkim_return = "DKIM_NEUTRAL";
                } else {
                    $dkim_return = "DKIM_FAIL";
                }
                return $dkim_return;
            } else {
                return "DKIM_NOT_FOUND";
            }
     }
     /*
     * get dkim result
     */
     static function dmarcCheck($message) {
            $dmarc = strpos($message,"dmarc=");
            if($dmarc) {
                $dmarc_result = substr($message,$dmarc+6,4);
                if($dmarc_result == "pass") {
                    $dmarc_return = "DMARC_PASS";
                } else if($dmarc_result == "neut") {
                    $dmarc_return = "DMARC_NEUTRAL";
                } else {
                    $dmarc_return = "DMARC_FAIL";
                }
                return $dmarc_return;
            } else {
                return "DMARC_NOT_FOUND";
            }
    }
    /*
     * checking name server is pointing with our server or not
     */
    static function getDnsNameServerRecord($domain_name) {
            $name_server = dns_get_record($domain_name, DNS_NS);
            foreach($name_server as $ns_record) {
                $ns_ptr     = $ns_record['target'];
                $ns_host    = gethostbyname($ns_record['target']);
                $domain_host= gethostbyname($domain_name);
                if($ns_host == $domain_host) {
                    //echo $ns_ptr." and ".$domain_name." Both are using same ".$ns_host."\n";		    
                    $return = 'POINTING_WITH_US';
                } else {
                    //echo $ns_ptr." using ".$ns_host." but ".$domain_name." using ".$domain_host."\n";
                    $return = 'NOT_POINTING_WITH_US';
                    return $return;
                }
            }
            return $return;
    }
    /*
     * genrerate and add dkim
     */
    static function addDkimTxtRecord($domain_name) {
	global $zdbh;
	/*$return = $this->getDnsNameServerRecord($domain_name);
	if($return == false)
	{
		$dkim_record = $this->getDkimRecord($domain_name);
		return DKIM_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL.":".$dkim_record;
	}*/
	$dkim_sql = $zdbh->prepare("SELECT count(*) AS count FROM x_dns WHERE dn_host_vc='default._domainkey' AND dn_type_vc='TXT' AND dn_name_vc=:domain AND dn_deleted_ts IS NULL");
	$dkim_sql->bindParam(':domain', $domain_name);
	$dkim_sql->execute();
	$results = $dkim_sql->fetch();
	$sh_path = trim(shell_exec("whereis sh | awk '{print $2}'"));
	//$sh_path = explode(" ",$sh_path_check);
	//$sh_path = $sh_path[1];
	$cmnd_exe_dkim = shell_exec("$sh_path /root/dkim.sh $domain_name");
	$filename = "/etc/opendkim/keys/".$domain_name."/default.txt";
	if (!file_exists($filename)) {
		return "CANNOT_ADD_DKIM";
	}
	$myfile = fopen("/etc/opendkim/keys/".$domain_name."/default.txt", "r");
	$line = fread($myfile,filesize("/etc/opendkim/keys/$domain_name/default.txt"));
	fclose($myfile);
	$data=explode('"',$line);
	$join =$data[1].$data[3];
	$target=str_replace(" ","",$join);
	$time = time();
	$def = "default._domainkey";
	$res = self::getDomainDetails($domain_name);
	if($res) {
	   $vh_acc_fk = $res['vh_acc_fk'];
	   $x_domain_id = $res['x_domain_id'];
	   if ($results['count'] == 0) {
		$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 ('".$vh_acc_fk."','".$domain_name."','".$x_domain_id."','TXT','".$def."','3600','".$target."','0','0','0','".$time."')";

		$sql = $zdbh->prepare($sql);
		$sql->execute();
		$inserted_dns_id = $zdbh->lastInsertId();
		if($inserted_dns_id) {
			shell_exec("service named restart");
			$return = "DKIM_ADDED=>".$target;
		} else {
			$return = "CANNOT_ADD_DKIM";
		}
		//$opendkim = shell_exec("service opendkim restart");
	   } else {
		$update_sql="UPDATE x_dns SET dn_target_vc=:dn_target_vc, dn_ttl_in='3600' WHERE dn_host_vc='default._domainkey' AND dn_type_vc='TXT' AND dn_name_vc=:domain AND dn_deleted_ts IS NULL";
		$update_sql = $zdbh->prepare($update_sql);
		$update_sql->bindParam(':domain', $domain_name);
		$update_sql->bindParam(':dn_target_vc', $target);
		$update_sql->execute();
		//$dkim_update_id =  $update_sql->rowCount();
		if($update_sql->execute()) {
			shell_exec("service named restart");
			$return = "DKIM_ADDED=>".$target;
		} else {
			$return = "CANNOT_UPDATE_DKIM";
		}
	    }
	}
	echo "DKIM TXT change return : $return\n";
	return $return;
    }
    /*
     * add spf text record
     */
    static function addSpfTxtRecord($domain_name) {
	global $zdbh;
	/*$return = $this->getDnsNameServerRecord($domain_name);
	if($return == false) {
		$spf_record = $this->getSpfRecord($domain_name);
		return SPF_TXT_NEED_TO_ADD_IN_USER_CONTROL_PANEL.":".$spf_record;
	}*/
	$res = self::getDomainDetails($domain_name);
	$vh_acc_fk = $res['vh_acc_fk'];
	$x_domain_id = $res['x_domain_id'];
	$spf_sql = $zdbh->prepare("SELECT count(*) AS count FROM x_dns WHERE dn_host_vc='@' AND dn_type_vc='TXT' AND dn_name_vc=:domain AND dn_deleted_ts IS NULL");
	$spf_sql->bindParam(':domain', $domain_name);
	$spf_sql->execute();
	$result = $spf_sql->fetch();
	$ip = ctrl_options::GetSystemOption('server_ip');
	$targetspf ="v=spf1 a mx mx:".$domain_name." ip4:".$ip." ~all";
	if ($result['count'] == 0) {
		$time = time();
		$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 ('".$vh_acc_fk."', '".$domain_name."', '".$x_domain_id."', 'TXT', '@','3600', '".$targetspf."','0','0','0', '".$time."')";
		$sql = $zdbh->prepare($sql);
		$sql->execute();
		$inserted_dns_id = $zdbh->lastInsertId();
		if($inserted_dns_id) {
			shell_exec("service named restart");
			$return = "SPF_ADDED=>".$targetspf;
		} else {
			$return = "CANNOT_ADD_SPF";
		}
	} else {
		$sql = "UPDATE x_dns SET dn_target_vc='".$targetspf."',dn_ttl_in='3600' WHERE dn_host_vc='@' AND dn_type_vc='TXT' AND dn_name_vc='".$domain_name."' AND dn_deleted_ts IS NULL";
		$update_sql = $zdbh->prepare($sql);
		$update_res = $update_sql->execute();	
		if($update_res) {
			shell_exec("service named restart");
			$return = "SPF_UPDATED=>".$targetspf;
		} else {
			$return = "CANNOT_UPDATE_SPF";
		}
	}
	echo "SPF Added result : $return \n";
	return $return;
    }
    /*
     * get domain details
     */
    static function getDomainDetails($domain_name) {
	global $zdbh;
	$sql = $zdbh->prepare("SELECT a.vh_acc_fk, b.x_domain_id FROM x_vhosts as a JOIN x_main_domain as b ON (a.vh_acc_fk = b.x_user_id) WHERE a.vh_name_vc =:domain");
        $sql->bindParam(':domain', $domain_name);
        $sql->execute();
        $res = $sql->fetchAll();
        if($res) {
        	$return = $res;
        } else {
                return false;
        }
        return $return;
    }
    /*
     * delete mailbox
     */
    static function ExecuteDeleteMailbox($email_id)
    {
	global $zdbh;
	global $controller;
	runtime_hook::Execute('OnBeforeDeleteMailbox');
	self::$delete = true;

	$numrows = $zdbh->prepare("SELECT * FROM x_mailboxes WHERE mb_address_vc like '".$email_id."' AND mb_deleted_ts is NULL");
	$numrows->execute();
	$row_count2 = $numrows->rowCount();
	if($row_count2 >0)
	{
		$rowmailbox = $numrows->fetch();
	// Include mail server specific file here.

		$MailServerFile = ctrl_options::GetSystemOption('sentora_root') .'modules/mailboxes/code/' . ctrl_options::GetSystemOption('mailserver_php');
		if (file_exists($MailServerFile)) {
			include($MailServerFile);
		}
		$time = time();
		$ip_deleted =self::get_client_ip();
		//$sql = "UPDATE x_mailboxes SET ip_deleted=:ip_deleted,mb_deleted_ts=:time WHERE mb_id_pk=:mid";
		$sql = "UPDATE x_mailboxes SET ip_deleted=:ip_deleted,mb_deleted_ts=:time WHERE mb_address_vc like '".$email_id."'";
		$sql = $zdbh->prepare($sql);
		$sql->bindParam(':time', $time);
		$sql->bindParam(':ip_deleted', $ip_deleted);
		//$sql->bindParam(':mailid', $email_id);
		$sql->execute();

		//$auto_email = $rowmailbox['mb_address_vc'];
		$auto_file_path = "/var/spool/autoresponse/responses/".$auto_email;
		if (file_exists($auto_file_path))
		{

			$currentuser = ctrl_users::GetUserDetail();
			$suid = $currentuser['userid'];
			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_mail like'".$email_id."'  and vh_acc_fk =:sid ");
				$stmt4->bindParam(':str_time',$current_str_time);
				$stmt4->bindParam(':sid',$suid);
				$stmt4->bindParam(':vhid',$email_id);
				//$stmt4->bindParam(':vhid',$auto_email);
				$stmt4->execute();
				/*********$affected_rows = $stmt4->rowCount(); *************/

			}
		}
	}
	runtime_hook::Execute('OnAfterDeleteMailbox');
	self::$ok = true;
    }
    /*
     * get client ip
     */
    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;
    }  
    /*
     * validations
     */
    static function CheckCreateForErrors($address, $domain, $password,$quota)
    {
        global $zdbh;
        $fulladdress = strtolower(str_replace(' ', '', $address . '@' . $domain));
        if (fs_director::CheckForEmptyValue($address)) {
            self::$noaddress = true;
            return false;
        }
        if (fs_director::CheckForEmptyValue($password)) {
            self::$password = true;
            return false;
        }
        if (!self::IsValidEmail($fulladdress)) {
            self::$validemail = true;
            return false;
        }
        $sql = "SELECT * FROM x_mailboxes WHERE mb_address_vc=:fulladdress AND mb_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
        $sql = "SELECT * FROM x_forwarders WHERE fw_address_vc=:fulladdress AND fw_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
        $sql = "SELECT * FROM x_distlists WHERE dl_address_vc=:fulladdress AND dl_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
	    return false;
        }
        $sql = "SELECT * FROM x_aliases WHERE al_address_vc=:fulladdress AND al_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }

        if (fs_director::CheckForEmptyValue($quota)) {
            self::$f_quota = true;
            return false;
        }

        return true;
    }
    /*
     * checking for the valid mail
     */
    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;
    }
    /*
     * get dkim record
     */
    static function getDkimRecord($domain_name)
    {
	$dkim = dns_get_record("default._domainkey.".$domain_name."", DNS_TXT);
	$return = $dkim ? $dkim[0]['txt'] : "NO_DKIM_RECORD_FOUND";
	return $return;
    }
    /*
     * get spf record
     */
    static function getSpfRecord($domain_name)
    {
	$return = "";
	$spf = dns_get_record($domain_name, DNS_TXT);
	foreach($spf as $record)
	{
		foreach($record as $key=>$row)
		{
			if($key =='txt')
			{
				if(strpos($row,"spf") !== false)
				{
					$return = $row;
				}
				else {
					continue;
				}
			}
			else
			{
				continue;
			}
		}
	}
	return $return;
    }
    /*
     * Sangeeth Code End
     */
    static function getErrorTypes(){
        global $controller;
        
        $formvars = $controller->GetAllControllerRequests('FORM');
        
        $error_types = array(1=>'Access Logs', 2=>'Error Logs');
        $res = array();
        foreach($error_types as $row_idx=>$row){
            $selected_yn = '';
            if(isset($formvars['log_type_id'])){
                $selected_yn = ($formvars['log_type_id'] == $row_idx) ? 'selected="selected"':'';
            }
            array_push($res, array(
                    'id' => $row_idx,
                    'name' => $row,
                    'selected' => $selected_yn,
                ));
        }
        
        return $res;
    }
    
    static function getErrorType(){
        global $controller;
        
        $formvars = $controller->GetAllControllerRequests('FORM');
        $log_type = '';
        
        if(isset($formvars['log_type_id']) && (int) $formvars['log_type_id']){
           if($formvars['log_type_id'] == 1){
               $log_type = ui_language::translate("Access Logs");
           } elseif($formvars['log_type_id'] == 2){
               $log_type = ui_language::translate("Error Logs");
           }
        
        }
        return $log_type;
    }


    static function getisDisplayLogs(){
        global $controller;
        
        $urlvars = $controller->GetAllControllerRequests('URL');
        $formvars = $controller->GetAllControllerRequests('FORM');

        if((isset($urlvars['action']) && $urlvars['action'] == 'DisplayLogs')){
            return true;
        }
        return false;
    }
    
    
    static function doDisplayLogs(){
        global $controller, $zdbh;
        
        $formvars = $controller->GetAllControllerRequests('FORM');
        self::$logfile = '';

        runtime_csfr::Protect();
        if((int) $formvars['domain_id'] && (int) $formvars['log_type_id']){
            $currentuser = ctrl_users::GetUserDetail();
            $log_dir = ctrl_options::GetSystemOption('hosted_dir').'domains/' . $currentuser['username'];
            $log_dir = str_replace('hostdata', 'logs', $log_dir);
            $log_dir = fs_director::ConvertSlashes($log_dir);
            
            if(is_dir($log_dir)){
         		$sql = "SELECT vh_name_vc FROM x_vhosts 
					        WHERE vh_id_pk=:vh_id AND vh_acc_fk=:uid AND vh_deleted_ts IS NULL";
                $bindArray = array(':vh_id' => (int)$formvars['domain_id'], ':uid' => $currentuser['userid']);
                $zdbh->bindQuery($sql, $bindArray);
                $domain_info = $zdbh->returnRow();
                
                if($formvars['log_type_id'] == 1){
                    $log_file = 'access.log';
                } elseif($formvars['log_type_id'] == 2){
                    $log_file = 'error.log';
                }
                
                if(!isset($log_file) || !$domain_info['vh_name_vc']){
                    self::$error['no_log_exist'] = true;
                    return false;                    
                }
                
                $log_path = $log_dir.'/'.$domain_info['vh_name_vc'].'-'.$log_file;
                $log_path = fs_director::ConvertSlashes($log_path);
                
                if(!is_file($log_path)){
                    self::$error['no_log_exist'] = true;
                    return false;                    
                }
                
                self::$logfile = $log_path;
                self::$ok = true;
                return true;

            } else {
                self::$error['no_log_exist'] = true;
                return false;
            }
        
        } else {
            self::$error = true;
            return false;
        }
    
    }
    
    static function getLogFile(){
        if(isset(self::$logfile) && self::$logfile != ''){
            $log_output = '';
            
            $log_content = file(self::$logfile);
            if(is_array($log_content) && count($log_content) > 1){
                foreach($log_content as $log){
                    $log_output .= $log.'<br><br>';
                }
            } else {
                $log_output = ui_language::translate("There are no log items to display.");
            }
            return $log_output;
        }
        
        return false;
    }


    static function getResult() {
        if (isset(self::$error['no_log_exist']) && !fs_director::CheckForEmptyValue(self::$error['no_log_exist'])) {
            return ui_sysmessage::shout(ui_language::translate("Unable to locate log file for the selected domain."), "zannounceerror");
        }
        
        if (!fs_director::CheckForEmptyValue(self::$error)) {
            return ui_sysmessage::shout(ui_language::translate("An error has occurred while executing your request, please check your input and try again."), "zannounceerror");
        }
	if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate('A mailbox, alias, forwarder or distribution list already exists with that name.'), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$validemail)) {
            return ui_sysmessage::shout(ui_language::translate("Your email address is not valid."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$password)) {
            return ui_sysmessage::shout(ui_language::translate("Your password cannot be blank."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$noaddress)) {
            return ui_sysmessage::shout(ui_language::translate("Your email address cannot be blank."), "zannounceerror");
        }
                if (!fs_director::CheckForEmptyValue(self::$f_quota)) {
            return ui_sysmessage::shout(ui_language::translate("Mailbox quota cannot be blank."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("Changes to your mailboxes have been saved successfully!"), "zannounceok");
        }
        if (!fs_director::CheckForEmptyValue(self::$badpassword)) {
            return ui_sysmessage::shout(ui_language::translate("Your password did not meet the minimun length requirements.Characters needed for password length : 9 with atleast 1 uppercase,lowercase,special character.number"), "Error");
        }
        return;
    }

    /**
     * Webinterface sudo methods.
     */
}

?>