Current File : //root/panel/modules/modhttp/code/controller.ext.php
<?php
error_reporting(0);
/**
 * @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
{

	public static $m_error;
	public static $tryagain;
	public static $lets_encrypt_path="";
	public static $ssl_log_path	= "/var/log/letsencrypt/sslrenew.log";
	public static $server_port 	= 80;
	public static $other_port	= 8080;
	

	static function n_sanitize($data)
	{
	
		$data = trim($data);
		$data = stripslashes($data);
		$data = htmlspecialchars($data);
		return $data;
	}
	
    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 getListDomaindata()
	{
		global $zdbh;
		$currentuser = ctrl_users::GetUserDetail();
		$stmt = $zdbh->prepare("select vh_id_pk,vh_name_vc from x_vhosts where vh_acc_fk =:uid and vh_deleted_ts IS NULL and vh_modhttp ='1' ");
		$stmt->bindParam(':uid',$currentuser['userid']);
		$stmt->execute();
		$row_count = $stmt->rowCount();
		if($row_count >0)
		{
			$domainarray = array(array("d_id"=>0,"d_name"=>"Select domain"));
			while($rows = $stmt->fetch())
			{
				array_push($domainarray,array('d_id' => $rows['vh_id_pk'],'d_name' => $rows['vh_name_vc']) ) ;   
			}
			return $domainarray;
		}
		else
		{
			$domainarray = array(array("d_id"=>0,"d_name"=>"No domain"));
			return $domainarray;
		} 
	}

	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 call_socket($cmd_detail,$status_code)
	{
        $service_port = 4444 ;
        $address = gethostbyname('localhost');
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket === false) {
                self::$tryagain=true;
            return false;
        }
        $result = socket_connect($socket, $address, $service_port);
        if ($result === false) {
                self::$tryagain=true;
            return false;
        }
        socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 20, "usec" =>0));
        $in="command ".$cmd_detail;
        $out = '';
        if(@socket_write($socket, $in, strlen($in)))
        {
            sleep(1);
            $s_data = socket_read($socket,1024);
            socket_close($socket);
            return $s_data;
        }
        else { return "2";  }
    }

    static function docheckmodhttp()
	{
	    global $controller;
		global $zdbh;
		$formvars = $controller->GetAllControllerRequests('FORM');

		if ( array_key_exists("dom_id",$formvars) && array_key_exists("st_code",$formvars))
		{
			$dom_id     = self::n_sanitize($formvars['dom_id']);
			$st_code    = self::n_sanitize($formvars['st_code']);
			if ( !fs_director::CheckForEmptyValue($dom_id) && !fs_director::CheckForEmptyValue($st_code) && is_numeric($dom_id) && is_numeric($st_code))
			{
		        $currentuser = ctrl_users::GetUserDetail();
				$suid = $currentuser['userid'];
		        if ($st_code == 1)
                {
                    $stmt1 = $zdbh->prepare("select vh_id_pk,vh_name_vc from x_vhosts where vh_acc_fk =:uid AND vh_id_pk =:did AND vh_deleted_ts IS NULL and vh_modhttp = 2 and vh_modhttp_status = 1 ");
                }
                else
                {
                    $stmt1 = $zdbh->prepare("select vh_id_pk,vh_name_vc from x_vhosts where vh_acc_fk =:uid AND vh_id_pk =:did AND vh_deleted_ts IS NULL and vh_modhttp = 1 and vh_modhttp_status = 1 ");
                }          
                $stmt1->bindParam(':uid',$suid);
                $stmt1->bindParam(':did',$dom_id);
                $stmt1->execute();
                $row_count1 = $stmt1->rowCount();
                if($row_count1 >0) { echo json_encode(array("status"=>1)); }
                else { echo json_encode(array("status"=>2)); }
            }
            else{ echo json_encode(array("status"=>3)); }
        }
        else { echo json_encode(array("status"=>3)); }	
        exit;
	}

	static function doswitchmodhttp()
	{
		global $controller;
		global $zdbh;
	
		//runtime_csfr::Protect();
		$formvars = $controller->GetAllControllerRequests('FORM');
		if ( array_key_exists("dom_id",$formvars) && is_numeric($formvars['dom_id']))
		{
			$dom_id = self::n_sanitize($formvars['dom_id']);
			if ( fs_director::CheckForEmptyValue($dom_id) || !is_numeric($dom_id) )
			{
				self::$m_error = "Enter all field";
			}
			else
			{
			    $module_path	= ctrl_options::GetSystemOption('sentora_root') ."modules/". ui_module::GetModuleName();
				$currentuser = ctrl_users::GetUserDetail();
				$suid = $currentuser['userid'];
                		$stmt1 = $zdbh->prepare("select vh_id_pk,vh_name_vc from x_vhosts where vh_acc_fk =:uid AND vh_id_pk =:did AND vh_deleted_ts IS NULL and vh_modhttp = '1' ");
				$stmt1->bindParam(':uid',$suid);
				$stmt1->bindParam(':did',$dom_id);
				$stmt1->execute();
				$row_count1 = $stmt1->rowCount();
				if($row_count1 >0)
				{
					$rows1          = $stmt1->fetch();
                    $domain_name    = $rows1['vh_name_vc'];
                    $vh_mod_no      = $rows1['vh_id_pk'];
					$stmt2 		= $zdbh->prepare("select ssl_no from x_ssl where ssl_doamin =:dom and userid =:uid and ssl_delete IS NULL ");
					$stmt2->bindParam(":dom",$domain_name);
					$stmt2->bindParam(":uid",$suid);
					$stmt2->execute();
					$row_count2 = $stmt2->rowCount();
					if($row_count2 > 0 )
					{
                        $privkey = array();
                        $domain_certbot = array();
                        shell_exec("touch /var/log/letsencrypt/sslrenew.log");
                        shell_exec("certbot certificates > /var/log/letsencrypt/sslrenew.log");
                        $domain_certbot = shell_exec("grep -ni 'Certificate Name' /var/log/letsencrypt/sslrenew.log");
                        $line_cerbot    = array_filter(explode("\n",$domain_certbot));
                        $privkey_list   = array();
                        foreach($line_cerbot as $key=>$value)
                        {
                            $domain_list_temp               = explode(":",$value);
                            $domain_name                    = self::remove_space($domain_list_temp[2]);
                            $line_no                        = self::remove_space($domain_list_temp[0])+3;
                            $privkey                        = shell_exec("sed -n '$line_no'p /var/log/letsencrypt/sslrenew.log");
                            $privkey_list_temp              = explode("/",$privkey);
                            $privkey_file                   = self::remove_space($privkey_list_temp[4]);
                            $privkey_list[$domain_name]     = $privkey_file;
                        }
                        if(array_key_exists($domain_name,$privkey_list))
                        {
					        $stmt4  =  $zdbh->prepare("update x_vhosts set vh_modhttp=2,vh_modhttp_status=0 where vh_id_pk =:dom_id_no");
					        $stmt4->bindParam(":dom_id_no",$vh_mod_no);
					        $stmt4->execute();						
						    $stmt3 	=  $zdbh->prepare("select x_varnish,x_nginx  from x_varnish limit 1");
						    $stmt3->execute();
						    $row_count3 = $stmt3->rowCount();
						    if($row_count3  > 0)
						    {
							    $rows3 		= $stmt3->fetch();
							    $varnish	= $rows3['x_varnish'];
							    $nginx		= $rows3['x_nginx'];
							    $asd        = 0;
							    if ($nginx == "On") { $asd = self::call_socket("modhttp nginx 1"); }
							    else { $asd = self::call_socket("modhttp apache 1"); }
							    if ($asd == 1)
							    {
							        echo json_encode(array("status"=>1,"error"=>"Http2 we are installing for this domain , please wait"));
						        }
						        else
						        {
						            echo json_encode(array("status"=>2,"error"=>"We are getting server issue, please contact Sysadmin"));
						        }
						    }
						    else
						    {
							    echo json_encode(array("status"=>2,"error"=>"We are getting server issue, please contact Sysadmin"));
						    }
					    }
					    else { 
					            echo json_encode(array("status"=>2,"error"=>"Please install ssl on your server"));
                            }
						
					}
					else {	
					    echo json_encode(array("status"=>2,"error"=>"Please install SSL on this domain"));
                    	}
				}
				else
				{
				    echo json_encode(array("status"=>2,"error"=>"Please choose proper domain"));
				}
			}
		}
		else
		{
		    echo json_encode(array("status"=>2,"error"=>"Enter all field"));
		}
		exit;
	}    
        
    static function getmodhttp_detail()
    {
        global $zdbh;
        $currentuser = ctrl_users::GetUserDetail();
        $suid = $currentuser['userid'];
        $stmt3 =$zdbh->prepare("select vh_id_pk,vh_name_vc,vh_modhttp_status from x_vhosts where vh_acc_fk =:sid and vh_modhttp=2 and vh_modhttp_status =1 and vh_deleted_ts IS NULL ");
        $stmt3->bindParam(':sid',$suid);
        $stmt3->execute();
        $row_count3 = $stmt3->rowCount();
        if($row_count3 >0)
        {
            $dom_array  = array();
            $inc_a      = 1;
            while($rows=$stmt3->fetch())
            {                
                $vhbody = $rows['vh_name_vc'];               
                array_push($dom_array,array('m_id' =>$inc_a,"mh_id"=> $rows['vh_id_pk'],'m_dom' => $rows['vh_name_vc']));
                $inc_a++;                   
            }
            return $dom_array;
        }
        else { echo false; }
    }
    
    static function  doconform_modhttp()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $suid = $currentuser['userid'];
        runtime_csfr::Protect();
		$formvars = $controller->GetAllControllerRequests('FORM');
        $modhttpdata =self::n_sanitize($formvars['modhttpdata']);
        if(array_key_exists("modhttpdata",$formvars))
        {
            if ( !fs_director::CheckForEmptyValue($modhttpdata) && is_numeric($modhttpdata)   )
            {   
                $stmt3 =$zdbh->prepare("select vh_id_pk,vh_name_vc from x_vhosts where vh_id_pk =:vhid and vh_acc_fk =:sid and vh_modhttp = 2 and vh_deleted_ts IS NULL ");
                $stmt3->bindParam(':sid',$suid);
                $stmt3->bindParam(':vhid',$modhttpdata);
                $stmt3->execute();
                $row_count3 = $stmt3->rowCount();
                if($row_count3 >0)
                {
                    $rows = $stmt3->fetch();
                    header("location: ./?module=". $controller->GetCurrentModule() ."&show=Delete&id=".$modhttpdata ."&dom=".$rows['vh_name_vc']."");
                    exit;
                }
                else
                {
                    header("location: ./?module=" . $controller->GetCurrentModule() );
                    exit;                
                }          
            }
            else
            {
                header("location: ./?module=" . $controller->GetCurrentModule() );
                exit;
            } 
        }
        else
        {
            header("location: ./?module=" . $controller->GetCurrentModule() );
            exit;
        }
    }
    
    static function getisDeletemodhttp()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Delete");        
    }

    static function getCurrentmodhttp()
    {
        global $controller;
        $auto_res = $controller->GetControllerRequest('URL', 'dom');
        return ($auto_res) ? $auto_res : '';
    }

    static function getid_data()
    {
        global $controller;
        $auto_resid = $controller->GetControllerRequest('URL', 'id');
        return ($auto_resid) ? $auto_resid : 0;
    }
    
    static function doDeletemodhttp()
    {
        global $zdbh;
        global $controller;
        //runtime_csfr::Protect();
      	$formvars = $controller->GetAllControllerRequests('FORM');
      	if(array_key_exists("dom_id",$formvars))
      	{
            $dom_id         = self::n_sanitize($formvars['dom_id']);
            $currentuser    = ctrl_users::GetUserDetail();
            $suid           = $currentuser['userid'];
            if ( !fs_director::CheckForEmptyValue($dom_id) && is_numeric($dom_id) && $dom_id > 0)
            { 
                $stmt3 =$zdbh->prepare("select vh_id_pk from x_vhosts where vh_id_pk =:vhid and vh_acc_fk =:sid and vh_modhttp=2 and vh_deleted_ts IS NULL ");
                $stmt3->bindParam(':sid',$suid);
                $stmt3->bindParam(':vhid',$dom_id);
                $stmt3->execute();
                $row_count3 = $stmt3->rowCount();
                if($row_count3 >0)
                {
                    $stmt4  =  $zdbh->prepare("update x_vhosts set vh_modhttp=1,vh_modhttp_status=0 where vh_id_pk =:dom_id_no");
                    $stmt4->bindParam(":dom_id_no",$dom_id);
                    $stmt4->execute();						
                    $stmt3 	=  $zdbh->prepare("select x_varnish,x_nginx  from x_varnish limit 1");
                    $stmt3->execute();
                    $row_count3 = $stmt3->rowCount();
                    if($row_count3  > 0)
                    {
                        $rows3 		= $stmt3->fetch();
                        $varnish	= $rows3['x_varnish'];
                        $nginx		= $rows3['x_nginx'];
                        //if ($nginx == "On") { self::call_socket("modhttp nginx 2"); }
                        //else { self::call_socket("modhttp apache 2"); } 
                                $asd        = 0;
							    if ($nginx == "On") { $asd = self::call_socket("modhttp nginx 2"); }
							    else { $asd = self::call_socket("modhttp apache 2"); }

							    if ($asd == 1)
							    {
							        echo json_encode(array("status"=>1,"error"=>"Removing http2 from domain , please wait"));
						        }
						        else
						        {
						            echo json_encode(array("status"=>2,"error"=>"We are getting server issue, please contact Sysadmin"));
						        }             
                    }
                    else
                    {
                        echo json_encode(array("status"=>2,"error"=>"we are getting some server issue, please contact system admin"));
                    }
                }
                else
                {
                    echo json_encode(array("status"=>2,"error"=>"Http2 is not enable for this domain"));
                }
            }
            else
            {
                echo json_encode(array("status"=>2,"error"=>"Unable to remove Http2 from domain, please contact system admin"));       
            }
        }
        else
        {
            echo json_encode(array("status"=>2,"error"=>"Unable to remove Http2 from domain, please contact system admin"));   
        }
        exit;
    }
   
    static function getresult()
    {
		if (!fs_director::CheckForEmptyValue(self::$tryagain)) {
			return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> Please try again Later. Server service not available."), "Error");
		}
        if (!fs_director::CheckForEmptyValue(self::$m_error)) {
            return ui_sysmessage::shout(ui_language::translate(self::$m_error), "zannounceerror");
        }
         return;
    }
}