octave interactive shell using php proc_open - php

I 'm writing a PHP code to be executed under apache (unfortunately under window OS by using xampp PHP 7.2.x). The PHP script should call an octave in an interactive way in order to be able to execute more commands in sequence without creating for each one a dedicated octave process.
here below an PHP script example.
I have a problem with the interactive working mode; I mean, I'm able to execute an octave script and have back the result but I'm not able to send several octave commands in sequence.
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to, you can specify a file as well
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q --eval disp(10)';
$process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($process)) {
die("PROCESS CREATION ERROR CMD: $cmd");
}
$str = "eval('disp(20)');\r\n" . chr(13);
if(fwrite($pipes[0],$str) === false){
die("fwrite ERROR");
}
$str = stream_get_contents($pipes[1]);
if($str === false){
die("stream_get_contents ERROR");
}else{
echo $str;
}
fclose($pipes[0]);
fclose($pipes[1]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
?>
In this case, the output is: 10 commands returned 0
Instead if define $cmd = $octave . ' --no-gui -i -q';
The script is blocked waiting for a returning charter to the stream_get_contents. Same result using fgets.
My understanding is that the fwrite command is not correctly received by an octave and so it doesn't print back the result (even if the fwrite doesn't return any error). Maybe the problem is due to the code to be sent as carriage return in order to tell to octave to execute the code. Moreover, it is not clear, if I should use the eval function or just write the command. However, in all tries done nothing is changed.
Any ideas?

