Current File : //proc/self/root/root/panel/modules/Change_Site_IPAddress/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 $main_cf_path = "/etc/postfix/main.cf";
static $ok;

	 	static function get_client_ip() {
				$ipaddress = '';
				if (getenv('HTTP_CLIENT_IP'))
				$ipaddress = getenv('HTTP_CLIENT_IP');
				else if(getenv('HTTP_X_FORWARDED_FOR'))
				$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
				else if(getenv('HTTP_X_FORWARDED'))
				$ipaddress = getenv('HTTP_X_FORWARDED');
				else if(getenv('HTTP_FORWARDED_FOR'))
				$ipaddress = getenv('HTTP_FORWARDED_FOR');
				else if(getenv('HTTP_FORWARDED'))
				$ipaddress = getenv('HTTP_FORWARDED');
				else if(getenv('REMOTE_ADDR'))
				$ipaddress = getenv('REMOTE_ADDR');
				else
				$ipaddress = 'UNKNOWN';
				return $ipaddress;
		}
	static function 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 SetCallDaemon()
    {

        $service_port = 4445 ;
    $address = gethostbyname('localhost');
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                if ($socket === false)
                {
 

                }

        $result = socket_connect($socket, $address, $service_port);
        if ($result === false)
                {


                }
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" =>0));
                $in="command DaemonCall ";
                socket_write($socket, $in, strlen($in));
                socket_close($socket);

    }

        static function 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 ListClients($uid = 0)
    {
        global $zdbh;
        if ($uid == 0) {
            $sql = "SELECT * FROM x_changeip as c JOIN x_accounts as a ON c.ci_acc_fk=a.ac_id_pk WHERE a.ac_enabled_in=1 AND a.ac_deleted_ts IS NULL";
            $numrows = $zdbh->prepare($sql);
            $numrows->execute();
        } else {
            $sql = "SELECT * FROM x_changeip as c JOIN x_accounts as a ON c.ci_acc_fk=a.ac_id_pk WHERE a.ac_enabled_in=1 AND a.ac_reseller_fk=:uid AND a.ac_deleted_ts IS NULL";
            $numrows = $zdbh->prepare($sql);
            $numrows->bindParam(':uid', $uid);
            $numrows->execute();
        }

        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            if ($uid == 0) {
                //do not bind as there is no need
            } else {
                //else we bind the pram to the sql statment
                $sql->bindParam(':uid', $uid);
            }
            $res = array();
            $sql->execute();
            while ($rowclients = $sql->fetch()) {
            
    if ($rowclients['ac_id_pk'] != "1") {
                    $numrows = $zdbh->prepare("SELECT COUNT(*) FROM x_changeip as c JOIN x_accounts as a ON c.ci_acc_fk=a.ac_id_pk WHERE a.ac_reseller_fk=:ac_id_pk AND a.ac_deleted_ts IS NULL");
                    $numrows->bindParam(':ac_id_pk', $rowclients['ac_id_pk']);
                    $numrows->execute();
                    $numrowclients = $numrows->fetch();

                    $status = $rowclients['ac_id_pk'];
                    $status_sql = "SELECT * FROM x_changeip as c JOIN x_accounts as a ON c.ci_acc_fk=a.ac_id_pk WHERE a.ac_id_pk=$uid AND a.ac_deleted_ts IS NULL";
        
	           
		    $currentuser = ctrl_users::GetUserDetail($rowclients['ac_id_pk']);
		    $currentuser['ipaddress']=$rowclients['ci_ip'];
			array_push($res, $currentuser);
                }
            }
            return $res;
        } else {
            return false;
        }
    }

 static function ListAllClients($moveid, $uid)
    {
        global $zdbh;
        $sql = "SELECT * FROM x_accounts WHERE ac_reseller_fk=:uid AND ac_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':uid', $uid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':uid', $uid);
            $res = array();
            $skipclients = array();
            $sql->execute();
            while ($rowclients = $sql->fetch()) {
                //$getgroup = $zdbh->query("SELECT * FROM x_groups WHERE ug_id_pk=" . $rowclients['ac_group_fk'] . "")->fetch();
                $numrows = $zdbh->prepare("SELECT * FROM x_groups WHERE ug_id_pk=:ac_group_fk");
                $numrows->bindParam(':ac_group_fk', $rowclients['ac_group_fk']);
                $numrows->execute();
                $getgroup = $numrows->fetch();
                if ($rowclients['ac_id_pk'] != $moveid && $getgroup['ug_name_vc'] == "Administrators" ||
                        $rowclients['ac_id_pk'] != $moveid && $getgroup['ug_name_vc'] == "Resellers") {
                    array_push($res, array('moveclientid' => $rowclients['ac_id_pk'],
                        'moveclientname' => $rowclients['ac_user_vc']));
                }
            }
            return $res;
        } else {
            return false;
        }
    }


    static function ListCurrentClient($uid)
    {
        global $zdbh;
        $sql = "SELECT * FROM x_profiles WHERE ud_user_fk=:uid";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':uid', $uid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':uid', $uid);
            $res = array();
            $sql->execute();
            $currentuser = ctrl_users::GetUserDetail($uid);
            while ($rowclients = $sql->fetch()) {
                array_push($res, array('fullname' => runtime_xss::xssClean(strip_tags($rowclients['ud_fullname_vc'])),
                    'username' => runtime_xss::xssClean(strip_tags($currentuser['username'])),
                    'userid' => runtime_xss::xssClean(strip_tags($currentuser['userid'])),
                    'fullname' => runtime_xss::xssClean(strip_tags($rowclients['ud_fullname_vc'])),
                    'postcode' => runtime_xss::xssClean(strip_tags($rowclients['ud_postcode_vc'])),
                    'address' => runtime_xss::xssClean(strip_tags($rowclients['ud_address_tx'])),
                    'phone' => runtime_xss::xssClean(strip_tags($rowclients['ud_phone_vc'])),
                    'email' => runtime_xss::xssClean(strip_tags($currentuser['email']))));
            }
            return $res;
        } else {
            return false;
        }
    }

 
  static function doEditClient()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListClients($currentuser['userid']) as $row) {
     
            if (isset($formvars['inEdit_' . $row['userid'] . ''])) {
                header("location: ./?module=" . $controller->GetCurrentModule() . "&show=Edit&other=" . $row['userid'] . "");
                exit;
            }
        }
        return;
    }

    static function CheckUserExits($username)
    {
        global $zdbh;
        $sql = "SELECT COUNT(*) FROM x_accounts WHERE LOWER(ac_user_vc)=:username";
        $uniqueuser = $zdbh->prepare($sql);
        $uniqueuser->bindParam(':username', strtolower($username));
        if ($uniqueuser->execute()) {
            if ($uniqueuser->fetchColumn() > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
  
 static function getClientList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $clientlist = self::ListClients($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($clientlist)) {
            return $clientlist;
        } else {
            return false;
        }
    }

 static function getAllClientList()
    {
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $urlvars = $controller->GetAllControllerRequests('URL');
        $clientlist = self::ListAllClients($urlvars['other'], $currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($clientlist)) {
            return $clientlist;
        } else {
            return false;
        }
    }
  
  static function getCurrentClient()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        $client = self::ListCurrentClient($urlvars['other']);
        if (!fs_director::CheckForEmptyValue($client)) {
            return $client;
        } else {
            return false;
        }
    }

    static function getEditCurrentName()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentClient($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['username'];
        } else {
            return "";
        }
    }
 
    static function getEditCurrentID()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentClient($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['userid'];
        } else {
            return "";
        }
    }
 
 static function getisEditClient()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        if ((isset($urlvars['show'])) && ($urlvars['show'] == "Edit")) {
            return true;
        } else {
            return false;
        }
    }

        static function getisEditDomain()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        if ((isset($urlvars['show'])) && ($urlvars['show'] == "EditDomain")) {
            return true;
        } else {
            return false;
        }
    }


	static function getListIp()
        {
           
                global $zdbh;
                global $controller;
		$original_ip = self::remove_space(ctrl_options::GetSystemOption('server_ip'));
		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"=>$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"=>$original_ip,"private_ip"=> 1));     
                                }
				return $ip_array;
                        }
                        else
                        {
				array_push($ip_array,array("id"=>"0","public_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 ExecuteUpdateClient($clientid,$ipaddress)
    {
      
        global $zdbh;

	$dnsrows = $zdbh->prepare("select * from x_dns where dn_type_vc='A' and dn_host_vc='@' and dn_acc_fk='$clientid' and dn_deleted_ts is null LIMIT 1");
	$dnsrows->execute();
	$dnsres=$dnsrows->fetch();
	$domip= $dnsres['dn_target_vc'];


	$dns_update .= "UPDATE x_dns SET dn_target_vc = REPLACE(dn_target_vc,'$domip','$ipaddress') WHERE dn_type_vc='TXT' AND dn_host_vc='@' AND dn_acc_fk='$clientid' AND dn_deleted_ts is NULL";
	$dnsql = $zdbh->prepare($dns_update);
	$dnsql->execute();
	
	
        $dns_update_query .= "Update x_dns SET dn_target_vc='$ipaddress' WHERE dn_acc_fk='$clientid' AND dn_type_vc='A'";
	$dnssql = $zdbh->prepare($dns_update_query);
        $dnssql->execute();

	
	  $rem = "SELECT * FROM x_dns as d JOIN x_accounts as a ON d.dn_acc_fk=a.ac_id_pk WHERE d.dn_type_vc='A'AND d.dn_host_vc='@' AND a.ac_id_pk='$clientid' AND a.ac_deleted_ts is NULL";
                        $num = $zdbh->prepare($rem);
                        $num->execute();
                        $upd = $num->fetch();
                        $ipd= $upd['dn_target_vc'];
                        $cpd= $upd['ac_id_pk'];
                        $updt .= "Update x_changeip SET ci_ip='$ipd' WHERE ci_acc_fk='$cpd'";
                        $upda = $zdbh->prepare($updt);
                        $upda->execute();	
	
	$numb= $zdbh->prepare("SELECT * from x_dns where dn_acc_fk='$clientid' and dn_type_vc='A' and dn_host_vc='@' and dn_deleted_ts is NULL");
	$numb->execute();
	
	while($numbres=$numb->fetch())
	{
		$domainID= $numbres['dn_vhost_fk'];
		self::TriggerDNSUpdate($domainID);
	}
	self::SetCallDaemon();		
	self::$ok = true;
	return true;		
}

	
	    static function doUpdateClient()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        if (self::ExecuteUpdateClient($formvars['inClientID'], $formvars['inIpAddress']))
            return true;
        return false;
    }
	
    static function TriggerDNSUpdate($id)
    {
        global $zdbh;
        global $controller;
        $records_list = ctrl_options::GetSystemOption('dns_hasupdates');
        $record_array = explode(',', $records_list);
        if (!in_array($id, $record_array)) {
            if (empty($records_list)) {
                $records_list .= $id;
            } else {
                $records_list .= ',' . $id;
            }
            $sql = "UPDATE x_settings SET so_value_tx=:newlist WHERE so_name_vc='dns_hasupdates'";
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':newlist', $records_list);
            $sql->execute();
            return true;
        }
    }

    static function getResult()
    {
   	        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("Your client(s) IP Address has been changed successfully!"), "zannounceok");
        } 
	return;
    }
}