Forecast.io service unavailable - php

I am using forecast.io API to deliver weather data to my website. Sometimes the forecast.io API is down, which causes every single page on my website which uses the forecast.io API to return "Service Unavailable, unable to get file content errors"
This is what I'm using to gather the weather data from the API
<?php
include("assets/php/forecast.php");
$api_key = '123123123';
$latitude = $data->getLatitude();
$longitude = $data->getLongitude();
$forecast = new ForecastIO($api_key);
/*
* GET CURRENT CONDITIONS
*/
$condition = $forecast->getCurrentConditions($latitude, $longitude);
$temp = $condition->getTemperature();
$temp = $temp + 2;
$summ = $condition->getSummary();
$icon = $condition->getIcon();
$icon2 = $condition->getIcon();
$icon = str_replace('-', '_', $icon);
$icon2 = str_replace('-', ' ', $icon2);
$icon = strtoupper($icon);
$icon2 = ucfirst($icon2);
?>
I would like to include some sort of error handler where if the forecast.io API is unavailable, then this code doesn't get called.

This is the site where I had the problem
https://seek.estate/
https://seek.estate/buy/422-melbournes-most-liveable-home-sea-views-elevator-designer-masterpiece
This is what I changed
$forecast = new ForecastIO($api_key);
$request_url = 'https://api.forecast.io/forecast/';
$content = file_get_contents($request_url);
if (!empty($content)) {
return condition = $forecast->getCurrentConditions($latitude, $longitude);
} else {
return false;
}

Related

generating raw trx and sending it to the network shows “transaction underpriced” error

I'm trying to make an ethereum raw transaction by php and these libraries:
https://github.com/simplito/elliptic-php
https://github.com/kornrunner/php-keccak
https://github.com/web3p/rlp
this is my code:
use Elliptic\EC;
use kornrunner\Keccak;
use Web3p\RLP\RLP;
$privateKeyHex = '.....'; // wallet private key
$toWallet = '118086be6247fBDa3BC64B4A11F07F3894aA1fAF';
$ec = new EC('secp256k1');
$key = $ec->keyFromPrivate($privateKeyHex );
$publicKeyHex = $key->getPublic('hex');
// $publicKeyHex => 0445e2caf0f227247dfa10440765812492e4d4c9df7b4e74d0d5cd3279fa80f5ef987a70e061ca20c06f09690957c9ba365cf06541181d1291e14c847d0d826583
$nonce= 0;
$gasPrice = 1e9;
$gasLimit = 21000;
$to = hex2bin($toWallet);
$value = 1e14-($gasLimit*$gasPrice)-1;
$inputData = 0;
//*********** EIP_155 *********
$chain_id = 1;
$r = 0;
$s = 0;
//*****************************
$SignData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$chain_id,$r,$s];
$SignRlpData = rlpEncode($SignData);
$signHash = Keccak::hash(hex2bin($SignRlpData), 256);
$signature = $ec->sign($signHash ,$key);
$r = $signature->r->toString('hex');
$s = $signature->s->toString('hex');
$v = $chain_id*2 + ($signature->recoveryParam +35);
$trxData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$v,hex2bin($r),hex2bin($s)];
$trxRlpData = rlpEncode($trxData );
// trxRlpData => f86980843b9aca0082520894118086be6247fbda3bc64b4a11f07f3894aa1faf8647d99eefefff8026a08a53214c92ff615c82eede2e51ab9d4d22d6a393f3ab8acee63c23d04e8e2fa7a07661f758f8b968d7597449ce05027edf3f2891fef0d1278f7330e99545109a2b
function rlpEncode($a){
$rlp = new RLP;
$encodedBuffer = $rlp->encode($a);
return $encodedBuffer->toString('hex');
}
now after I send value of $trxRlpData to the ethereum network by https://etherscan.io/pushTx, show me this error message:
Error! Unable to broadcast Tx : {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"transaction underpriced"}}
but where is problem ?
finally I solved this problem with increasing a little $gasLimit.
$gasLimit = 21001;
When there is a pending transaction and you try to send a new one with same nonce you see this error.
If you needs to make a new transaction while the old one has not confirmed yet, you must get pending transactions count getTransactionCount of address and use as nonce

PHP - Icecast info being updated on page

