Current File : //root/panel/modules/mail_admin/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 $ok;
	static $tryagain;
	static $main_cf_path = "/etc/postfix/main.cf";
     static function n_sanitize($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    static function getConfig()
    {
        global $zdbh;
        $currentuser = ctrl_users::GetUserDetail();
        $sql = "SELECT * FROM x_settings WHERE so_module_vc=:name AND so_usereditable_en = 'true' ORDER BY so_cleanname_vc";
        //$numrows = $zdbh->query($sql);
        $name = ui_module::GetModuleName();
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':name', $name);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':name', $name);
            $res = array();
            $sql->execute();
            while ($rowmailsettings = $sql->fetch()) {
                if (ctrl_options::CheckForPredefinedOptions($rowmailsettings['so_defvalues_tx'])) {
                    $fieldhtml = ctrl_options::OuputSettingMenuField($rowmailsettings['so_name_vc'], $rowmailsettings['so_defvalues_tx'], $rowmailsettings['so_value_tx']);
                } else {
                    $fieldhtml = ctrl_options::OutputSettingTextArea($rowmailsettings['so_name_vc'], $rowmailsettings['so_value_tx']);
                }
                array_push($res, array('cleanname' => ui_language::translate($rowmailsettings['so_cleanname_vc']),
                    'name' => $rowmailsettings['so_name_vc'],
                    'description' => ui_language::translate($rowmailsettings['so_desc_tx']),
                    'value' => $rowmailsettings['so_value_tx'],
                    'fieldhtml' => $fieldhtml));
            }
            return $res;
        } else {
            return false;
        }
    }
    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 doUpdateConfig()
    {
        global $zdbh;
        global $controller;
        runtime_csfr::Protect();
        $sql = "SELECT * FROM x_settings WHERE so_module_vc=:name AND so_usereditable_en = 'true'";
        //$numrows = $zdbh->query($sql);
        $name = ui_module::GetModuleName();
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':name', $name);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':name', $name);
            $sql->execute();
            while ($row = $sql->fetch()) {
                if (!fs_director::CheckForEmptyValue($controller->GetControllerRequest('FORM', $row['so_name_vc']))) {
                    $updatesql = $zdbh->prepare("UPDATE x_settings SET so_value_tx = :name2 WHERE so_name_vc = :so_name_vc");
                    $name2 = $controller->GetControllerRequest('FORM', $row['so_name_vc']);
                    $updatesql->bindParam(':name2', $name2);
                    $updatesql->bindParam(':so_name_vc', $row['so_name_vc']);
                    $updatesql->execute();
                }
            }
        }
        $formvars = $controller->GetAllControllerRequests('FORM');
        // $tls_detail = 0;
        $smtp_detail = 0;
            if(array_key_exists("smtp_enable",$formvars))
            {
                $smtp_detail = 1;                
            }

           /*  if(array_key_exists("tls_enable",$formvars))
            {
                $tls_detail=1;
            }
      
         $currentuser = ctrl_users::GetUserDetail();
            $suid = $currentuser['userid'];
            $stmt1 = $zdbh->prepare(" select vh_id_pk,vh_name_vc  from  x_vhosts where    vh_deleted_ts  IS NULL AND vh_type_in =1  ");
            
            $stmt1->execute();
            $row_count1 = $stmt1->rowCount();
            if($row_count1 >0)
            {
               
                $dom_array=array();
                while($rows = $stmt1->fetch())
                {
                    array_push($dom_array,$rows['vh_name_vc']);
                }
               
                if(count($dom_array) >0)
                {
                    $domain_name_detail=json_encode($dom_array);
                    $filepath=realpath(dirname(__FILE__))."/tls_detail";

                    $fod = fopen($filepath, "w+") ;
                    if ( !$fod ) {  }
                    else
                    {
                        fwrite($fod,$tls_detail);
                        fclose($fod);
                        
                        if($tls_detail ==1)
                        {
                        $tls_command="command tls 1 ".$domain_name_detail;
                        }
                        else
                        {
                        $tls_command="command tls 0 ".$domain_name_detail;
                        }
                        self::call_socket($tls_command);
                    }
                }
                else
                {
                    $dom_array=array("dummyQWTESesaq");
                    $domain_name_detail=json_encode($dom_array);
                    $tls_command="command tls 0 ".$domain_name_detail;
                    self::call_socket($tls_command);

                }
                       
            }   
            else
            {
                $dom_array=array("dummyQWTESesaq");
                $domain_name_detail=json_encode($dom_array);
                $tls_command="command tls 0 ".$domain_name_detail;
                self::call_socket($tls_command);
            }
           */ 
            if($smtp_detail == 1)
            {
                $smtp_command="command smtpport 1 ";
                self::call_socket($smtp_command);
            }
            else
            {
                $smtp_command="command smtpport 0 ";
                self::call_socket($smtp_command);            
            }
        




	if(array_key_exists("ipdetail",$formvars) && ((!filter_var($formvars['ipdetail'], FILTER_VALIDATE_IP) === false) || $formvars['ipdetail'] == 1))
	{
                $n_ip  = self::n_sanitize($formvars['ipdetail']);
		$ip = ctrl_options::GetSystemOption('server_ip');
		if ($n_ip == 1)
		{
			$original_ip = $ip;
		}
		else
		{
			$stmt3 = $zdbh->prepare("select public_ip from x_serverip where priv_ip =:privip and ip_deleted IS NULL ");
			$stmt3->bindParam(':privip', $n_ip);
			$stmt3->execute();
			$row_count3 = $stmt3->rowCount();
			if($row_count3 >0)
			{
				$rows=$stmt3->fetch();
				$original_ip = $rows['public_ip'];
			}
		}
		if (filter_var($original_ip, FILTER_VALIDATE_IP))
		{
			if($n_ip == 1) 	{ $n_ipd = "command mailip 1"; }
			else { 	$n_ipd="command mailip 2 ".$n_ip; }
			self::call_socket($n_ipd);	
			$stmt4 = $zdbh->prepare("select dn_id_pk,dn_name_vc from x_dns where dn_type_vc ='TXT' and dn_host_vc ='@' and  dn_deleted_ts IS NULL");
			$stmt4->execute();
			$row_count4 = $stmt4->rowCount();
			if($row_count4 > 0)
			{
				while($rows=$stmt4->fetch())
				{
					$t_id_detail	= $rows['dn_id_pk'];
					$t_dom_detail 	= $rows['dn_name_vc'];
					$new_txt_detail = "v=spf1 a mx mx:".$t_dom_detail." ip4:".$original_ip." ~all";
					$stmt5 = $zdbh->prepare("update x_dns set dn_target_vc =:dn_dom_data where dn_id_pk =:dn_id");
					$stmt5->bindParam(":dn_dom_data",$new_txt_detail);
					$stmt5->bindParam(":dn_id",$t_id_detail);
					$stmt5->execute();
				}
			}
		}
	}
        self::$ok = true;
    }
    
    static function call_socket($command_detail)
    {

	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" => 1, "usec" =>0));
        	sleep(3);
        
        	$out = '';
        	socket_write($socket, $command_detail, strlen($command_detail));
        	socket_close($socket);
	}
	catch(Exception $e)
	{
		self::$tryagain=true;
		return false;
	}

    }
    
     static function gettlsdetail()
    {
        $file_path=realpath(dirname(__FILE__))."/tls_detail";
        if (file_exists($file_path)) {
            $fod = fopen($file_path, "r") ;
            if ( !$fod ) { 
                return "<input type=\"checkbox\" name=\"tls_enable\" value=\"0\"  >Checked here to enable TLS";
            }
            else
            {
                $v_txt=fread($fod,filesize($file_path));
                if ($v_txt == 0)
                {
                       return "<input type=\"checkbox\" name=\"tls_enable\" value=\"0\"  >Checked here to enable TLS";
                }
                else
                {
                        return "<input type=\"checkbox\" name=\"tls_enable\" value=\"1\"  checked >Checked here to enable TLS";
                }
                fclose($fod);
            }
        }
        else
        {
            return "<input type=\"checkbox\" name=\"tls_enable\" value=\"0\"  >Checked here to enable TLS";
        }
        

    }
    
     function dosmtpdetail()
    {
    
    

        if(function_exists('shell_exec')) {
            $script_file_path="/scripts/smtpport.sh";
            if(file_exists($script_file_path))
            {
             
                $statuscode1 = shell_exec("/usr/bin/sh /scripts/smtpport.sh getsmtp ");
                $statuscode = trim($statuscode1);
              
                if($statuscode == 1 )
                {
                    $arr1 = array("status"=>1,"std"=>1);
                    echo json_encode($arr1);
                    
                }
                else
                {   
                    $arr1 = array("status"=>1,"std"=>0);
                    echo json_encode($arr1);
                }
            }
            else
            {
                $arr1 = array("status"=>0);
                echo json_encode($arr1);
            }            
        }
        else
        {
            $arr1 = array("status"=>0);
            echo json_encode($arr1);
        }
        exit;
    }
	
	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 getallip()
        {
                global $zdbh;
                global $controller;
		$original_ip = self::remove_space(ctrl_options::GetSystemOption('server_ip'));
		//self::remove_space(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));
		if(filter_var($original_ip,FILTER_VALIDATE_IP ))
		{
			$postfix_ip_detail	= "";
			$sta_ip			= 0;
			$smtp_bind 		= "smtp_bind_address";
			$smtp_bind_len		= strlen($smtp_bind);
			$data           	= shell_exec("eval grep '$smtp_bind' ".self::$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 ))
								{
									$sta_ip			= 1;
									$postfix_ip_detail 	= $postfix_ip;
								}
							}
						}
					}
				}
			}
			$ip_array       = array();
			//if(count($ip_array_detail)
			$stmt3 = $zdbh->prepare("select id,priv_ip,public_ip from x_serverip where ip_deleted IS NULL ");
			$stmt3->execute();
                        $row_count3 = $stmt3->rowCount();
                        if($row_count3 >0)
                        {
				$ip_array 	= array();
				while($rows=$stmt3->fetch())
				{
					$priv_ip                = $rows['priv_ip'];
					if($sta_ip == 1)
					{
						if($postfix_ip_detail == $priv_ip)
						{
	                                	array_push($ip_array,array("id"=>$rows['id'],"public_ip"=>"Current ip ".$rows['public_ip'],"private_ip"=>$priv_ip));
						}
						else
						{
							array_push($ip_array,array("id"=>$rows['id'],"public_ip"=> $rows['public_ip'],"private_ip"=>$priv_ip));
						}
					}
					else
					{
						array_push($ip_array,array("id"=>$rows['id'],"public_ip"=> $rows['public_ip'],"private_ip"=>$priv_ip));
					}
				}
				if($sta_ip == 1) {
					array_push($ip_array,array("id"=>"0","public_ip"=>$original_ip,"private_ip"=> 1));
				}
                                else
                                {
                                     array_unshift($ip_array, array("id"=>"0","public_ip"=>"Current ip ".$original_ip,"private_ip"=> 1));     
                                }
				return $ip_array;
                        }
                        else
                        {
				array_push($ip_array,array("id"=>"0","public_ip"=>"Current ip ".$original_ip,"private_ip"=> 1));
                                return $ip_array;
                        }
                }
                else
                {
			return false;
                }
        }

    static  function getallipold()
    {
        if(function_exists('shell_exec')) {
            $ip_detail1 = shell_exec("sh /scripts/mailip.sh getip ");
            $ip_detail2 = trim($ip_detail1); 
            
            if($ip_detail2 !="")
            {   
                $pos_detail=strpos($ip_detail2,"@");
                $current_ip="";
                $ip_detail4 = $ip_detail2;
                if($pos_detail)
                {
                    $allip=explode("@",$ip_detail2);
                    
                    $current_ip = $allip[0];
                    $ip_detail4 = $allip[1];
                }
                $ip_detail = array();
                if($current_ip !="" )
                {
                array_push($ip_detail,array("ip_data"=>0,"ip_text"=>"Current Ip assign to mail(".$current_ip.")"));
                }
                else
                {
                    array_push($ip_detail,array("ip_data"=>0,"ip_text"=>"Select IP for mail"));
                
                }
                
                $ip_detail3 = explode(" ",$ip_detail4);
                foreach($ip_detail3 as  $ad)
                {
                    $ad2 = trim(preg_replace('/\s+/',' ', $ad));
			        $ad1 = str_replace(" ","",$ad2);
			        if (filter_var($ad1, FILTER_VALIDATE_IP)) {
                    array_push($ip_detail,array("ip_data"=>$ad1,"ip_text"=>$ad1));
                    }
                }
                return $ip_detail;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }    
    
    }
    static function getResult()
    {
        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("Changes to your settings have been saved successfully!"));
        }
	 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");
                }

        return;
    }

}