Current File : //etc/zpanel/panel/modules/phpversion/code/controller.ext.php
<?php

/**
 * @copyright 2014-2015 Sentora Project (http://www.sentora.org/) 
 * Sentora is a GPL fork of the ZPanel Project whose original header follows:
 *
 * ZPanel - A Cross-Platform Open-Source Web Hosting Control panel.
 *
 * @package ZPanel
 * @version $Id$
 * @author Bobby Allen - ballen@bobbyallen.me
 * @copyright (c) 2008-2014 ZPanel Group - http://www.zpanelcp.com/
 * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3
 *
 * This program (ZPanel) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class module_controller extends ctrl_module
{

    static $complete;
    static $error;
    static $writeerror;
    static $nosub;
    static $alreadyexists;
    static $badname;
    static $blank;
    static $ok;

    /**
     * The 'worker' methods.
     */
    static function ListSubDomains($uid)
    {
        global $zdbh;
       // $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:uid AND vh_deleted_ts IS NULL ORDER BY vh_name_vc ASC";
		 $sql = "SELECT a.vh_id_pk,a.vh_name_vc,(select x_php_version from x_phpversion_upgrade where x_client_id=a.vh_id_pk) as phpversion FROM x_vhosts a  WHERE a.vh_acc_fk=:uid  AND a.vh_deleted_ts IS NULL ORDER BY a.vh_name_vc ASC";

        //$numrows = $zdbh->query($sql);
        $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();
            while ($rowdomains = $sql->fetch()) {
			//	$domain_php_version=
                array_push($res, array('subname' => $rowdomains['vh_name_vc'],
                    'phpversion' => $rowdomains['phpversion'],
                    'subid' => $rowdomains['vh_id_pk']));
            }
            return $res;
        } else {
            return false;
        }
    }
	
	static function getResult()
    {
        if (!fs_director::CheckForEmptyValue(self::$error)) {
            if (self::$error == "ok") {
                return ui_sysmessage::shout(ui_language::translate("Your PHP version has been changed successfully..! could you please wait for 2 minutes for background configuration."), "Update");
            }
        } 
    }
	static function doUpdateVersion()
	{
		global $zdbh;
        global $controller;
		$formvars = $controller->GetAllControllerRequests('FORM');
		$update_version = $formvars['php_version'];
		$userid=$formvars['inSave'];
		$sql = "SELECT * FROM x_phpversion_upgrade WHERE x_client_id=:userid ";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $userid);
        $numrows->execute();
		if ($numrows->fetchColumn() <> 0) {
			
			$sql_update = "Update x_phpversion_upgrade SET x_php_version=:x_php_version,x_flag=:x_flag,x_update_time=:x_update_time WHERE x_client_id=:userid ";
			$numrows1 = $zdbh->prepare($sql_update);
			$numrows1->bindParam(':userid',$userid );
			$numrows1->bindParam(':x_php_version', $update_version);
			$time=time();
			$flag="On";
			$numrows1->bindParam(':x_flag', $flag);
			$numrows1->bindParam(':x_update_time', $time);
			$numrows1->execute();
			
			
		}else
		{
			// Insert the PHP version 
			$sql_update ="INSERT INTO x_phpversion_upgrade (x_php_version,
											 x_flag,
											 x_update_time,
											 x_client_id) VALUES (
											 :x_php_version,
											 :x_flag,
											 :x_update_time,
											 :userid)";
			$numrows1 = $zdbh->prepare($sql_update);
			$numrows1->bindParam(':userid',$userid );
			$numrows1->bindParam(':x_php_version', $update_version);
			$time=time();
			$flag="On";
			$numrows1->bindParam(':x_flag', $flag);
			$numrows1->bindParam(':x_update_time', $time);
			$numrows1->execute();
			
		} 
		
			$gsql=$zdbh->prepare("select vh_id_pk from x_vhosts where  vh_acc_fk=:userid AND vh_deleted_ts is NULL");	
			$gsql->bindParam(':userid', $userid);
			$gsql->execute();
			$records_list="";
			$iter=0;
			while($res=$gsql->fetch())
			{
			if($iter==0)
			{
			$records_list=$res['vh_id_pk'];
			$iter=1;
			}	
			else
			{

			$records_list=$res['vh_id_pk'];
			}	
			}
			
			$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();
			
			$sql = "UPDATE x_ssl SET ssl_status='0' WHERE ssl_delete IS NULL";
                        $sql = $zdbh->prepare($sql);
                        $sql->execute();

			$sql = $zdbh->prepare("UPDATE x_settings
			SET so_value_tx='true'
			WHERE so_name_vc='apache_changed'");
			$sql->execute();
			
			$sql = $zdbh->prepare("UPDATE x_varnish
			SET x_isactive='0'");
			$sql->execute();
		// passthru("php /etc/sentora/panel/bin/daemon.php");
		// sleep(30);
		self::SetCallDaemon();
		self::$error="ok";
	}
     
         static function SetCallDaemon()
    {

        $service_port = 4445 ;
    $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" => 2000, "usec" =>0));
                $in="command DaemonCall ";
                socket_write($socket, $in, strlen($in));
                socket_close($socket);

    }
	static function getEditID()
    {
        global $controller;
        $id = $controller->GetControllerRequest('URL', 'other');
        return ($id) ? $id : '';
    }
	
	static function getEditCurrentSubDomain()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentSubDomain($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['currentdomain'];
        } else {
            return '';
        }
    }
	 static function getshowVersion()
    {
		global $zdbh;
        global $controller;
	    $id = $controller->GetControllerRequest('URL', 'other');
		 $core_php_version = ctrl_options::GetSystemOption('core_php_version');
		$sql = "SELECT * FROM x_phpversion_upgrade WHERE x_client_id=:userid ";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $id);
        $numrows->execute();
		$php53selected="";
		$php54selected="";
		$php55selected="";
		$php56selected="";
		$php70selected="";
		$php71selected="";	
		$php72selected="";
	if ($numrows->fetchColumn() <> 0) 
	{
			$numrows1 = $zdbh->prepare($sql);
			$numrows1->bindParam(':userid', $id);
			$numrows1->execute();
			$res=$numrows1->fetch();
			$getvalue=$res['x_php_version'];
			if($getvalue=="php53")$php53selected='selected=selected';
			if($getvalue=="php54")$php54selected='selected=selected';
			if($getvalue=="php55")$php55selected='selected=selected';
			if($getvalue=="php56")$php56selected='selected=selected';
			if($getvalue=="php70")$php70selected='selected=selected';
			if($getvalue=="php71")$php71selected='selected=selected';
			if($getvalue=="php72")$php72selected='selected=selected';
		}else
		{
			if(!$core_php_version)
			{
			$php56selected='selected=selected';
			}else 
			{
				$getvalue=strtolower($core_php_version);
				if($getvalue=="php53")$php53selected='selected=selected';
				if($getvalue=="php54")$php54selected='selected=selected';
				if($getvalue=="php55")$php55selected='selected=selected';
				if($getvalue=="php56")$php56selected='selected=selected';
				if($getvalue=="php70")$php70selected='selected=selected';
				if($getvalue=="php71")$php71selected='selected=selected';
				if($getvalue=="php72")$php72selected='selected=selected';
			}
		}
		$php54_found=file_exists("/usr/local/php54/bin/php-cgi");
		$php55_found=file_exists("/usr/local/php55/bin/php-cgi");
		$php56_found=file_exists("/usr/local/php56/bin/php-cgi");
		$php70_found=file_exists("/usr/local/php70/bin/php-cgi");
    	$php71_found=file_exists("/usr/local/php71/bin/php-cgi");
		$php72_found=file_exists("/usr/local/php72/bin/php-cgi");
		$info="";
		
		if($php54_found==0 && $php55_found==0 && $php56_found==0 && $php70_found==0 && $php71_found==0 && $php72_found==0 )
		{
			$info="<select id='php_version' name='php_version' class='css_phpversion'>";
             if(version_compare(phpversion(),"5.5")==1)
			    $info.="<option value='php56'>PHP 5.6</option>";
            else 			
         	    $info.="<option value='php53'>PHP 5.3</option>";
         $info.="</select>";
		}
		else
		{
			$info="<select id='php_version' name='php_version' class='css_phpversion'>";
            if(!(version_compare(phpversion(),"5.5")==1))
			$info.="<option value='php53' $php53selected >PHP 5.3</option>";
			if($php54_found) $info.="<option value='php54' $php54selected >PHP 5.4</option>";
			if($php55_found) $info.="<option value='php55' $php55selected >PHP 5.5</option>";
			if($php56_found) $info.="<option value='php56' $php56selected >PHP 5.6</option>";
			if($php70_found) $info.="<option value='php70' $php70selected >PHP 7.0</option>";
			if($php71_found) $info.="<option value='php71' $php71selected >PHP 7.1</option>";
			if($php72_found) $info.="<option value='php72' $php72selected >PHP 7.2</option>";

			$info.="</select>";
		}
        return $info;
    }
	static function ListCurrentSubDomain($mid)
    {
		global $zdbh;
		global $controller;
		$mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
		include('cnf/db.php');
		$z_db_user = $user;
		$z_db_pass = $pass;
		try {
		$mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
		} catch (PDOException $e) {
		echo $e;
		}
		
		$sql = "SELECT * FROM x_vhosts WHERE vh_id_pk=:mid AND vh_deleted_ts IS NULL ORDER BY vh_name_vc ASC";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':mid', $mid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':mid', $mid);
            $res = array();
            $sql->execute();
			$rowdomain = $sql->fetch();
			$res[] = array('currentdomain' => $rowdomain['vh_name_vc']);
		}
		return $res;
	}
	
	 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 CheckCreateForErrors($domain)
    {
        global $zdbh;
        // Check for spaces and remove if found...
        $domain = strtolower(str_replace(' ', '', $domain));
        // Check to make sure the domain is not blank before we go any further...
        if ($domain == '') {
            self::$blank = TRUE;
            return FALSE;
        }
        // Check for invalid characters in the domain...
        if (!self::IsValidDomainName($domain)) {
            self::$badname = TRUE;
            return FALSE;
        }
        // Check to make sure the domain is in the correct format before we go any further...
        if (strpos($domain, 'www.') === 0) {
            self::$error = TRUE;
            return FALSE;
        }
        // Check to see if the domain already exists in Sentora somewhere and redirect if it does....
        $sql = "SELECT COUNT(*) FROM x_vhosts WHERE vh_name_vc=:domain AND vh_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':domain', $domain);

        if ($numrows->execute()) {
            if ($numrows->fetchColumn() > 0) {
                self::$alreadyexists = TRUE;
                return FALSE;
            }
        }
        return TRUE;
    }

    

    static function IsValidDomainName($a)
    {
        if (stristr($a, '.')) {
            $part = explode(".", $a);
            foreach ($part as $check) {
                if (!preg_match('/^[a-z\d][a-z\d-]{0,62}$/i', $check) || preg_match('/-$/', $check)) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    static function IsValidEmail($email)
    {
        return preg_match('/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i', $email) == 1;
    }

    static function SetWriteApacheConfigTrue()
    {
        global $zdbh;
        $sql = $zdbh->prepare("UPDATE x_settings
								SET so_value_tx='true'
								WHERE so_name_vc='apache_changed'");
        $sql->execute();
    }

    /**
     * End 'worker' methods.
     */

    /**
     * Webinterface sudo methods.
     */
    static function getSubDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $core_php_version = ctrl_options::GetSystemOption('core_php_version');
		$res = array();
        $subdomains = self::ListSubDomains($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($subdomains)) {
            foreach ($subdomains as $row) {
				$get_php_version="PHP ".phpversion();
				$phpversion=array("php54" => "PHP 5.4","php55" => "PHP 5.5","php56"=>"PHP 5.6","php70" => "PHP 7.0","php71" => "PHP 7.1","php72" => "PHP 7.2");
				if($row["phpversion"]===NULL)
				{
					if(!$core_php_version)
					$get_php_version="PHP ".phpversion();
					else 
					$get_php_version=$phpversion[strtolower($core_php_version)];
				}else 
				{
					$get_php_version=$phpversion[strtolower($row['phpversion'])];
				}
				
                $res[] = array('subname' => $row['subname'],
                    'subdirectory' => $get_php_version,
                    'subid' => $row['subid']);
            }
            return $res;
        } else {
            return false;
        }
    }

    static function getDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $domains = self::ListDomains($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($domains)) {
            return $domains;
        } else {
            return false;
        }
    }
	
	static function doEditSubDomain()
    {
		global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListSubDomains($currentuser['userid']) as $row) {
            if (isset($formvars['inDelete_' . $row['subid'] . ''])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Delete&id=' . $row['subid'] . '&domain=' . $row['subname']);
                exit;
            }
            if (isset($formvars['inEdit_' . $row['subid']])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Edit&other=' . $row['subid']);
                exit;
            }
        }
        return true;
	}
	
    static function getCreateSubDomain()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return ($currentuser['subdomainquota'] < 0) or //-1 = unlimited
                ($currentuser['subdomainquota'] > ctrl_users::GetQuotaUsages('subdomains', $currentuser['userid']));
    }

    /* static function getSubDomainDirsList()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $domaindirectories = self::ListDomainDirs($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($domaindirectories)) {
            return $domaindirectories;
        } else {
            return false;
        }
    } */

    static function doCreateSubDomain()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        if (self::ExecuteAddSubDomain($currentuser['userid'], $formvars['inSub'] . "." . $formvars['inDomain'], $formvars['inDestination'], $formvars['inAutoHome'],$formvars['inDomain'])) {
            self::$ok = TRUE;
            return true;
        } else {
            return false;
        }
        return;
    }



    static function doConfirmDeleteSubDomain()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListSubDomains($currentuser['userid']) as $row) {
            if (isset($formvars['inDelete_' . $row['subid'] . ''])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Delete&id=' . $row['subid'] . '&domain=' . $row['subname']);
                exit;
            }
        }
        return false;
    }

	static function getisEditSubDomain()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Edit");
    }
	
	
    static function getCurrentID()
    {
        global $controller;
        $id = $controller->GetControllerRequest('URL', 'id');
        return ($id) ? $id : '';
    }

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

    static function getSubDomainUsagepChart()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $maximum = $currentuser['subdomainquota'];
        if ($maximum < 0) { //-1 = unlimited
            return '<img src="' . ui_tpl_assetfolderpath::Template() . 'img/misc/unlimited.png" alt="' . ui_language::translate('Unlimited') . '"/>';
        } else {
            $used = ctrl_users::GetQuotaUsages('subdomains', $currentuser['userid']);
            $free = max($maximum - $used, 0);
            return '<img src="etc/lib/pChart2/sentora/z3DPie.php?score=' . $free . '::' . $used
                    . '&labels=Free: ' . $free . '::Used: ' . $used
                    . '&legendfont=verdana&legendfontsize=8&imagesize=240::190&chartsize=120::90&radius=100&legendsize=150::160"'
                    . ' alt="' . ui_language::translate('Pie chart') . '"/>';
        }
    }


}