I'm using a script from this site. This script works fine for me and it does what its need to do but I have one problem. When a track finishes on my Icecast server it doesn't get updates on the site. So if my song is 'Stole the show' than it says 'Stole the show' the page but when the song finished and e.g. 'Thinking out loud' starts the page still says 'Stole the show' on a refresh it will update. But how to make it so the page auto updates itself so the users doesn't have to refresh manually?
PHP
<?php
// include the class file
include( 'icecast.php' );
// instantiate class
$stream = new IceCast();
// set server and mount
$server = 'http://radio.finioxfm.com:8000';
$file = '/status.xsl';
// set the url
$stream->setUrl($server,$file);
// get status info
$radio = $stream->getStatus();
// assign array to variables
extract($radio);
// echo the status
echo $status.'<br/>';
// display more stats if ON AIR
if ($status=='ON AIR') :
echo $listeners.' listeners<br/>';
echo $title.'<br/>';
echo $genre.'<br/>';
for ($i=0; $i < 1; $i++) {
echo $now_playing['artist'].'<br/>';
echo $now_playing['track'].'<br/>';
}
endif;
?>
icecast.php script
<?php
class IceCast {
var $server = "http://radio.finioxfm.com:8000";
var $stats_file = "/status.xsl";
var $radio_info=array();
function __construct() {
// build array to store our Icecast stats
$this->radio_info['server'] = $this->server;
$this->radio_info['title'] = '';
$this->radio_info['description'] = '';
$this->radio_info['content_type'] = '';
$this->radio_info['mount_start'] = '';
$this->radio_info['bit_rate'] = '';
$this->radio_info['listeners'] = '';
$this->radio_info['most_listeners'] = '';
$this->radio_info['genre'] = '';
$this->radio_info['url'] = '';
$this->radio_info['now_playing'] = array();
$this->radio_info['now_playing']['artist'] = 'Unknown';
$this->radio_info['now_playing']['track'] = 'Unknown';
$this->radio_info['status'] = 'OFF AIR';
}
function setUrl($url,$file) {
$this->server=$url;
$this->stats_file=$file;
$this->radio_info['server'] = $this->server;
}
private function fetch() {
// create a new curl resource
$ch = curl_init();
// set the url
curl_setopt($ch,CURLOPT_URL,$this->server.$this->stats_file);
// return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// $output = the status.xsl file
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
return $output;
}
function getStatus() {
$output=$this->fetch();
// loop through $output and sort arrays
$temp_array = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($temp_array,$to_push);
}
}
if(count($temp_array)) {
//sort our temp array into our ral array
$this->radio_info['title'] = $temp_array[0];
$this->radio_info['description'] = $temp_array[1];
$this->radio_info['content_type'] = $temp_array[2];
$this->radio_info['mount_start'] = $temp_array[3];
$this->radio_info['bit_rate'] = $temp_array[4];
$this->radio_info['listeners'] = $temp_array[5];
$this->radio_info['most_listeners'] = $temp_array[6];
$this->radio_info['genre'] = $temp_array[7];
$this->radio_info['url'] = $temp_array[8];
if(isset($temp_array[9])) {
$x = explode(" - ",$temp_array[9]);
$this->radio_info['now_playing']['artist'] = $x[0];
$this->radio_info['now_playing']['track'] = $x[1];
}
$this->radio_info['status'] = 'ON AIR';
}
return $this->radio_info;
}
}
?>
First of all, I have to point out that you shouldn't use this script. It works by parsing the Icecast Status page, which we highly discourage, as it may change. For example in Icecast 2.4 we re-made the complete web interface, so chances are that this script breaks.
You should actually parse the XML Icecast provides at http://icecast.tld:8000/admin/stats. It contains everything you need. If you can't access Icecast's Admin page for some reason, you can use the JSON at http://icecast.tld:8000/status-json.xsl, which is there since Icecast 2.4 exactly for the purpose you describe.
To get the site display new metadata information without refreshing, you need to use an AJAX call which either loads directly the status-json.xsl and extracts the metadata and updates it on the page, or if you use the admin XML you need to write a PHP script which returns json, that you can fetch via AJAX and update accordingly.
A lot of people in the past have spoken about setting up node.js (if you have a server doing your streaming).
Personally I have gone with a jquery solution; which just compares the last fetched data with the live data every 10 seconds. That way it loads in almost 'real time'.
You can find my solution here broken down here http://www.radiodj.ro/community/index.php?topic=7471.0

UDP Tracker Scraping 1 script working other Not

