In the code below, the code would stop from executing further when Kiyoh would not be reachable. This is not good for production. So I was wondering what the best way would be to replace the die function, in a way that the content would execute further -even when Kiyoh would not be reachable-.
The code looks like:
<?php
// Get KiyOh rating
$readdir = $_SERVER['DOCUMENT_ROOT'] . '/kiyoh/';
$file = 'kiyohdata.dat';
// Open the file to get existing content
$kiyohdata = file_get_contents($readdir . $file);
if( $kiyohdata === false ) { // NOT CACHED
$xml = simplexml_load_file('https://www.kiyoh.nl/widgetfeed.php?company=YYYYY') or die("Error: Cannot create object");
$kiyohdata = explode(",", $xml->channel->description);
if(!empty($kiyohdata)) {
file_put_contents($readdir . $file, serialize($kiyohdata));
}
} else { // IS CACHED
$kiyohdata = unserialize($kiyohdata);
}
$cijfer = str_replace('Average score ', '', $kiyohdata[0]);
$cijfer = str_replace('.', ',', $cijfer);
$aantal = str_replace(' Total reviews ', '', $kiyohdata[2]);
?>
I tried with placing an exception: throw new Exception("Kiyoh is not available at the moment");, but the page crashes anyway (Magento 1.9.4.3 webshop).
this wil send you the error per email
<?php
$to_email_address = webmaster#example.com
// Get KiyOh rating
$readdir = $_SERVER['DOCUMENT_ROOT'] . '/kiyoh/';
$file = 'kiyohdata.dat';
// Open the file to get existing content
$kiyohdata = file_get_contents($readdir . $file);
if( $kiyohdata === false ) { // NOT CACHED
$xml = simplexml_load_file('https://www.kiyoh.nl/widgetfeed.php?company=YYYYY') or mail($to_email_address,"GOOGOO hapened !","Error: Cannot create object");
$kiyohdata = explode(",", $xml->channel->description);
if(!empty($kiyohdata)) {
file_put_contents($readdir . $file, serialize($kiyohdata));
}
} else { // IS CACHED
$kiyohdata = unserialize($kiyohdata);
}
$cijfer = str_replace('Average score ', '', $kiyohdata[0]);
$cijfer = str_replace('.', ',', $cijfer);
$aantal = str_replace(' Total reviews ', '', $kiyohdata[2]);
?>
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>
I am trying to create a small php script that pulls down a list of all user id's of people that are following/friends with a handle on twitter, for this I am using https://twitteroauth.com
I can get the id's to a file itself when I use either "friends" or "followers" individually, but when I am trying to move this script to a function I get "Fatal error: Call to a member function get() on null" (line 19)
the error is triggered because this line
" $tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
"
is being used inside a function...
I used composer and tried and got it to work outside a function.. the 2 main files are
index.php
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once 'config.php';
// Pass in arguments
if (PHP_SAPI === 'cli') {
$type = $argv[1];
$term = $argv[2];
}
else {
$type = $_GET['type'];
$term = $_GET['term'];
}
switch ($type){
case 'timeline':
include 'timeline.php';
break;
case 'followers':
case 'friends':
include 'f.php';
break;
case 'ratelimit':
include 'ratelimit.php';
break;
case 'users_followers':
case 'users_friends':
include 'users.php';
break;
case 'all':
// include 'timeline.php';
include 'f.php';
break;
}
?>
And f.php
<?php
function getFrindsFollowers($term, $type){
// create file to print follwer/friends id's to file
$file = "files/" . $term . '_' . $type . '.csv';
// set empty content to file
$content = null;
// set previous cursor
$previous_cursor = 0;
$next_cursor = -1;
$loop_num = 0;
// While statment for followers or friends calls.
while($next_cursor != $previous_cursor && $loop_num < 15 && $next_cursor != 0){
//use Abraham\TwitterOAuth\TwitterOAuth;
//$twitteroauth = new TwitterOAuth(consumer_key, consumer_secret, oauth_access_token, oauth_access_token_secret);
$tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
// Pause the loop for 16 min after every 15th request
if ($loop_num % 15 == 0 && $loop_num > 15) {
echo "sleep mode";
sleep(960);
echo "sleep mode done";
}
// set cursors
$previous_cursor = $next_cursor;
//echo 'Previous cursor is ' . $previous_cursor;
//echo '\n Next cursor is ' . $next_cursor;
foreach($tweets as $key => $val) {
if($key == "ids"){
//echo $val[0];
foreach($val as $value){
$value . "\n";
$content .= ",\n" . $value;
}
}
if($key == "next_cursor"){
//echo "\n \n";
$next_cursor = $val;
}
}
$loop_num ++;
echo "Type is now " . $type . "\n";
echo "Loop is " . $loop_num . " for " . $type . "\n";
file_put_contents($file, $content);
}
}
getFrindsFollowers($term, $type);
?>
Is most likely a easy fix but would appreciate any guidance on how to use a get request inside a function.
You are having trouble with scope (http://php.net/manual/en/language.variables.scope.php)
If you already have the twitteroauth variable defined outside the function, add this line at the start of it
global $twitteroauth;
This will give you access to the variable inside the function.
Consider the following: I am using gzipped .cvs reports downloaded through an API to render data live (constructTable). First I check to see if the file has been downloaded, then if it's complete (more thorough check should be implemented, just don't know how yet). If everything's okay, it should read the file and turn it into an array - which I return to the recursive function which in turn returns it to my constructTable function. But the array won't return from the checkReport function to the constructTable. What am I doing wrong?
function fileToArray($filePath){
$file = fopen($filePath,'rb');
$gzipcsv = fread($file, filesize($filePath));
fclose($file);
$ungzipcsv = gzdecode($gzipcsv);
return parse_csv($ungzipcsv);
}
function checkReport($filePath,$queryStr,$status=''){
if($status!='ok'){
if(!file_exists($filePath)){
if($status!='creating_report'){
DownloadReport($_SESSION['currentUser'],$filePath,$queryStr);
$status='creating_report';
} else {
usleep(100000);
$status='downloading_report';
}
} else {
if(filesize($filePath)!=0){
$fs = filesize($filePath);
usleep(100000);
clearstatcache(TRUE, $filePath);
if($fs==filesize($filePath)){
$status='ok';
} else {
$status='downloading_report';
}
} else {
$status='zero_filesize';
}
}
checkReport($filePath,$queryStr,$status);
} else {
return fileToArray($filePath);
}
}
function constructTable($user, $fields, $dataType, $reportName, $conditionItem, $conditionId, $dateRange) {
$filePath = dirname(dirname(__FILE__)) . '/csv/'.$GLOBALS['customer'].'__'.$dataType.'__'.$reportName.'.csv.gz';
$queryStr = 'SELECT '.implode(',',$fields);
$queryStr .= ' FROM '.$reportName;
$queryStr .= '';
if($conditionId!='') $queryStr .= ' WHERE '.$conditionItem.' = '.$conditionId;
$queryStr .= ' DURING '.$dateRange;
$csv_array = NULL;
$i = 0;
while(!$csv_array){
if($i++>2){
break;
}
$csv_array = checkReport($filePath,$queryStr);
var_dump(checkReport($filePath,$queryStr));
}
Warning: Please contact support about failure in /public_html/install/index.php on line 1295
Fatal error: Function name must be a string in /public_html/install/index.php on line 1296
Okay so I did bad at explaining the whole thing. So Basically I'm trying to install Boonex Dolphin 7.0.6 (Social Networking CMS) on my Web site. I installed all the files correctly. I went to the install page. Went to the second page where I had to make all the files Writable. Once I made all the files Writable I went on to the next page called "Paths". And this is where it gave me the error above. The file has over 1483 Lines. Here is the Code Below.
Where it says $func = create_function("", $funcbody); Thats Line 1295
Lines 1281 - 1350
function printInstallError($sText) {
$sRet = (strlen($sText)) ? '<div class="error">' . $sText . '</div>' : '';
return $sRet;
}
function createTable($arr) {
$ret = '';
$i = '';
foreach($arr as $key => $value) {
$sStyleAdd = (($i%2) == 0) ? 'background-color:#ede9e9;' : 'background-color:#fff;';
$def_exp_text = "";
if (strlen($value['def_exp'])) {
$funcbody = $value ['def_exp'];
$func = create_function("", $funcbody);
$def_exp = $func();
if (strlen($def_exp)) {
$def_exp_text = " <font color=green>found</font>";
$value['def'] = $def_exp;
} else {
$def_exp_text = " <font color=red>not found</font>";
}
}
$st_err = ($error_arr[$key] == 1) ? ' style="background-color:#FFDDDD;" ' : '';
$ret .= <<<EOF
<tr class="cont" style="{$sStyleAdd}">
<td>
<div>{$value['name']}</div>
<div>Description:</div>
<div>Example:</div>
</td>
<td>
<div><input {$st_err} size="30" name="{$key}" value="{$value['def']}" /> {$def_exp_text}</div>
<div>{$value['desc']}</div>
<div style="font-style:italic;">{$value['ex']}</div>
</td>
</tr>
EOF;
$i ++;
}
return $ret;
}
function rewriteFile($sCode, $sReplace, $sFile) {
$ret = '';
$fs = filesize($sFile);
$fp = fopen($sFile, 'r');
if ($fp) {
$fcontent = fread($fp, $fs);
$fcontent = str_replace($sCode, $sReplace, $fcontent);
fclose($fp);
$fp = fopen($sFile, 'w');
if ($fp) {
if (fputs($fp, $fcontent)) {
$ret .= true;
} else {
$ret .= false;
}
fclose ( $fp );
} else {
$ret .= false;
}
} else {
$ret .= false;
}
return $ret;
}
If you need more code please let me know so I can help also thanks for reading this ^_^ and re helping as well. I also tried what the last person said with the adding "$a" and ";" but it did not help. Just got me more errors.
What can be stored in $value['def_exp']?
As it is your create_function call is not returning a value. Or so it seems. I did a simple mock up to show an example:
$funcbody = 'hello';
$func = create_function('$a', 'return $a;');
$def_exp = $func($funcbody);
This works as expected. Depending on what is in $funcbody you either need to add a ; after it IE:
$func = create_function('$a', $funcbody . ';');
A return before it and ; after it:
$func = create_function('$a', 'return ' . $funcbody . ';');
Or pass it as a parameter as I did in the first example. Not sure which you require, as I do not know what is stored in the $value['def_exp'] but hopefully that gets you rolling.
create_function() is probably failing. try
var_dump( $func );
if its false, then that is why and you should look at $funcbody