Current File : //etc/sentora/panel/modules/tomcatrestart/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;
	static $ok_switch;
	static $ans_switch="";
	static $output_set;
	static $output;
    /**
     * The 'worker' methods.
     */
	  static function dooperation()
	 {
		global $zdbh;
		global $controller;
		$currentuser = ctrl_users::GetUserDetail();
		if(isset($_POST['postoperation']))
		{
				$in="";
				if($_POST['postoperation']=="tomcatstart")					
				{
					$in="command tomcat_start";
				}
				else if($_POST['postoperation']=="tomcatstop")					
				{
					$in="command tomcat_stop";
				}
				else if($_POST['postoperation']=="tomcatrestart")					
				{
					$in="command tomcat_restart";
				}
					$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));
					self::$output = "" ; 
					//sleep(10);
					//echo "Hai";
					 self::$output = socket_read($socket, 2048);  
					socket_close($socket);
					self::$output_set=TRUE;
					return true;
		}
	 return true;
	 }
	 static function doupload_file()
	 {
		 global $zdbh;
		 global $controller;
		 runtime_csfr::Protect();
		
		/* //////////////////////////////// Important File Path Start ///////////////////////// */
		// $upload_id is equal to domain Id 
        $formvars = $controller->GetAllControllerRequests('FORM');
		$upload_id=$formvars['upload_id'];
		$filename_id="fileToUpload_".$upload_id;
		$currentuser = ctrl_users::GetUserDetail();
		$currentusername=$currentuser['username'];
		$sql = $zdbh->prepare("SELECT * FROM x_java_version");
        $sql->execute();
        $row_java = $sql->fetch();
		$java_file_path=$row_java['x_file_path'];      
		// Get the java tomcat file path  /usr/local/tomcat7/  (or)  /usr/local/tomcat8/
		$sql = $zdbh->prepare("SELECT * FROM x_vhosts where vh_id_pk='".$upload_id."'");
        $sql->execute();
        $row_domain = $sql->fetch();
		$domain=$row_domain['vh_name_vc'];
		/* //////////////////////////////// Important File Path End ///////////////////////// */
		
		if(isset($_FILES[$filename_id])){
			$errors= array();
			$file_name = $_FILES[$filename_id]['name'];
				if($file_name=="")
				{
				   self::$blank = TRUE;
					return FALSE;
				}
				else
				{
					$file_size =$_FILES[$filename_id]['size'];
					$file_tmp =$_FILES[$filename_id]['tmp_name'];
					$file_type=$_FILES[$filename_id]['type'];
					$file_ext=strtolower(end(explode('.',$_FILES[$filename_id]['name'])));

					$expensions= array("WAR","war","War");

					if(in_array($file_ext,$expensions)=== false){
					self::$badname = TRUE;
					return FALSE;
					}
					
				/* ////////////////////////// Create a folder / Clean folder start ////////////////////// */
					 self::changepermissionstart($java_file_path);
				    $destination = $java_file_path.$currentusername."/".str_replace(".", "_", $domain);
					if (!file_exists($destination)) {
						// Folder does not exists create a folder
						mkdir($destination, 0777, true);
					}else
					{
						// else we will need to delete all the contents of the folder  
						/*	$files = glob($destination.'/{,.}*', GLOB_BRACE);
							foreach($files as $file){ // iterate files
							if(is_file($file))
							unlink($file); // delete file
							}
						*/
					}
					echo $file_tmp;
					echo $destination;
				/* ////////////////////////// Create a folder / Clean folder End ////////////////////// */
				/* ////////////////////////// Upload the File start ////////////////////// */
							if(move_uploaded_file($file_tmp,$destination."/".$file_name))
							{
								
									$sql = "SELECT COUNT(*) FROM x_java_domain_path WHERE x_domain_id=:domain";
										$numrows = $zdbh->prepare($sql);
										$numrows->bindParam(':domain', $upload_id);
										$numrows->execute();
										if ($numrows->fetchColumn() <> 0){
										}else
										{
											$sql="INSERT INTO  `sentora_core`.`x_java_domain_path` (
												`x_domain_id` ,
												`x_file_path`
												)
												VALUES (
												'".$upload_id."',  '".$destination."'
												)";
												$numrows = $zdbh->prepare($sql);
												$numrows->execute();
										}
								self::deploy($java_file_path);
								self::changepermissionend($java_file_path);
								self::$ok= TRUE;
							   self::tomcatrestart();
								// passthru("service tomcat restart");
								return FALSE;	
							}
							else
							{
								
								
								 self::changepermissionend($java_file_path);
								self::$error= TRUE;
								return FALSE;
							}
				/* ////////////////////////// Upload the File End ////////////////////// */
				
				}
		}else
		{
			   self::$blank = TRUE;
				return FALSE;
		}
			
		 return true;
	 }
	 static function getisadmin()
	 {
		 global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        if ($currentuser['usergroup'] == "Administrators" || $currentuser['usergroup'] == "Resellers") {
            return true;
        } else {
            return false;
        }
		 
	 }
	 static function getParticular_User()
	 {
		 
	 }
	
    static function ListDomains($uid = 0)
    {
        global $zdbh;
        if ($uid == 0 || $uid == 1 ) {
            $sql = "SELECT * FROM x_vhosts WHERE vh_deleted_ts IS NULL AND vh_type_in IN ('1','2') ORDER BY vh_name_vc ASC ";
            $numrows = $zdbh->prepare($sql);
        } else {
            $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:uid AND vh_deleted_ts IS NULL AND vh_type_in IN ('1','2') ORDER BY vh_name_vc ASC";
            $numrows = $zdbh->prepare($sql);
            $numrows->bindParam(':uid', $uid);
        }
        //$numrows = $zdbh->query($sql);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            if ($uid == 0 || $uid == 1) {
                $sql = $zdbh->prepare($sql);
            } else {
                $sql = $zdbh->prepare($sql);
                $sql->bindParam(':uid', $uid);
            }
            $res = array();
            $sql->execute();
            while ($rowdomains = $sql->fetch()) {
			  array_push($res, array(
                    'uid' => $rowdomains['vh_acc_fk'],
                    'name' => $rowdomains['vh_name_vc'],
                    // 'directory' => $rowdomains['vh_directory_vc'],
					'directory' => str_replace(".", "_", $rowdomains['vh_name_vc']),
                    'active' => $rowdomains['vh_active_in'],
                    'id' => $rowdomains['vh_id_pk'],
                ));
            }
            return $res;
        } else {
            return false;
        }
    }

    static function ListDomainDirs($uid)
    {
        global $controller;
        $currentuser = ctrl_users::GetUserDetail($uid);
        $res = array();
        $handle = @opendir(ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . "/public_html");
        $chkdir = ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . "/public_html/";
        if (!$handle) {
            # Log an error as the folder cannot be opened...
        } else {
            while ($file = @readdir($handle)) {
                if ($file != "." && $file != ".." && $file != "_errorpages") {
                    if (is_dir($chkdir . $file)) {
                        array_push($res, array('domains' => $file));
                    }
                }
            }
            closedir($handle);
        }
        return $res;
    }

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

    /**
     * Webinterface sudo methods.
     */
    static function getDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $res = array();
        $domains = self::ListDomains($currentuser['userid']);
        if (!fs_director::CheckForEmptyValue($domains)) {
            foreach ($domains as $row) {
                $res[] = array('name' => $row['name'],
                    'directory' => $row['directory'],
                    'active' => $row['active'],
                    'id' => $row['id']);
            }
            return $res;
        } else {
            return false;
        }
    }

 
    static function getResult()
    {
        if (!fs_director::CheckForEmptyValue(self::$blank)) {
            return ui_sysmessage::shout(ui_language::translate("Could you please upload a file."), "Error");
        }
        if (!fs_director::CheckForEmptyValue(self::$badname)) {
            return ui_sysmessage::shout(ui_language::translate("extension not allowed, please choose a War file. "), "Error");
        }
        if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate("The domain already appears to exist on this server."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$nosub)) {
            return ui_sysmessage::shout(ui_language::translate("You cannot add a Sub-Domain here. Please use the Subdomain manager to add Sub-Domains."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$error)) {
            return ui_sysmessage::shout(ui_language::translate("Upload failed. Try after sometimes."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$writeerror)) {
            return ui_sysmessage::shout(ui_language::translate("There was a problem writting to the virtual host container file. Please contact your administrator and report this error. Your domain will not function until this error is corrected."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("WAR file has been Uploaded successfully. Please wait  for sometimes for configure tomcat automatically in background."), "ok");
        }
		
        if (!fs_director::CheckForEmptyValue(self::$ok_switch)) {
            return ui_sysmessage::shout(ui_language::translate("Domain switch over the user successfully."), "Domain Ok");
        }
	if (!fs_director::CheckForEmptyValue(self::$output_set)) 
	{
            return ui_sysmessage::shout(ui_language::translate("<h2>Log:</h2><br/> ".self::$output), "Log:");
        }
		
        return;
    }
	
	
	static function changepermissionstart($java_file_path){
	self::commandcreation("command permissionstarttomcat $java_file_path");
	return;
	}
	static function changepermissionend($java_file_path){
	 self::commandcreation("command permissionendtomcat $java_file_path");
	
	return;
	}
	static function deploy($java_file_path){
	self::commandcreation("command deploytomcat $java_file_path");
	return;
	}
	static function tomcatrestart()
	{
	self::commandcreation("command restarttomcat");
	return;
	}
	
	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" => 1, "usec" =>0));
                $out = '';
                socket_write($socket, $in, strlen($in));
				socket_close($socket);
				sleep(1);
	}
    /**
     * Webinterface sudo methods.
     */
	 
}