Related
I would like first to thank everyone who is trying to help or even who read my question.
So what i am trying to do is make a script run on an online server as a cron job each 1 hour. So this will run it one time. But i need to make sure the script is successfully run. Sometimes the script gives this error after it ran 502 Bad Gateway . So need a method please to let the script run again and again until it is successful. So how can i do that in PHP ?
here is an image of the cron parameter and in the last line i put the script link
my script so far is :
<?php
include '../includes/init.php';
$timeout_seconds = 3153600; // 1 year...
// Make sure the PHP script doesn't time out
//set_time_limit(0);
//ignore_user_abort(1);
// Make sure the PHP socket doesn't time out
ini_set('default_socket_timeout', $timeout_seconds);
ini_set('mysqlnd.net_read_timeout', $timeout_seconds);
// This count to keep count of the news found
$news_count = 0;
$image_count = 0;
$sqlCommand = "SELECT * FROM news_feeds_list WHERE cron_file = '1' ORDER BY cron_timestamp ASC";
$query = mysqli_query($connection, $sqlCommand);
if(!$query) {
echo "Query Error: ".mysqli_error($query)."<br/>";
} else {
while ($row = mysqli_fetch_array($query)) {
$feed_id = $row["feed_id"];
$feed_title = html_entity_decode($row["feed_title"]);
$feed_name = $row["feed_name"];
$feed_url = $row["feed_url"];
$feed_region = $row["feed_region"];
$feed_length = $row["feed_length"];
$feed_notes = $row["feed_notes"];
$feed_subject = $row["feed_subject"];
$feed_source_url = $row["feed_source_url"];
libxml_get_errors();
// Here we insert the news into database
$url = "$feed_url";
$xml = simplexml_load_file($url);
if($xml === false){
echo "Operation failed<br/><br/>";
continue;
} else {
// Success
echo "Success<br/><br/>";
for($i = 0; $i < $feed_length; $i++) {
$news_count++;
$title = $xml->channel->item[$i]->title;
$description = $xml->channel->item[$i]->description;
$description_html = htmlentities($description);
$link = $xml->channel->item[$i]->link;
$pubDate = $xml->channel->item[$i]->pubDate;
$author = $xml->channel->item[$i]->author;
$title1 = str_replace("'", "\'", $title);
$description1 = strip_tags($description, '<p><b>');
$description1 = str_replace("'", "\'", $description1);
$author1 = str_replace("'", "\'", $author);
$feed_source_image = $xml->channel->item[$i]->image['url'];
$feed_image = $xml->channel->item[$i]->enclosure['url'];
// $feed_image will be empty so I can fetch the image from the html of the source
$news_timestamp = time();
// Here we convert pubDate which is a string to a timestamp
$time = strtotime($pubDate);
$time = strtotime($pubDate);
$imageLink = "";
$imgexists = false;
if($feed_image == ""){
//echo "<b>feed_image is empty!</b><br><br/>";
// UNTILL HERE THE SCRIPT RUNS WELL BUT AFTER I ADD THE CURL THE 502 COMES IN
//we do this only if the feed_image is empty
// HERE WE START LOOKING FOR AN IMAGE FROM THE WEBSITE ITSELF IF THE XML DOESNT CONTAIN ANY IMAGES
//Get the page's HTML source using file_get_contents.
// We use the following to not get an SSL error
$curl = curl_init();
// curl_setopt($curl, CURLOPT_URL, $location_url);
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($curl);
curl_close($curl);
// end of if(feed_image = "")
} else {
echo "<i>feed_image is not empty!</i><br><br/>";
} // end of else (feed_image = "")
}
} // end of else $xml === false
} // end of first while
mysqli_free_result($query);
$sqlCommand2 = "DELETE FROM news_feeds WHERE news_title = ''";
$query_cleaning = mysqli_query($connection, $sqlCommand2);
if (!$query_cleaning) {
echo("Error Cleaning description: " . mysqli_error($query_cleaning)."<br/><br/>");
}
echo "news count: ".$news_count."<br/>";
echo "image count: ".$image_count."<br/>";
} // end of Query Error check
?>
thank you so much
i am trying to use the push notification in google cloud messages and i am passing an array om registration ids, but for some reason i got the following error:
Field "data" must be a JSON array: You have just invited to play 'Soccer'
this is the part that i am trying to pass:
"registred_ids":["APA91bF9itasGCSK8NbD9u5GJWnEmbWCdS0sEn_xxRVbVpfI0_3FKkvxVBr5xtdE26VZgOO8rCBpf4CaAzHUbMj7PmmDxqpdbWO6VBrPB8dW4CPqPovJbnB_p1Ha_fuwyf8SnOqgOFajK8HEdiZO65qUljO2wCuuDQ"]
not the code of the gcm is :
<?php
class GCM {
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once 'connection.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' .GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
and the code which passing the registration ids is:
<?php
include 'response_process.php';
include 'gcm.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(manager_id,kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,current_participants,scheduled,event_status)
VALUES ('$manager','$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','1','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$query_users = "SELECT id,gcm_id From users WHERE ";
$i=0;
$size_of_param = (count($json));
foreach($json as $user) {
if ($i < $size_of_param - 1)
// add a space at end of this string
$query_users .= "users.mobile = '".$user."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
$event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$insert_query = "INSERT into attending (event_id,user_id,status) VALUES ";
$i=0;
$status = "deny";
$registration_ids = array();
while($row_user = mysqli_fetch_assoc($event_user_s_res))
{
$registration_ids[$i]=$row_user["gcm_id"];
if($i<$size_of_param - 1)
$insert_query .= "('" .$event_id. "','" .$row_user["id"]. "','" .$status. "'), ";
else
$insert_query .= "('".$event_id."','".$row_user["id"]."','".$status."') ";
$i++;
}
$insert_query_res = mysqli_query($dblink,$insert_query) or die (mysqli_error($dblink));
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}else{
$output["id_query"]= $insert_query;
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$message = "You have just invited to play '".$sport."'";
$output["gcm_message"]=$message;
$gcm_res = $gcm->send_notification($registration_ids,$message);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
} // if $no_of_rows < 1
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
Use this-
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => array("message" => $message),
);
It says the data field needs to be an array, but you are setting it to $message, which is a string, not an array.
Field "data" must be a JSON array: You have just invited to play 'Soccer'
This means the value passed in data node is not a json.
Encoding $message into json will fix the error.
In PHP script I parsed some .csv file and trying to execute on a few ways and this is a closest I can get. When I run query manually in database everything is o.k but when I go through the the script I just got New record created successfully and the table stays empty except ID which count how many inserts I got.
o.k that's cool optimization but I still don't getting the data. Yap the $dataPacked is clear below is my whole script can you pls gave some suggestion.
<?php
class AdformAPI {
private $baseUrl = 'https://api.example.com/Services';
private $loginUrl = '/Security/Login';
private $getDataExportUrl = '/DataExport/DataExportResult?DataExportName=ApiTest';
public function login($username, $password) {
$url = $this->baseUrl . $this->loginUrl;
$params = json_encode(array('UserName' => $username, 'Password' => $password));
$response = $this->_makePOSTRequest($url, $params);
$response = json_decode($response, true);
if (empty($response['Ticket'])) {
throw new \Exception('Invalid response');
}
// var_dump($response);
return $response['Ticket'];
}
public function getExportData($ticket) {
$url = $this->baseUrl . $this->getDataExportUrl;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Ticket: '. $ticket
));
$output = curl_exec($ch);
return $output;
}
public function downloadFileFromUrl($url, $savePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
// if (!is_dir($savePath) && is_writable($savePath)) {
$file = fopen($savePath, "w+");
fputs($file, $data);
fclose($file);
// } else {
// throw new \Exception('Unable to save file');
// }
}
private function _makePOSTRequest($url, $json_data) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($json_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
// Login and data download url
$api = new AdformAPI();
$ticket = $api->login('example', '123546');
$exportDataResponseJson = $api->getExportData($ticket);
$exportDataResponse = json_decode($exportDataResponseJson, true);
if (empty($exportDataResponse['DataExportResult']) || $exportDataResponse['DataExportResult']['DataExportStatus'] != "Done") {
throw new \Exception('GetDataExport invalid response');
}
// Download zip
$fileDir = '/var/www/html/app-catalogue/web/export';
$fileName = 'report.zip';
$filePath = $fileDir . DIRECTORY_SEPARATOR . $fileName;
$api->downloadFileFromUrl($exportDataResponse['DataExportResult']['DataExportResultUrl'], $filePath);
// Unzip
$zip = new ZipArchive;
$res = $zip->open($filePath);
$csvFilename = '';
if ($res === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$csvFilename = $zip->getNameIndex($i);
}
$zip->extractTo($fileDir);
$zip->close();
} else {
throw new Exception("Unable to unzip file");
}
// Parse CSV
$csvPath = $fileDir . DIRECTORY_SEPARATOR . $csvFilename;
if (is_readable($csvPath)) {
$dataCsv = file_get_contents($fileDir . DIRECTORY_SEPARATOR . $csvFilename);
$dataArr = explode("\n", $dataCsv);
$dataPacked = array();
foreach ($dataArr as $row) {
$row = str_replace(" ", "", $row);
//$row = wordwrap($row, 20, "\n", true);
$row = preg_replace('/^.{20,}?\b/s', "$0 ", $row);
$row = explode("\t", $row);
$dataPacked[] = $row;
}
}
// SQL Connestion
$servername = "192.168.240.22";
$username = "liferaypublic";
$password = "liferaypublic";
$dbname = "liferay_dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue; }
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//var_dump($dataPacked);
try this - I am assuming you have sanitised the values in $dataPacked.
Note edited to addslashes just in case.
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue;}
foreach ($rowArray as $k=>$v) {
$sanitised = preg_replace("/[^[:alnum:][:space:]]/ui", '', $v);
$rowArray[$k] = addslashes(trim($sanitised));
}
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
iam trying to make an php file to import xml to sql database, but i have this error-:
Warning: Invalid argument supplied for foreach() in /home/morrisse/public_html/xml_to_database.php on line 18
My code:
$url ="http://www.example/example.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL); //GET THE URL CONTENDS
$data = curl_exec ($ch); //execute the curl request
curl_close($ch);
$xml = simplexml_load_string($data);
foreach ($xml -> track as $row) {
$title = $row -> name;
$artist = $row -> artist;
$duration = $row -> duration;
// performing sql query
$sql = "INSERT INTO 'test_xml' ('title', 'artist', 'duration')"
. "VALUES ('$title', '$artist', '$duration')";
$result = mysql_query($sql);
if (!result) {
echo 'MYSQL ERROR';
} else {
echo 'SUCESSO';
}
}
my xml:
<lfm status="ok">
<track>
<id>602366984</id>
<name>Barbarism Begins At Home (BBC TV Tube performance)</name>
<mbid/>
<url>http://www.last.fm/music/The+Smiths/_/Barbarism+Begins+At+Home+(BBC+TV+Tube+performance)</url>
<duration>384000</duration>
<streamable fulltrack="0">0</streamable>
<listeners>10</listeners>
<playcount>24</playcount>
<artist>
<name>The Smiths</name>
<mbid>40f5d9e4-2de7-4f2d-ad41-e31a9a9fea27</mbid>
<url>http://www.last.fm/music/The+Smiths</url>
</artist>
<toptags>
</toptags>
</track>
</lfm>
help please?
The full code:
<?php
$url ="http://www.morrisseyradio.com/shoutcastinfo/cache/track.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL); //GET THE URL CONTENDS
$data = curl_exec ($ch); //execute the curl request
curl_close($ch);
$con=mysql_connect("localhost", "", ""); //connect to database
mysql_select_db("morrisse_forum", $con)
if (!$con) {
die('Could not connect: ' . mysql_error());
}; // select database
libxml_use_internal_errors(true);
$xml = simplexml_load_string($data);
if ($xml === false) {
$errors = libxml_get_errors();
foreach ($errors as $error) {
echo "XML Error at line $error->line: $error->message\n";
}
}
else {
foreach ($xml -> track as $row) {
$title = $row -> name;
$artist = $row -> artist;
$duration = $row -> duration;
// performing sql query
$sql = "INSERT INTO 'test_xml' ('title', 'artist', 'duration')"
. "VALUES ('$title', '$artist', '$duration')";
$result = mysql_query($sql);
if (!result) {
echo 'MYSQL ERROR';
} else {
echo 'SUCESSO';
}
}
}
?>
For anyone the answer is:
First thing:
in the line:
curl_setopt($ch, CURLOPT_URL, $URL);
the "$URL" must be Lower
Second:
In this line:
$sql = "INSERT INTO 'test_xml' ('title', 'artist', 'duration')"
the "'" must be "`"
It's pretty clear that your call to simplexml_load_string() failed because the xml was not well formed. When that happens you get back false rather than a usable xml element.
Here's what I suggest you do about this. Add some error-tracking code, as follows.
libxml_use_internal_errors(true);
$xml = simplexml_load_string($data);
if ($xml === false) {
$errors = libxml_get_errors();
foreach ($errors as $error) {
echo "XML Error at line $error->line: $error->message\n";
}
}
else {
foreach ( $xml->track as $row ) { /* your code continues here ... */
There's clearly something wrong with the xml you're getting back from that server you're using with curl. This code will help you figure out what is wrong.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s wrong with my PHP curl request, please help .. I’m not getting any data back
I'm posting XML data to a URL that is supposed to send me (echo) back results, and instead of sending them back to me , this is what I get after running the PHP .. My curl code is below this result ... I am suspecting that something might be wrong with my CURL code below, how can I actually get the results back from the XML data posted to the URL(mysgproc.php), I posted the url code as well ? Thanks a bunch
HTTP/1.1 200 OK
Date: Fri, 19 Oct 2012 16:30:26 GMT
Server: Apache/2.2.9 (Fedora)
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Content-Length: 238
Connection: close
Content-Type: text/html
<?xml version="1.0" encoding="UTF-8"?><iniResponseMsg deliveryTimeStamp="19/10/2012 16:30:26 GMT" messageID="9d085e45-9e9b-11da-befd-0014221b359d" correlationID="69c8277d-77af-4fd9-8cc0-7c30d2963bee"> <state>fail</state></iniResponseMsg>
Below is my code ...
<?php
$url ="http://127.0.0.1/sens/msgproc.php";
$xml_data = file_get_contents("/usr/local/www/data/message_test.xml");
#$header ="POST HTTP/1.0 \r\n";
#$header .="Content-type: text/xml \r\n";
#$header .="Content-length: ".strlen($xml_data)." \r\n";
#$header .="Content-transfer-encoding: text\r\n";
#$header .="Connection: close \r\n\r\n";
#$header .= $xml_data;
$headers = array('Content-Type: text/xml','Content-Transfer-Encoding: text','Connection: close');
$ch = curl_init();
curl_setopt ($ch,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml_data);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
#curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch); // if the post is successful , the server will return some data.
#$info = curl_getinfo($ch);
#
#if(!curl_errno($ch))
# echo 'It took '.$info['total_time'].'seconds to send a request to'.$info['url'];
#
# else
#
curl_close($ch);
echo $data;
?>
Here is the msgproc.php code
<?php
//$pass='go';
/*******************************************************************************
* COMPONENT NAME:
* msgproc.php
*
* DESCRIPTION:
* This script accepts the various XML documents from G*.
* The document is passed to the correct routine
* in msgproc.php based on what it is.
*
*******************************************************************************/
require('sensdb.php');
require('dbutil.php');
require('msgproc_util.php');
// first this is to pipe all output to the buffer for loggin later in the file
// echo and print statements will get logged instead of outputted
ob_start();
//$raw_post_data = $HTTP_RAW_POST_DATA;
$raw_post_data = file_get_contents("php://input");
$time_log = date("d/m/Y G:i:s") . ' - aeroastro sensor sys time';
/* CONNECT TO THE DATABASE */
sensdb_connect();
$script_time = date("M-d-Y H:i:s");
// logging variables
$type='';
$byte_count=0;
$message_id='';
$error='';
$error_type='';
$source = $_SERVER['REMOTE_ADDR'];
/*******************************************************************************
* COMPONENT NAME:
* main process
*
* DESCRIPTION:
*
*******************************************************************************/
/****** formerly function test_read_xml_post() ***********************/
//$fp = fopen("/usr/local/www/data/sensor/sens/message_test.xml", "r");
//$fp = fopen("php://input", "r");
echo "string length:" . strlen($raw_post_data) . ' ';
// reject all data not from Globalstar of development
//if ( $source == "207.88.248.142" ) {
$data = trim($raw_post_data);
//} else {
// $data = NULL;
//}
$byte_count += strlen($data);
//fclose($fp);
// test of php5 parsing xml .... much easier
if ( $xml = simplexml_load_string($data) ) {
// innocent until proven guilty
$status = true;
// this will help us find the root element to determine message type
$dom = dom_import_simplexml($xml);
$xml_root = $dom->tagName;
// process stumessages here
if ( $xml_root == 'stuMessages' ) {
$type = 'STxMessage';
// what is the message id
$xml_messageID = $xml->xpath('/stuMessages/#messageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// what is the packet time
$packetTimes = $xml->xpath('/stuMessages/#timeStamp');
foreach ( $packetTimes as $_time ) {
$packetTime = $_time;
}
$time_log .= "\n". $packetTime . ' - globalstar packet time';
// how many messages
$message_count = count($xml->xpath('/stuMessages/stuMessage'));
if ( $message_count >= 1 ) {
// fomat the sql string
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
// be careful not to change the sql above which might break our ability here to get the last insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - stu_message packet $message_id logged: insert_id:$incoming_id";
} else {
echo $script_time . " - stu_message failed logging";
}
// mysql_query("LOCK TABLES STxMessage WRITE");
// mysql_query("SET AUTOCOMMIT = 0");
mysql_query("BEGIN");
foreach( $xml->stuMessage as $stuMessage ) {
$unixtime = $stuMessage->unixTime;
$gps = $stuMessage->gps;
$payload = $stuMessage->payload;
// convert to an ESN int
$esn = $stuMessage->esn;
$esn = esn_to_num($esn);
// test the message time against system time
// JL 2007
$time_log .= "\n" . gmdate("d/m/Y H:i:s", "$unixtime") . " - packet stu message time";
// JL 2006 Apr
// log message data larger than 255 chars for TSM account a la Tony B
// these messages don't fit in our DB
if ( strlen($payload) > 255 ) {
// log any output
$large_message_log = '/usr/local/www/logs/large_message_log';
$sql = 'INSERT INTO STxLargeMessage ( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert of large message
$result = #mysql_query($sql);
// Let's make sure the file exists and is writable first.
if ( is_writable($large_message_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($large_message_log, 'a');
// Write $response to our opened file.
#fwrite($handle, "\n".$data);
#fclose($handle);
}
}
// do we have an ESN for this message
// $select_esn = 'select ESN from STx where ESN = "'.$esn.'"';
// $result = mysql_query($select_esn);
// $result_count = mysql_num_rows($result);
$sql = 'INSERT INTO STxMessage( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
$GMT_unixtime = gmdate("Y-m-d H:i:s", "$unixtime");
$update = 'update STx set MessageCount = MessageCount + 1, LastMessageTime = "' . $GMT_unixtime . '" where ESN = "' . $esn . '"';
// increment the message count by 1
mysql_query($update);
unset($update);
// Check db result
if ( !$result ) {
$status = false;
// log the error
echo 'Invalid query: ' . mysql_error() . "\n";
echo $message .= 'Whole query: ' . $query;
}
unset($result);
unset($unixtime);
unset($gps);
unset($payload);
unset($esn);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
// mysql_query("UNLOCK TABLES");
// mysql_query("SET AUTOCOMMIT = 1");
} else { // no data but valid xml, return pass, probably G* "pining" aeroastro for life
$error = "no data in xml packet id:" . $message_id . "\n";
echo $error;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('stuResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'prvmsgs' ) { // process prvmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* PRVMSGS
*
* DESCRIPTION:
* These routines accept the PRVMSGS sent by Globalstar in response to the
* INIMSGS that were sent. This routine stores the PRVMSGS into the database,
* and also sends a respose message back to Globalstar.
*
*******************************************************************************/
$type = 'PrvMessage';
// what is the message id
$xml_messageID = $xml->xpath('/prvmsgs/#prvMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/prvmsgs/prvmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - PrvMessage packet $message_id logged";
} else {
echo $script_time . " - PrvMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->prvmsg as $prvmsg ) {
$esn = esn_to_num($prvmsg->esn);
$provid = $prvmsg->provID;
$tstart = $prvmsg->tStart;
$tend = $prvmsg->tEnd;
$txretryminsec = $prvmsg->txRetryMinSec;
$txretrymaxsec = $prvmsg->txRetryMaxSec;
$txretries = $prvmsg->txRetries;
$rfchannel = $prvmsg->rfChannel;
$sql = 'REPLACE INTO PrvMessage ( ESN, ProvID, TStart, TEnd, TxRetryMinSec, TxRetryMaxSec, TxRetries, RFChannel, IncomingID) values ("'.$esn.'","'.$provid.'","'.$tstart.'","'.$tend.'","'.$txretryminsec.'","'.$txretrymaxsec.'","'.$txretries.'","'.$rfchannel.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
// insert status "change" record
$insert_sql = 'insert INTO STxStatusChangeHistory (StatusChangeID, ESN, Status, StatusChangeTimestamp) values ("","'.$esn.'","Provisioned",NOW())';
// Perform Insert
$insert = mysql_query($insert_sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Provisioned" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "PrvMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('prvResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'instmsgs' ) { // process instmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INSTMSGS
*
* DESCRIPTION:
* After the VAR gets the PRVMSGS and installs the RTU, it will send the
* INSTMSG back here to indicate where the unit was installed.
*
*******************************************************************************/
$type = 'InstMessage';
// what is the message id
$xml_messageID = $xml->xpath('/instmsgs/#instMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/instmsgs/instmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - InstMessage packet $message_id logged";
} else {
echo $script_time . " - InstMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->instmsg as $instmsg ) {
$esn = esn_to_num($instmsg->esn);
$provid = $instmsg->provID;
$rfchannel = $instmsg->rfChannel;
$tactual = $instmsg->tActual;
$deltat = $instmsg->deltaT;
$latitude = $instmsg->latitude;
$longitude = $instmsg->longitude;
$txretries = $instmsg->txRetries;
$txoffset = $instmsg->txOffset;
$txretryminsec = $instmsg->txRetryMinSec;
$txretrymaxsec = $instmsg->txRetryMaxSec;
$powerlevel = $instmsg->powerLevel;
$sql = 'REPLACE INTO InstMessage ( ESN
,ProvID
,IncomingID
,RFChannel
,TActual
,DeltaT
,Latitude
,Longitude
,TxRetries
,TxOffset
,TxRetryMinSec
,TxRetryMaxSec
,PowerLevel ) values ("'.$esn.'"
,"'.$provid.'"
,"'.$incoming_id.'"
,"'.$rfchannel.'"
,"'.$tactual.'"
,"'.$deltat.'"
,"'.$latitude.'"
,"'.$longitude.'"
,"'.$txretries.'"
,"'.$txoffset.'"
,"'.$txretryminsec.'"
,"'.$txretrymaxsec.'"
,"'.$powerlevel.'")';
// Perform Insert
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid InstMessage sql: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Installed" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during Install: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
unset($txoffset);
unset($txretryminsec);
unset($txretrymaxsec);
unset($powerlevel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "InstMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('instResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'inimsgs' ) { // process inimsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INIMSGS
*
* DESCRIPTION:
* The 'INIMSGS' are the messages sent to begin the provisioning process. The
* message contains a range of ESN numbers to be provisiond. The 'INIMSGS'
* are forwarded to Globalstar. Then, the 'get_prvmsgs' function is called
* to poll the database for the response 'prvmsgs' that Globalstar will send.
*
*******************************************************************************/
$type = 'inimsgs';
// what is the message id
$xml_messageID = $xml->xpath('/inimsgs/#iniMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/inimsgs/inimsg'));
if ( $message_count >= 1 ) {
/* DONT FORGET - have a trigger in the database to set a default route for NASCORP */
$sql = "INSERT INTO STx (ESN, RouteID, GroupID, SubGroupID, STxModel, STxModelGenType, STxName, Note, Status, FilterProfile) VALUES ";
$sep = "";
/* FOR EACH OF THE MESSAGES IN THE PACKET.. .*/
foreach ( $xml->inimsg as $inimsg ) {
$groupid = $inimsg->groupID;
$subgroupid = strlen($inimsg->subGroupID) ? $inimsg->subGroupID : 'NULL';
/* FIRST CHECK THAT THE REQUESTED RANGE IS AVAILABLE */
$esnStart = $inimsg->esnStart;
$esnEnd = $inimsg->esnEnd;
$number = check_esn_range($esnStart, $esnEnd, $inuse);
$isreal = ($inimsg->isReal == 'Yes') ? true : false;
$route_id = get_route_id($groupid, $inimsg->routeAddress);
if ( $number > 0 ) {
/* SPLIT THE ESN NUMBER INTO MANUFACTURER AND SERIAL NUMBER */
$esnS = explode('-', $esnStart);
$esnE = explode('-', $esnEnd);
/* FOR EACH ESN IN THE SPECIFIED RANGE... */
for ( $mfg=(int) $esnS[0]; $mfg <= (int) $esnE[0]; $mfg++ ) {
for ( $ser=(int) $esnS[1]; $ser <= (int) $esnE[1]; $ser++ ) {
$sxtmodel = $inimsg->stxModel;
$sxtmodelgentype='1';
switch ($sxtmodel) {
case "101-1":
$sxtmodel = '101';
$sxtmodelgentype = "1";
break;
case "101-2":
$sxtmodel = '101';
$sxtmodelgentype = "2";
break;
case "101-3":
$sxtmodel = '101';
$sxtmodelgentype = "3";
break;
}
$esn = (($mfg << 23) | $ser);
$sql .= $sep;
$sql .= sprintf("(%d ,%d ,%d ,%s ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' )",
$esn
,$route_id
,$groupid
,$subgroupid
,mysql_escape_string($sxtmodel)
,$sxtmodelgentype
,mysql_escape_string($inimsg->stxName)
,mysql_escape_string($inimsg->note)
,$isreal ? 'Initiated' : 'Fake'
,$inimsg->filterProfile);
$sep = ",";
}
}
$groupid = $inimsg->groupID;
$subgroupid = $inimsg->subGroupID;
$esnstart = esn_to_num($inimsg->esnStart);
$esnend = esn_to_num($inimsg->esnEnd);
$stxmodel = $inimsg->stxModel;
$stxname = $inimsg->stxName;
// new filter setting
$filterprofile = $inimsg->filterProfile;
$routeaddress = $inimsg->routeAddress;
// $mobility = $inimsg->mobility;
// $latdefault = $inimsg->latDefault;
// $londefault = $inimsg->lonDefault;
$stxspacing = $inimsg->txSpacing;
// $txfrequency = $inimsg->txFrequency;
// $trequestedstart = $inimsg->tRequestedStart;
// $trequestedend = $inimsg->tRequestedEnd;
$note = $inimsg->note;
$isreal = $inimsg->isReal;
$insert_inimessage = 'INSERT INTO IniMessage (GroupID
,SubGroupID
,ESNStart
,ESNEnd
,STxModel
,STxName
,FilterProfile
,TxSpacing
,RouteAddress
,Note
,IsReal) VALUES ("'.$groupid.'"
,"'.$subgroupid.'"
,"'.$esnstart.'"
,"'.$esnend.'"
,"'.$stxmodel.'"
,"'.$stxname.'"
,"'.$filterprofile.'"
,"'.$stxspacing.'"
,"'.$routeaddress.'"
,"'.$note.'"
,"'.$isreal.'")';
mysql_query("BEGIN");
if ( mysql_query($insert_inimessage) ) {
// not used for anything
$inserted = true;
} else {
$status=false;
}
unset($groupid);
unset($subgroupid);
unset($esnstart);
unset($esnend);
unset($stxmodel);
unset($stxname);
unset($filterprofile);
unset($routeaddress);
unset($mobility);
unset($stxspacing);
unset($note);
unset($isreal);
} else {
$status = false;
echo $script_time . " invalid ESN range\n".$raw_post_data;
}
}
/* IF THE CONTENTS OF THE MESSAGE LOOKED OK, THEN COMMIT
IT TO THE DATABASE... */
/* CREATE THE STx TABLE ENTRIES */
if ( $status ) {
if ( $status = mysql_query($sql) ) {
mysql_query("COMMIT");
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$status = false;
echo $script_time . " no messages in xml \n".$raw_post_data;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('iniResponseMsg', $message_id, $status);
}
} else {
// failed to load xml so lets fail
$status=false;
$response = make_globalstar_response_xml('xml_error', 0, $status);
echo $script_time . " - xml error\n" . $raw_post_data;
}
// log any output
$msgproc_log = '/usr/local/www/logs/msgproc_log';
// collect any trash here for logging
$buffer_string = ob_get_contents()."\n";
// Let's make sure the file exists and is writable first.
if ( is_writable($msgproc_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($msgproc_log, 'a');
// Write $response to our opened file.
#fwrite($handle, $buffer_string);
#fclose($handle);
}
//empty buffer to logs so that globalstar gets response only
ob_end_clean();
mysql_close();
// send the output for Globalstar to see
echo $response;
?>
msgproc.php has dependencies. No one has the time to debug it. So do this:
Try tracing into the server processing code.
echo __LINE__, PHP_EOL; flush(); // every few lines :)
// even followed by a die; to slowly move deeper into the code
Poor man's debugging. And see where output stops, slowly pinpoint the issue. Also set_error_handler and set_exception_handler and see if anything gets caught.