Here below the code review, working if can be useful.
I have also created a dedicated class (octave_stream) in order to provide an interface that permits, for instance, an html pages to start a dedicated octave process ondemand (using a SSE communication) and then send one by one commands as ajax request. The sw will close the octave process whenever the user leave the page or after an unused time.
here below the whole code based on the following 4 files: octave.php, octave_sse.php, octave_com.php.
octave.php
<?php
class octave {
private $pipes = null;
private $process = null;
private $add_semicolon = false;
private $debug = false;
private $print = false;
function __destruct() {
$this->close_octave();
}
public function close_octave(){
if ($this->pipes !== null){
fclose($this->pipes[0]);
fclose($this->pipes[1]);
$return_value = proc_close($this->process);
if($this->debug){ echo "command returned $return_value<br>";}
return $return_value;
}
return false;
}
public function open_octave(){
$dir = sys_get_temp_dir();
$error_file_name = tempnam($dir, "npt");
$descriptorspec = array(
0 => array("pipe", "rb"), // stdin is a pipe that the child will read from
1 => array("pipe", "wb"), // stdout is a pipe that the child will write to
2 => array("file", $error_file_name,"a") // stderr:: you HAVE TO specify a file
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q';
$pipes = array();
$this->process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($this->process)) {
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
if (count($pipes) == 0){
echo 'pipes: '; var_dump($pipes); echo '<br>';
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
//stream_set_blocking($pipes[1],false); // doesn't work on STDIN / OUT
$this->pipes = $pipes;
$cmd_id = 0;
$this->read($cmd_id);
return true;
} //end open_octave
private function raw_read(){
$str = fread($this->pipes[1],8192);
if($str === false){
echo '<br>'. __FUNCTION__ . ' fgets ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//echo "READ: $str<br>";
return $str;
} //end read
private function read(&$cmd_num){
$result = '';
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ1: ' . $string; }
if($string[0] == '>'){
//special case, multiple line statement
if($this->debug){echo '<br>' . __FUNCTION__ . ' multiple line statement.' ; }
$cmd_num = -1;
return '';
}
$tok = strtok($string, "octave:");
while (($tok === false) || ($tok == $string)) {
//the response do not conatin the promt; therefore, other rows are coming, read them as well and concatenate to the current response
$result .= $string;
usleep(100);
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ NEXT: ' . $string; }
$tok = strtok($string, "octave:");
}
$cmd_num = -1;
//in this case string include the promt; nothing more to be read. tok is the string without the "ocatve:" but you still have the 'num>' to be removed.
$allTheRest = strtok( '' );
if(($allTheRest === false) || ($allTheRest == '')){
//tok has the promt rest
list($cmd_num) = sscanf($tok,'%u>');
}else{
$result .= $tok;
list($cmd_num) = sscanf($allTheRest,'ctave:%u>');
}
if($this->debug){echo '<br>' . __FUNCTION__ . " RAW_READ TOK: '$tok' STRING: '$string' RESULT: '$result' allTheRest: '$allTheRest' cmd_num: $cmd_num ## "; }
return $result;
}
//return the command answer removing the promt. Therefore, in case no retrun message command an empty string is given
public function octave_cmd($cmd,&$cmd_num){
if($this->add_semicolon){
$last_chr = strlen($cmd) - 1;
if(substr($cmd, $last_chr, 1) != ';'){
$cmd = $cmd . ';'; // adding ; at the input command required by octave
}
}
//echo "$cmd<br>";exit(0);
$cmd = $cmd . PHP_EOL ;// "\r\n"
if(fwrite($this->pipes[0],$cmd) === false){
echo '<br>'. __FUNCTION__ . ' fwrite ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//usleep(100); // needed when more output row are given ... without this you read before the progam write the next row ... and you lost it ... a nice solution anyway should be to read again unil you find the promt that is always the latest given.
$ret = $this->read($cmd_num);
if($this->print){
echo "<br>COMMAND # $cmd_num: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
return $ret;
}
public function print_cmd($cmd){
$cmd_id = 0;
$ret = $this->octave_cmd($cmd,$cmd_id);
echo "<br>COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
}
class octave_stream {
private $address = 'tcp://127.0.0.1';
private $port = 5454;
private $errno = 0;
private $errstr = '';
private $server_istance = false;
private $sse = false;
/*This function start octave process, open a tcp connection and waits for incoming commands.
(to send the commands use the func. send_cmd)
Each command received is forwared to octave and the ocatve answer is forwared to who sent the command.
To stop the server a special command has to be sent. The caller has to use the stop_server()
*/
public function create_server($accept_max_retray = 30){
$this->server_istance = true; // first command to be done
$available_port = $this->find_usable_listening_port($this->port);
if($available_port === false){
$this->server_log('NOT FOUND AN AVAILABLE PORT TO START THE LISTENING SERVER');
return false;
}else{
$this->port = $available_port;
}
$oct_obj = new octave();
if(!$oct_obj->open_octave()){
return false;
}
$this->server_log('OCTAVE PROCESS STARTED');
$cmd_id = 0;
$server_socket_address = 'tcp://127.0.0.1:' . $this->port;
$socket = stream_socket_server($server_socket_address, $errno, $errstr);
if (!$socket) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
$oct_obj->close_octave();
$this->server_log("<b>LISTENING SOCKET CREATION ERROR: $this->errstr</b>");
return false;
}
$exit = false;
$this->server_log("LISTENING SOCKET CREATED: $server_socket_address DEFAULT SOCKET TIMEOUT:" . ini_get("default_socket_timeout"));
$this->server_log($server_socket_address,'server_ready'); // dedicated event type sent, html page has a dedicated event listener on it
$accept_retray = -1;
$conn_id = 0;
do{
$accept_retray += 1;
while ($conn = stream_socket_accept($socket)) {
$this->server_log("LISTENING SOCKET CONNECTION ACCEPTED: $conn_id");
$accept_retray = -1;
//cmd: received octave command request to be sent to octave
$cmd = '';
$cmd = fread($conn,8192);
if($cmd === false){
$this->server_log( __FUNCTION__ . "[$conn_id] fread ERROR for CMD: " . htmlentities($cmd));
return false;
}
$this->server_log("[$conn_id] RECEIVED RAW COMMAND: $cmd");
if(strpos($cmd, '#exit#') !== false){
//special command EXIT
$this->server_log("[$conn_id] RECEIVED EXIT COMMAND.");
fwrite($conn,self::prefix($conn_id) . 'RECEIVED EXIT COMMAND.'); // you need always to send an answer to the calling (it is waiting on read it
$exit = true;
}else if (strpos($cmd, '#loopback:') !== false) {
//special command LOOPBACK
$this->server_log("[$conn_id] RECEIVED LOOPBACK COMMAND: $cmd");
fwrite($conn,self::prefix($conn_id) . $cmd); // you need always to send an answer to the calling (it is waiting on read it
} else {
//OCATVE COMMAND
$this->server_log("[$conn_id] RECEIVED COMMAND FOR OCTAVE: $cmd");
$cmd_id = 0;
$ret = $oct_obj->octave_cmd($cmd,$cmd_id);
$this->server_log("[$conn_id] COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>');
fwrite($conn,self::prefix($conn_id) . 'RESULT:'. $ret);
$this->server_log("[$conn_id] SENT ANSWER: RESULT:". $ret);
}
fclose($conn);
$this->server_log("[$conn_id] CLOSE CONNECTION");
$conn_id++;
if($exit) break;
}
if($exit) break;
//note, calling the server_log func here you are testing the socket between this script and the html pages. If the sse connection is no more working, the PHP engine will close this script.
$this->server_log("LISTENING SOCKET CONNECTION TIMEOUT RETRAY: $accept_retray MAX_RETRAY: $accept_max_retray");
}while($accept_retray < $accept_max_retray);
$this->server_log($server_socket_address,'server_stopped'); // dedicated event type sent
fclose($socket);
$this->server_log('SOCKET CLOSED.');
unset($oct_obj);
$this->server_log('OCTAVE PROCESS STOPPED.');
return true;
} // end start_server
private static function prefix($conn_id){
return "[$conn_id] [" . date('n/j/Y g:i:s a') .'] ';
}
//return the ocatve command answer to be encoded e.g. json to be delivered to the http page or false
public function send_cmd($cmd){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
return false;
}
$ret = '';
$fp = stream_socket_client($this->address . ':' .$this->port , $errno, $errstr, 30);
if ($fp === false) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
return false;
} else {
//fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
}
return $ret;
} // end send_cmd
//return false or the server answer
public function stop_server(){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#exit#');
} //
//return false or the server answer
public function loopback_msg($msg){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#loopback:' . $msg);
}
public function get_errstr(&$errno){
$ret = $this->errstr;
$this->errstr = '';
$errno = $this->errno;
$this->errno = 0;
return $ret;
}
//$ip_name: IP or dns name
public function set_address_connection($ip_name,$port){
$this->address = 'tcp://' . $ip_name ;
$this->port = $port;
}
//str can be encoded as json if you need to transfert more data field.
//see: https://www.html5rocks.com/en/tutorials/eventsource/basics/
private function server_log($str,$event_name = ''){
$msg = '<br>[' . date('n/j/Y g:i:s a') .'] '. $str ;
if($this->sse){
if($event_name != ''){
echo "event: $event_name" . PHP_EOL;
echo "data: $str" . PHP_EOL;
}else{
echo "data: $msg" . PHP_EOL;
}
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
public function set_sse($sse){
$this->sse = $sse;
}
private function check_server_running_on_port($port,&$ret_errstr,&$errno){
if(!$this->server_istance){
$ret_errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$msg = __FUNCTION__ . ' PORT CHECK: ' . $port;
$cmd = '#loopback:' . $msg; // you cannot change it, is the defined loopback command
$fp = stream_socket_client($this->address . ':' .$port , $errno, $errstr, 30);
if ($fp === false) {
$ret_errstr = "$errstr ($errno)<br />\n";
return false;
}
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
return true;
}
private function find_usable_listening_port($start_port){
if(!$this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$this->errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$max_port = $start_port +10;
$port = $start_port;
do{
//ret = true server running, so I need to find another unused port
$ret = $this->check_server_running_on_port($port,$ret_errstr,$errno);
if($ret){
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port ALREADY USED.");
}else{
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port NOT USED. GIVEN ERROR: $ret_errstr" );
return $port;
}
$port++;
if($port > $max_port) return false;
}while($ret);
return false;
}
} // end class
?>
octave_sse.php
<?php
/* this page should be called by the web page as sse
this page calling the create_server func start the octave process and the communication server as well.
The function return only when the exit command is received over the server channel created.
Then the page has to send a polling to the web page to test the presence of the page itself.
*/
function sendMsg($sse,$msg) {
if($sse){
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
$sse = false;
if(isset($_GET['sse'])){
if($_GET['sse'] > 0){
$sse = true;
}
}
if($sse){
header('Content-Type: text/event-stream');
}else{
header( 'Content-type: text/html; charset=utf-8' );
}
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
require 'octave.php';
set_time_limit(4000);
$oct_server_obj = new octave_stream();
if($sse){
$oct_server_obj->set_sse(true);
}
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] CALLING create_server.<br>');
$ret = $oct_server_obj->create_server();
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server EXIT. return: '. (($ret)?'TRUE':'FALSE').'<br>');
//you are here only at the end when the web page send the exit command to the created server
do{
sleep(2);
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server PING<br>');
}while(true);
?>
octave_com.php
<?php
/*
This page is called using a json post request from web page.
Each request has a octave command. special param is to terminate the server.
*/
/** Error reporting: this is not used since you are using myErrorHandler */
if($_SERVER['SERVER_NAME'] == "localhost"){ // my PC
error_reporting(E_ALL);
}else{
error_reporting(E_ERROR | E_PARSE);
}
//http://php.net/manual/it/errorfunc.configuration.php#ini.display-errors
/* The errors are redirect over the stderr and not over the stdout.
In this way, you have to properly send the error using json without using the set_error_handler.
ini_set('display_errors','Off');
//ini_set('display_errors','On');
*/
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
if (0 === error_reporting()) { return false;}
$errorType = array (
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSING ERROR',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE ERROR',
E_CORE_WARNING => 'CORE WARNING',
E_COMPILE_ERROR => 'COMPILE ERROR',
E_COMPILE_WARNING => 'COMPILE WARNING',
E_USER_ERROR => 'USER ERROR',
E_USER_WARNING => 'USER WARNING',
E_USER_NOTICE => 'USER NOTICE',
E_STRICT => 'STRICT NOTICE',
E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR');
// create error message
if (array_key_exists($errno, $errorType)) {
$err = $errorType[$errno];
} else {
$err = 'CAUGHT EXCEPTION';
}
if($_SERVER['SERVER_NAME'] != "localhost"){ // not my PC
if (!($errorType == E_ERROR ) || ($errorType == E_PARSE ))
return;
}
$str_err = "$err($errno) <br> in line: " .$errline. " of file: " .$errfile . " <br> PHP: " . PHP_VERSION . " (". PHP_OS .")<br> $errstr";
terminate($str_err);
} // end myErrorHandler
// configura il gestore dell'errore definito dall'utente
$old_error_handler = set_error_handler("myErrorHandler");
// functions
function terminate($str_err, $txt=false){
if($txt){
die($str_err);
}
header("Content-Type: application/json;charset=utf-8");
echo json_encode(array("result"=>"false","error"=>$str_err));
exit(0);
} // end terminate
require 'octave.php';
if(isset($_POST['send_loopback'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->loopback_msg($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'loopback_msg' => $msg)) ;
exit(0);
} // end send_loopback
if(isset($_POST['send_octave_msg'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->send_cmd($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
$pos = strpos($msg,'RESULT:');
$ret = trim(substr($msg,$pos+strlen('RESULT:')));
$ret = nl2br(htmlentities($ret));
echo json_encode(array('result' => 'true', 'error' => '', 'msg' => $msg, 'return' => $ret)) ;
exit(0);
} // end send_octave_msg
if(isset($_GET['send_exit_msg'])){
$address = '';
$ip='';
$port = 0;
if(isset($_GET['address'])){
$address = $_GET['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>' . "ADDRESS: $address IP: $ip PORT: $port<br>" ;
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->stop_server();
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'return' => $msg)) ;
exit(0);
} // end send_exit_msg
?>

The html web page to be used together with the above code.
octave_shell.html:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.css">
<link rel="stylesheet" href="../../libs/messi/messi.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.js"></script>
<script src="../../libs/messi/my_messi.min.js"></script>
<script src="../../libs/chosen/chosen.jquery.min.js"></script>
<title>OCTAVE SHELL</title>
</head>
<body>
<h2>OCTAVE WEB INTERFACE</h2>
<script type="text/javascript">
var server_ready = false; // true, octave process running and ready to accept commands
var sse_source; // sse_obj
var octave_close_req = false; // true when the user stop octave
var address = ''; //address on which the server is in listening for commands at server side
function clearArray(array_tbc){
array_tbc.splice(0,array_tbc.length); // set the array to empty
array_tbc.length = 0;
}
function isParamExist(paramName){
if($.inArray(paramName,Object.getOwnPropertyNames(urlParams)) > -1){
console.log("isParamExist:" + paramName + " return TRUE");
return true;
}
console.log("isParamExist:" + paramName + " return FALSE");
return false;
} //end isParamExist
function getParam(urlParams) {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
console.log(Object.getOwnPropertyNames(urlParams));
} //end getParam
function octave_close(){
octave_close_req = true;
$.getJSON('octave_com.php',
{send_exit_msg: 1,
address: address},
function(data) {
if(data.result == "true"){
$('#octave_shell').append("<p><b>"+ data.return +"</b></p>" );
}else{
//alert("Error : " + data.error);
new Messi('Error : ' + data.error, {title: 'ERROR from JSON', titleClass: 'anim error', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
}
);
} //end octave_close
function ping_server(){
var message = 'HELLO!';
$.post( "octave_com.php",
{ send_loopback: 1,
address: address,
message: message } ,
function( data ) {
if(data.result == 'true'){
var msg = data.loopback_msg;
$('#octave_shell').append("<p><b>"+ msg +"</b></p>" );
}else{
var err = data.error;
new Messi("LOOPBACK ERROR: err: " + err, {title: 'LOOPBACK MESSAGE', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end ping_server
function send_octave_cmd(cmd){
$.post( "octave_com.php",
{ send_octave_msg: 1,
address: address,
message: cmd } ,
function( data ) {
if(data.result == 'true'){
var msg = data.return;
if(msg == '') msg = 'OK';
$('#octave_shell').append("<p>OCTAVE ANSWER: " + msg + "</p>");
console.log('OCTAVE MESSAGE: ' + data.msg);
}else{
var err = data.error;
new Messi("OCTAVE COMMAND: err: " + err, {title: 'OCTAVE COMMAND ERROR', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end send_octave_cmd
$(function(){
if(typeof(EventSource) !== "undefined") {
sse_source = new EventSource("octave_sse.php?sse=1");
sse_source.onmessage = function(event) {
console.log('SSE MSG: ' + event.data);
document.getElementById("sse_log").innerHTML += event.data + "<br>";
};
sse_source.addEventListener('open', function(e) {
// Connection was opened.
console.log('SSE OPEN.');
document.getElementById("sse_log").innerHTML += 'SSE OPEN.' + "<br>";
}, false);
sse_source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
// Connection was closed.
server_ready = false;
console.log('SSE CLOSED.');
document.getElementById("sse_log").innerHTML += 'SSE CLOSED.' + "<br>";
}
}, false);
//user defined event types
sse_source.addEventListener('server_ready', function(e) {
// server_ready event received.
server_ready = true;
address = e.data;
console.log('SSE server_ready EVENT ADDR: ' + address);
$('#octave_status').text('SERVER READY TO ACCEPT OCTAVE COMMANDS ON: '+ address);
}, false);
sse_source.addEventListener('server_stopped', function(e) {
// server_stopped event received.
server_ready = false;
console.log('SSE server_stopped EVENT');
setTimeout(function(){ sse_source.close(); }, 3000); //close the sse connection as well, you don't need anymore.
if(!octave_close_req){
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'OCTAVE PROCESS STOPPED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}else{
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR USER DECISION. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'YOU HAVE CLOSED CORRECTLY THE OCTAVE PROCESS. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}
}, false);
} else {
alert('NO SSE SUPPORT. Please do not use an obsolete browser!');
}
$('#close_octave_id').click(function() {
console.log('CLOSE OCTAVE REQUEST');
octave_close();
});
$('#send_ping_id').click(function() {
console.log('PING DISPATCHER SERVER REQUEST');
ping_server();
});
$('#send_octave_cmd_id').click(function() {
var cmd = $('#write_octave_cmd_id').val();
//console.log('SEND OCTAVE CMD REQUEST: ' + cmd);
$('#octave_shell').append("<p>OCTAVE: " + cmd + "</p>");
send_octave_cmd(cmd);
$('#write_octave_cmd_id').val('');
});
$('#write_octave_cmd_id').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('#send_octave_cmd_id').click();
return false;
}
});
//getParam(urlParams);
/*
if(!isParamExist('json_file_net_name')){
//load the NPT results
loadNPTData();
}else{
// load DESIGN results
loadJSONData();
}
*/
}); // end startup page
</script>
<div id='octave_cmd'>
<h4>Write your OCTAVE commands here, press enter or click on SEND OCTAVE CMD to execute them.<br>
<b>IMPORTANT: </b>Don't forget to terminate the commands with semicolon as per OCTAVE syntax.</h4>
<br><p>Some example commands: disp(10) just to print 10,<br>
to solve a non linear system equation writes the following commands line by line pressing enter for each row:<br>
<i>function y = test6(x)<br>
y(1) = 18.028*cosd(x(1))+10*cosd(45)-15*cosd(x(2))<br>
y(2) = 18.028*sind(x(1))+10*sind(45)-15*sind(x(2))<br>
endfunction<br>
[x, fval, info] = fsolve(#test6, [0;0]);<br>
disp(x);<br>
disp(info);</i><br>
</p><br>
</div><br>
<br><a href='#' id='close_octave_id' >CLOSE OCTAVE - CLICK WHEN YOU HAVE TERMINATED.</a><br>
<br><a href='#' id='send_ping_id' >PING DISPATCHER SERVER </a><br>
<div id='octave_status'></div>
<br><div id='octave_shell'><h4>OCTAVE SHELL:</h4><br></div><br>
<input type='text' id='write_octave_cmd_id' size="400"><br>
<a href='#' id='send_octave_cmd_id' >SEND OCTAVE CMD</a>
<br><div id='sse_log'><h4>SSE LOG:</h4><br></div><br>
</body>
</html>

Related

GameServerQuery how to check if server is online & count online players?

I want to check if a quake3 game server is online or offline. If offline then echo 'Server is offline' if online then echo 'Server is online'.
I'm using this library:
As you see in the library there's already an isOnline function I think that's for server is online or no?! but I don't know how to output that.
Calling the game server data's:
<?php
include 'test/GameServerQuery.php';
$data = GameServerQuery::queryQuake3('1.1.1.1', 28960);
echo 'Hostname: ' . $data['sv_hostname'] . '<br />';
echo 'Players online: ' . $data['sv_maxclients'] . '<br />'; /// How can I count online players / maxclients? ex.: 0/20
echo 'Punkbuster: ' . $data['sv_punkbuster'] . '<br />';
?>
Here is relevant code from the library (in case the link should die or change):
public static function isOnline ($host, $port, $type)
{
if ($type == 'minecraft') { // No need for the full ping
return #fclose (#fsockopen ( $host , $port , $err , $errstr , 2 ));
}
if (method_exists('GameServerQuery', 'query'.$type)) {
return self::{'query'.$type}($host , $port);
}
return #fclose (#fsockopen ( $host , $port , $err , $errstr , 2 ));
}
public static function queryQuake3($host, $port)
{
$reponse = self::ping($host, $port, "\xFF\xFF\xFF\xFFgetstatus\x00");
if ($reponse === false || substr($reponse, 0, 5) !== "\xFF\xFF\xFF\xFFs") {
return false;
}
$reponse = substr($reponse, strpos($reponse, chr(10))+2);
$info = array();
$joueurs = substr($reponse, strpos($reponse,chr(10))+2);
$reponse = substr($reponse, 0, strpos($reponse, chr(10)));
while($reponse != ''){
$info[self::getString($reponse, '\\')] = self::getString($reponse, '\\');
}
if (!empty($joueurs)) {
$info['players'] = array();
while ($joueurs != ''){
$details = self::getString($joueurs, chr(10));
$info['players'][] = array('frag' => self::getString($details, ' '),
'ping' => self::getString($details, ' '),
'name' => $details);
}
}
return $info;
}
private static function ping($host, $port, $command)
{
$socket = #stream_socket_client('udp://'.$host.':'.$port, $errno, $errstr, 2);
if (!$errno && $socket) {
stream_set_timeout($socket, 2);
fwrite($socket, $command);
$buffer = #fread($socket, 1500);
fclose($socket);
return $buffer;
}
return false;
}
private static function getString(&$chaine, $chr = "\x00")
{
$data = strstr($chaine, $chr, true);
$chaine = substr($chaine, strlen($data) + 1);
return $data;
}
It's a static function, just like the one you're already calling. Something like this would do the job, I think:
$result = GameServerQuery::isOnline('1.1.1.1', 28960, "Quake3");
print_r($result);
That will show you what result you get back. I suspect it will be the same as the queryQuake3 function actually, because if you specify "Quake3" as the last parameter, the isOnline function will simply call the "queryQuake3" function and pass the result back directly.
So, the function should return either false if the server is offline or otherwise unresponsive, and either true, or a more complex dataset if it's online.
So in fact I think you could write:
$result = GameServerQuery::isOnline('1.1.1.1', 28960, "Quake3");
if ($result === false) {
echo "Server is offline";
}
else {
echo "Server is online";
}

Amazon Product Advertising API 5.0 with SDK php return error 500

In a list of Amazon products that I retrieve by analyzing the WordPress database, I have this code that allows me to get product by product their Amazon information:
function get_product_infos(asin, ext){
$.post(window.location.href, {
activate: 'get-product-informations',
asin: asin,
ext: ext
}, function(data){
//var json = JSON.parse(data);
console.log(data);
/*if(json.response === 'alright'){
var current_asin = json.current_asin;
current_asin = $('#'+current_asin);
var next_asin = current_asin.next().attr('id');
var next_ext = current_asin.next().attr('data-domain-ext');
current_asin.find('td').first().find('.progress').text('ok');
if(typeof next_asin !== typeof undefined && next_asin !== false){
get_product_infos(next_asin, next_ext);
}
}*/
});
}
File called with $.post() to have the product information from Amazon:
<?php
$autorisation = isset($_POST['activate']) ? $_POST['activate'] : '';
$current_asin = isset($_POST['asin']) ? $_POST['asin'] : '';
$current_ext = isset($_POST['ext']) ? $_POST['ext'] : '';
if($autorisation !== 'get-product-informations'){
return;
}
use pa\src\com\amazon\paapi5\v1\api\DefaultApi;
use pa\src\ApiException;
use pa\src\Configuration;
use pa\src\com\amazon\paapi5\v1\GetItemsRequest;
use pa\src\com\amazon\paapi5\v1\GetItemsResource;
use pa\src\com\amazon\paapi5\v1\PartnerType;
use pa\src\com\amazon\paapi5\v1\ProductAdvertisingAPIClientException;
require_once(plugin_dir_url( __FILE__ . '/bundles/admin-pages/tool/crawling-system/pa/vendor/autoload.php' ));
function parseResponse($items){
$mappedResponse = array();
foreach ($items as $item) {
$mappedResponse[$item->getASIN()] = $item;
}
return $mappedResponse;
}
function getItems(){
global $wpdb;
$prefix_table = $wpdb->prefix;
$table_name = $prefix_table.'azon_lc';
$result = ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name) ? $wpdb->get_results("SELECT * FROM $table_name") : '';
$access_key = ($result !== '') ? $result[0]->access_key : '';
$secret_key = ($result !== '') ? $result[0]->secret_key : '';
$associate_tag = ($result !== '') ? $result[0]->associate_tag : '';
$config = new Configuration();
/*
* Add your credentials
* Please add your access key here
*/
$config->setAccessKey($access_key);
# Please add your secret key here
$config->setSecretKey($secret_key);
# Please add your partner tag (store/tracking id) here
$partnerTag = $associate_tag;
/*
* PAAPI host and region to which you want to send request
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
$config->setHost('webservices.amazon.'.$current_ext);
$config->setRegion('us-east-1');
$apiInstance = new DefaultApi(
/*
* If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
* This is optional, `GuzzleHttp\Client` will be used as default.
*/
new pa\vendor\GuzzleHttp\guzzle\src\Client(), $config);
# Choose item id(s)
$itemIds = array($current_asin);
/*
* Choose resources you want from GetItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter
*/
$resources = array(
GetItemsResource::ITEM_INFOTITLE,
GetItemsResource::OFFERSLISTINGSPRICE);
# Forming the request
$getItemsRequest = new GetItemsRequest();
$getItemsRequest->setItemIds($itemIds);
$getItemsRequest->setPartnerTag($partnerTag);
$getItemsRequest->setPartnerType(PartnerType::ASSOCIATES);
$getItemsRequest->setResources($resources);
# Validating request
$invalidPropertyList = $getItemsRequest->listInvalidProperties();
$length = count($invalidPropertyList);
if ($length > 0) {
echo "Error forming the request", PHP_EOL;
foreach ($invalidPropertyList as $invalidProperty) {
echo $invalidProperty, PHP_EOL;
}
return;
}
# Sending the request
try {
$getItemsResponse = $apiInstance->getItems($getItemsRequest);
echo 'API called successfully', PHP_EOL;
echo 'Complete Response: ', $getItemsResponse, PHP_EOL;
# Parsing the response
if ($getItemsResponse->getItemsResult() != null) {
echo 'Printing all item information in ItemsResult:', PHP_EOL;
if ($getItemsResponse->getItemsResult()->getItems() != null) {
$responseList = parseResponse($getItemsResponse->getItemsResult()->getItems());
foreach ($itemIds as $itemId) {
echo 'Printing information about the itemId: ', $itemId, PHP_EOL;
$item = $responseList[$itemId];
if ($item != null) {
if ($item->getASIN()) {
echo 'ASIN: ', $item->getASIN(), PHP_EOL;
}
if ($item->getItemInfo() != null and $item->getItemInfo()->getTitle() != null
and $item->getItemInfo()->getTitle()->getDisplayValue() != null) {
echo 'Title: ', $item->getItemInfo()->getTitle()->getDisplayValue(), PHP_EOL;
}
if ($item->getDetailPageURL() != null) {
echo 'Detail Page URL: ', $item->getDetailPageURL(), PHP_EOL;
}
if ($item->getOffers() != null and
$item->getOffers()->getListings() != null
and $item->getOffers()->getListings()[0]->getPrice() != null
and $item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() != null) {
echo 'Buying price: ', $item->getOffers()->getListings()[0]->getPrice()
->getDisplayAmount(), PHP_EOL;
}
} else {
echo "Item not found, check errors", PHP_EOL;
}
}
}
}
if ($getItemsResponse->getErrors() != null) {
echo PHP_EOL, 'Printing Errors:', PHP_EOL, 'Printing first error object from list of errors', PHP_EOL;
echo 'Error code: ', $getItemsResponse->getErrors()[0]->getCode(), PHP_EOL;
echo 'Error message: ', $getItemsResponse->getErrors()[0]->getMessage(), PHP_EOL;
}
} catch (ApiException $exception) {
echo "Error calling PA-API 5.0!", PHP_EOL;
echo "HTTP Status Code: ", $exception->getCode(), PHP_EOL;
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
if ($exception->getResponseObject() instanceof ProductAdvertisingAPIClientException) {
$errors = $exception->getResponseObject()->getErrors();
foreach ($errors as $error) {
echo "Error Type: ", $error->getCode(), PHP_EOL;
echo "Error Message: ", $error->getMessage(), PHP_EOL;
}
} else {
echo "Error response body: ", $exception->getResponseBody(), PHP_EOL;
}
} catch (Exception $exception) {
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
}
}
getItems();
exit;?>
I tested the file in several ways to understand when there was an error and I determined that by trying to use this code it crashes:
$config = new Configuration();
I would like to determine why the call returns a 500 error? There is obviously something that I do not understand.

fsockopen(): unable to connect when using ajax

I am required to get domain information so I wrote this function
$servers = array(
"biz" => "whois.neulevel.biz",
"com" => "whois.internic.net",
function whois($domainName, $ext)
{
$server = trim($this->servers[$ext]);
$output = "";
try {
if ($conn = fsockopen($server, 43)) {
fputs($conn, strtolower($domainName) . '.' . $ext . "\r\n");
while (!feof($conn)) {
$output .= fgets($conn, 128);
}
fclose($conn);
if (stristr($output, "No match") ||
stristr($output, "No Data") ||
stristr($output, "No entries") ||
stristr($output, "No entries") ||
stristr($output, "NOT FOUND")) {
$this->durum[$ext]["durum"] = "bos";
} else {
$this->durum[$ext]["durum"] = "dolu";
// $this->durum[$ext]["son"] =substr($output)
}
$bas = strpos($output, "Expiry Date:");
$t = substr($output, $bas, 23);
$tarih = str_replace("Expiry Date:", "", $t);
$this->durum[$ext]["son"] = $tarih;
} else {
}
} catch (exception $e) {
echo $e->getMessage();
}
this function works fine without using ajax The problem is if I use ajax I realized that Its not working second time without waiting 10 or 15 seconds.
this my ajax code
$.ajax({
type: "POST",
url: "islem.php",
beforeSend:function(){
$('#table').html("")
$('.load').show()
},
data: {
extension:myCheckboxes,domainName:domainName },
success:function (e) {
$('#table').html(e)
}
Am I missin out something Why should I wait to execute second time

proc_open called only one time in foreach loop

class CommandExecuter {
const EXEC_FAILED = "EXEC_FAILED";
public function execute($cmd, $sleep, $descriptors, $progressCallback, $progressCallbackParams, $showProgress = false, $callbackTurns = 0) {
log_out("INFO", basename(__FILE__), "Executing: $cmd");
// Start execution of $cmd
if (!($process = proc_open($cmd, $descriptors, $pipes)) || !is_resource($process)) {
throw new CTException("Unable to execute command:\n$cmd\n", self::EXEC_FAILED);
}
// Set the pipes as non-blocking
if (isset($descriptors[1]) && $descriptors[1]) {
stream_set_blocking($pipes[1], FALSE);
}
if (isset($descriptors[2]) && $descriptors[2]) {
stream_set_blocking($pipes[2], FALSE);
}
if ($callbackTurns) {
$i = 0;
}
// Used to store all output
$allOut = "";
$allOutErr = "";
// Check process status at every turn
$procStatus = proc_get_status($process);
while ($procStatus['running']) {
// Read prog output
if (isset($descriptors[1]) && $descriptors[1]) {
$out = fread($pipes[1], 8192);
$allOut .= $out;
}
// Read prog errors
if (isset($descriptors[2]) && $descriptors[2]) {
$outErr = fread($pipes[2], 8192);
$allOutErr .= $outErr;
}
// If callback only after N turns
if ($callbackTurns) {
if ($i == $callbackTurns) {
if ($showProgress) {
echo ".\n";
}
// Call user provided callback.
// Callback should be an array as per doc here:
// http://www.php.net/manual/en/language.types.callable.php
// Type 3: Object method call
if (isset($progressCallback) && $progressCallback) {
call_user_func($progressCallback, $progressCallbackParams, $allOut, $allOutErr);
}
$i = 0;
}
} else {
// Call user provided callback.
// Callback should be an array as per doc here:
// http://www.php.net/manual/en/language.types.callable.php
// Type 3: Object method call
if (isset($progressCallback) && $progressCallback) {
call_user_func($progressCallback, $progressCallbackParams, $allOut, $allOutErr);
}
}
// Get latest status
$procStatus = proc_get_status($process);
if ($showProgress) {
echo ".";
flush();
}
if ($callbackTurns) {
$i++;
}
sleep($sleep);
}
if ($showProgress) {
echo "\n";
}
// Process is over
proc_close($process);
return array('out' => $allOut, 'outErr' => $allOutErr);
}
}
following scenario: when i put the executer command into an foreach loop the executer gets only one time called and the rest of the foreach loop are dead or hangs forever.
So what is wrong ?
Here is the call...
$out = $this->executer->execute('some call', 1, array(2 => array("pipe", "w")), false, false, false, 1);
Regards Sascha
Solved it the class is written without errors.
I solved it in the programm.
On the cli have forgotten the -y force overwrite parameter.
Thanks Sascha

Executing a PHP script from within nested batch scripts

I'm trying to rewrite our Windows FTP server configuration script that was created for IIS and now we're trying to get something similar working for Filezilla Server.
The structure goes like this, we have a batch file which is a for loop of another batch file, so we can batch configure our FTP websites. This batch file I'm currently trying to get working contains a line of code to execute a PHP script to set up the FTP username and password in Filezilla as well as doing a few other neat things.
Now, running CreateIIStmp.bat var1 var2 works just fine. But executing the BatchCreateIIS.bat seems to skip the execution of the php script, or the php script fails. (I'm just looking into how I put in some error handling into the PHP script to catch any error and display it, but I'm not a (PHP) developer/coder so I'll be updating this when I figure it out.)
Here's a stripped down version of what I'm talking about:
The initial batch file BatchCreateIIS.bat:
#Echo off
for /f %%X in (NewWebsiteEntries.txt) do start cmd.exe /c "CreateIIStmp.bat %%X %%X"
echo ...
echo *** BATCH PROCESS HAS BEEN COMPLETED ***
pause
The CreateIIStmp.bat:
# echo off
C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2
pause
#echo on
The NewWebsiteEntries.txt:
somedomain.com ftpuname
somedomain2.net ftpuname2
The filezilla-user-script.php:
<?php
$xmlfolder = 'C:/Program Files (x86)/FileZilla Server/';
$xmlfilename = 'FileZilla Server.xml';
$ftpRoot = 'C:/inetpub/wwwroot/';
$ftpDocumentation = 'C:/Documentation ftp server/';
$xmlfile = $xmlfolder . $xmlfilename;
$xmlbackupfile = $xmlfolder . #date("Y-m-d-H-i-s") . '_FileZilla_Server.xml';
// Copy Config for backup
createXMLbackup($xmlfile,$xmlbackupfile);
//Load XML file
$xml = simplexml_load_file($xmlfile);
$msg = "Allowed usernames: 20 characters out of a...z A...Z 0...9 _ \n\nPlease input username (Ctrl+C to quit)";
// Copy Config for backup before each change, too.
createXMLbackup($xmlfile,$xmlbackupfile);
echo "\n\n";
$input = ($argv[2]);
echo "\n";
//echo 'Userinput: ' . $input . "\n";
$isvalid = isUserID($input);
//var_dump($isvalid);
if($isvalid)
{
$ftpUserFolder = $ftpRoot . ($argv[1]);
if ((file_exists($ftpUserFolder) && is_dir($ftpUserFolder)))
{
echo "The directory $ftpUserFolder exists.\nPlease select another user name.\n";
}
else
{
//echo "The directory $ftpUserFolder does not exist\n";
if(!check_user_exists($xml,$input))
{
echo "Adding user $input...\n";
if (!mkdir($ftpUserFolder))
{
die("Could not create directory $ftpUserFolder \n");
}
else
{
echo "Directory $ftpUserFolder created.\n";
}
$password = generatePassword();
//echo 'Password: ' . $password . "\n";
$user = $xml->Users->addChild('User');
$user->addAttribute('Name', $input);
$option = $user->addChild('Option', md5($password));
$option->addAttribute('Name', 'Pass');
$option = $user->addChild('Option');
$option->addAttribute('Name', 'Group');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'Bypass server userlimit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'User Limit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'IP Limit');
$option = $user->addChild('Option', '1');
$option->addAttribute('Name', 'Enabled');
$option = $user->addChild('Option', 'none');
$option->addAttribute('Name', 'Comments');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'ForceSsl');
$filter = $user->addChild('IpFilter');
$filter->addChild('Disallowed');
$filter->addChild('Allowed');
$permissions = $user->addChild('Permissions');
$permission = $permissions->addChild('Permission');
$permission->addAttribute('Dir', str_replace("/","\\",$ftpUserFolder));
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileRead');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileWrite');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'FileDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileAppend');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirCreate');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'DirDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirList');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirSubdirs');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'IsHome');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'AutoCreate');
$speed = $user->addChild('SpeedLimits');
$speed->addAttribute('DlType', '1');
$speed->addAttribute('DlLimit', '10');
$speed->addAttribute('ServerDlLimitBypass', '0');
$speed->addAttribute('UlType', '1');
$speed->addAttribute('UlLimit', '10');
$speed->addAttribute('ServerUlLimitBypass', '0');
$speed->addChild('Download');
$speed->addChild('Upload');
$rv = $xml->asXML($xmlfile);
//echo $rv . "\n";
if(!$rv)
{
die('SimpleXML could not write file');
}
//$newentry = $xml->addChild('element', iconv('ISO-8859-1', 'UTF-8', $write));
//The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode()
//to work with texts in ISO-8859-1 encoding or Iconv for other encodings.
//make human readable, parse using DOM function
//otherwise everything will be printed on one line
if( !file_exists($xmlfile) ) die('Missing file: ' . $xmlfile);
else
{
$dom = new DOMDocument("1.0","ISO-8859-1");
//Setze die Flags direkt nach dem Initialisieren des Objektes:
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
//$dl = #$dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
$dl = $dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlfile);
//echo $dom->save($xmlfile) . "\n";
if(!$dom->save($xmlfile))
{
die('DOMDocument could not write file');
}
}
//Create documentation
$docuFile = $ftpDocumentation . $input . '.txt';
//echo $docuFile . "\n";
$docuString = "Username: " . $input . "\n";
$docuString = $docuString . "Password: " . $password . "\n";
$docuString = $docuString . "Folder: " . str_replace("/","\\",$ftpUserFolder) . "\n";
$docuString = $docuString . "Date: " . #date("d.m.Y") . "\n";
// $docuString = $docuString . "\n";
// $docuString = $docuString . "Direct link:\n";
// $docuString = $docuString . "ftp://" . $input . ":" . $password . "#ftp.yourcompany.com";
$handleDocuFile = fopen($docuFile, "wt");
if(!$handleDocuFile)
{
die('Could not fopen docu file');
}
$rv = fwrite($handleDocuFile, $docuString);
if(!$rv)
{
die('Could not fwrite docu file');
}
// Close xml file
$rv = fclose($handleDocuFile);
if(!$rv)
{
die('Could not fclose docu file');
}
echo "Documentary file written.\n";
$ftpExecutable = "\"C:\\Program Files (x86)\\FileZilla Server\\FileZilla server.exe\" /reload-config";
$command = $ftpExecutable;
$last_line = system($command, $retval);
echo ("Filezilla reloaded, user active.\n");
echo ("Close Notepad to add another user or quit.\n");
$command = "C:\\Windows\\System32\\notepad.exe $docuFile";
$last_line = system($command, $retval);
}
else
{
echo "Username $input already exists...\n";
}
}
}
else
{
echo "Username $input is invalid\n";
}
function check_user_exists($xml,$username)
{
$children=$xml->Users->children();
foreach($children as $child)
{
if ($child->getName()=='User')
{
foreach($child->attributes() as $attributes )
{
if(trim($attributes) == trim($username))
{
echo "Username $username already exists... \n";
return true;
}
}
}
}
return false;
}
function isUserID($username)
{
//return preg_match('/^\w{2,20}$/', $username);
return preg_match('/^[A-Za-z0-9][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username);
}
function isValid($str)
{
//return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
return !preg_match('/[^A-Za-z0-9\_\-]/', $str);
}
function getInput($msg)
{
fwrite(STDOUT, "$msg: ");
$varin = trim(fgets(STDIN,20));
return $varin;
//$input = fgets($fr,128); // read a maximum of 128 characters
}
function createXMLbackup($xmlfile,$xmlbackupfile)
{
// Copy Config for backup
$rv = copy($xmlfile,$xmlbackupfile);
if(!$rv)
{
die('Problem creating xml backup file');
}
echo "\nBackup file created\n";
}
function generatePassword ($length = 15)
{
// start with a blank password
$password = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// we refer to the length of $possible a few times, so let's grab it now
$maxlength = strlen($possible);
// check for length overflow and truncate if necessary
if ($length > $maxlength)
{
$length = $maxlength;
}
// set up a counter for how many characters are in the password so far
$i = 0;
// add random characters to $password until $length is reached
while ($i < $length)
{
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, $maxlength-1), 1);
// have we already used this character in $password?
if (!strstr($password, $char))
{
// no, so it's OK to add it onto the end of whatever we've already got...
$password .= $char;
// ... and increase the counter by one
$i++;
}
}
// done!
return $password;
}
?>
I've looked around and there are some places that suggest using # in front of calling in PHP so: #C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2 but that doesn't work, and I can see that my script does work, just not in this nested form.
Maybe there's an approach to this problem that I'm missing? Or something that I don't know about executing scripts in nested batch scripts?
In your BatchCreateIIS.bat, when you use this:
start cmd.exe /c "CreateIIStmp.bat %%X %%X"
the parent cmd.exe will not wait for each instance of CreateIIStmp.bat (and child processes) to finish. Since you seem to be writing to the same XML file, it is likely that the DOM that get written last persists. Instead try this:
call "CreateIIStmp.bat %%X %%X"

Categories