While using this script my tracker only update seeds & leechers from http tracker only 1st Tracker of my torrent.
print("<tr><td class='desc'><b>" .T_("Torrent Stats"). ": </b></td><td valign='top' class='lista'>");
$seeders1 = $leechers1 = $downloaded1 = null;
$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
while ($trow = mysql_fetch_assoc($tres)) {
$ann = $trow["url"];
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = preg_replace("/^announce/", "scrape", $path);
$tracker = implode("/", $tracker)."/".$path;
if ($oldpath == $path) {
continue; // Scrape not supported, ignored
}
// TPB's tracker is dead. Use openbittorrent instead
if (preg_match("/thepiratebay.org/i", $tracker) || preg_match("/prq.to/", $tracker)) {
$tracker = "http://tracker.openbittorrent.com/scrape";
}
$stats = torrent_scrape_url($tracker, $row["info_hash"]);
if ($stats['seeds'] != -1) {
$seeders1 += $stats['seeds'];
$leechers1 += $stats['peers'];
$downloaded1 += $stats['downloaded'];
SQL_Query_exec("UPDATE `announce` SET `online` = 'yes', `seeders` = $stats[seeds], `leechers` = $stats[peers], `times_completed` = $stats[downloaded] WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
} else {
SQL_Query_exec("UPDATE `announce` SET `online` = 'no' WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
}
}
Please correct It I haven't been able to solve this trouble.
In first code I think trouble is here
$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=".$id.";");
This should work if $id is a php variable
The problem is that you are sending a http-scrape to an UDP-tracker.
UDP-tracker uses an entirely diffrent protocol: http://www.bittorrent.org/beps/bep_0015.html

Geocoding doesn't work now V3 is in play

I have a internal site which uses php to look through my msql customer database. Find any customers which do not have lat and lng fields filled in. Grab the postcodes and geocode them posting the lat and lng back to my database and plot the customers on the map. This is done by a cron job once a day. This worked fine using v.2 of google api. Since march or april its stopped. Im guessing because of v.3.
Jist my jl_jobscoordinates.cron.php file searches through the database picking up all the postcodes for empty lat and lng fields. Then calls a function from my geocode.class.php called doGeocode which uses xml to put togther and find results and save the lat and lng. Inside the geocodeclass it refers to a m_url which is the googleapi url which is saved inside my config file. I have updated this url to the new v.3 url which is http://maps.googleapis.com/maps/api/geocode/xml?address=%s&sensor=false. My map is back up and running, just nothing will geocode.
I will paste the two files jl_jobscooedinates.cron.php and geocode.class.php. I have commented out the old xml in the geocode which used to work with the old url.
The results of my cron is that it is not getting coordinates. e.g. -- [3-2013] Google could not find this Postcode: [COO041] Test Company Name, Oxfordshire OX26 4SS
jl_jobcoordinates.cron.php
require_once("../includes/config.php");
require_once(_PATH_JMS."/classes/session.class.php");
require_once(_PATH_JMS."/classes/db.class.php");
require_once(_PATH_JMS."/classes/lib.class.php");
require_once(_PATH_JMS."/classes/security.class.php");
require_once(_PATH_JMS."/classes/emails.class.php");
require_once(_PATH_JMS."/classes/geocode.class.php");
require_once(_PATH_JMS."/services/actiontrail.ds.php");
require_once(_PATH_JMS."/services/jobsdue.ds.php");
//-----------------------------------------------------
// Main Object Instances - Initialize what we require
//-----------------------------------------------------
$DB = new DB();
$Security = new Security($DB->i_db_conn);
$Lib = new Lib();
$Session = new Session();
$ActionTrail = new ActionTrail($DB, $Session, $Security);
$JobsDue = new JobsDue($DB, $Session, $Security, $ActionTrail);
$Geocode = new Geocode($Session, $Security);
$Emails = new Emails($DB, $Session, $Security);
//-----------------------------------------------------
// Save as a valid system user
//-----------------------------------------------------
$Session->save('USR_AUTH',_CRON_USER_NAME);
$Session->save('USR_PASS',_CRON_USER_PASS);
$Session->save('USR_IS_EMPLOYED', '1');
$Session->save('CONS',$Session->get('USR_AUTH'));
//-----------------------------------------------------
// Postcodes to Ignore - we cannot geocode these
//-----------------------------------------------------
$m_ignore = array("IRL","IRELAND","IRE","ITA","USA","BEL","EGY","GER","FR","FRA","HOL","POL");
//-----------------------------------------------------
// Get Jobs Due for all consultants for this year and next
//-----------------------------------------------------
$mY = (int) date("Y");
//-----------------------------------------------------
// Find t-cards without lat & lng
//-----------------------------------------------------
$m_errors = array();
for ($y=$mY;$y<=$mY+1;$y++)
{
for ($i=1;$i<=12;$i++)
{
$mM = (int) $i;
//echo "<br> mM =".$mM ." i =".$i;
$mJobs = $JobsDue->getAllJobsDue('%',$mM,$y,'%',NULL,NULL,FALSE); /* DON'T GET MISSED JOBS AS WE WILL START FROM JAN */
//echo "<br>mJobs =".$mJobs;
foreach ($mJobs as $row)
{
$m_postcode = $Lib->lib_str_clean(trim($row->postcode)); //this loops through each of the records and gets the post codes. m_postcodes are the postcodes found
echo "<br>m_postcode =".$m_postcode;
if (($row->latlngexists == 1)||(in_array($m_postcode,$m_ignore))||(in_array($row->card_id,$m_ignore))||(strlen($m_postcode)<=0)) continue;
if ($Lib->lib_ispostcode($m_postcode)) {
$m_coordinates = $Geocode->doGeocode($m_postcode);
echo "<br>m_coords =".$m_coordinates;//nothing displayed
if ($m_coordinates != NULL) {
$DB->setGeoTCard($row->card_id,$m_coordinates['lat'],$m_coordinates['lng']);
} else {
$m_err_desc = sprintf("[%s-%s] Google could not find this Postcode",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
sleep(_GEOCODE_PAUSE);
} else {
$m_err_desc = sprintf("[%s-%s] Postcode is invalid please check",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
}
}
}
if (count($m_errors) > 0) {
$Emails->doGeocodeErrNotify($m_errors);
}
geocode.class.php
class Geocode {
private $m_session = NULL;
private $m_security = NULL;
private $m_session_user;
private $m_session_pass;
private $m_key = _GMAP_KEY;
private $m_url = _GMAP_URL;
private $m_res = Array();
public function __construct($p_session,$p_security)
{
$this->m_session = $p_session;
$this->m_security = $p_security;
$this->m_session_user = $this->m_session->get('USR_AUTH');
$this->m_session_pass = $this->m_session->get('USR_PASS');
if ($this->m_security->doLogin($this->m_session_user,$this->m_session_pass) <= 0)
{
return NULL;
die;
}
}
public function doGeocode($p_postcode)
{
try {
// //$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode,$this->m_key),0,TRUE); //OLD FOR V.2
$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode),0,TRUE);
} catch (Exception $e) {
echo sprintf('Caught exception: %s', $e->getMessage());
return NULL;
die;
}
$st = $xml->Response->Status->code;
if (strcmp($st, "200") == 0)
{
$co = $xml->Response->Placemark->Point->coordinates;
$cs = preg_split("/[\s]*[,][\s]*/", $co);
$this->m_res = Array(
"lng" => $cs[0],
"lat" => $cs[1],
"alt" => $cs[2]
);
return $this->m_res;
} else {
return NULL;
}
}
}
I would really appriciate if someone could help me please. Im guessing its something to do with the new url in my config file and the current xml not set properly for the sensor??
My geocode stuff is still working fine just like this don't forget to use your own personal API key!
/**
* Geocode postcode to get long/lat used when adding suppliers and sites
* #param - $postcode - string - Input post code to geocode
* #return - $lat,$long - array - array containing latitude coords
*/
function geocode($postcode) {
$postcode = urlencode(trim($postcode)); // post code to look up in this case status however can easily be retrieved from a database or a form post
//$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false"; // the request URL you'll send to google to get back your XML feed
define("MAPS_HOST", "maps.google.co.uk");
define("KEY", "YOUR API KEY HERE");
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
$request_url = $base_url . "&q=" . $postcode;
$xml = simplexml_load_file($request_url);
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = explode(",", $coordinates);
// Format: Longitude, Latitude, Altitude
return array("lat"=>$coordinatesSplit[1],"long"=>$coordinatesSplit[0]);
} else {
return array("lat"=>0,"long"=>0);
}
}

Exporting Invoices from Magento

I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source

Categories