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);
}
}
Related
I am trying to get all Ad Schedules placed in Google Ads through the Google Ads API and obtain the start and end times (hour and minute) to compare it with some existing values and depending on whether they differ update accordingly.
Here is my code showing where I am iterating over returned Ad Schedules.
foreach($campaigns as $camp) {
// Get restaurant and details
$res = RestaurantsService::getRestaurantByName($camp->getName());
$hours =$res->getHours()->dequeue();
$start = explode("-",$hours)[0];
$end = explode("-",$hours)[1];
// Get current ad schedules as they are now
$campaignAdSchedules = self::getCampaignAdSchedule($campaignCriterionService,$camp->getId());
if ($campaignAdSchedules == null){
$operations = [];
$schedule = new AdSchedule();
$schedule->setDayOfWeek(self::DAYS[date("N")-1]);
$schedule->setStartHour((int)substr($start,0,2));
$schedule->setStartMinute(MinuteOfHour::ZERO);
$schedule->setEndHour((int)substr($end,0,2));
$schedule->setEndMinute(MinuteOfHour::ZERO);
$operation = new CampaignCriterionOperation();
$criterion = new CampaignCriterion();
$criterion->setCampaignId($camp->getId());
$criterion->setCriterion($schedule);
$operation->setOperand($criterion);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
$campaignCriterionService->mutate($operations);
} else {
foreach($campaignAdSchedules as $adSchedule){
---> $schedule = $adSchedule->getCriterion(); <---
}
}
}
Here the line marked with arrows is the line I am having problems with. The getCriterion() function returns a Criterion object which does not have the methods getStartHour() etc. I have tried casting it but haven't found the correct way.
Help is much appreciated!
Try check the instance:
$result = $campaignCriterionService->get($serviceSelector);
$campaignAdSchedules = $result->getEntries();
foreach ($campaignAdSchedules as $criterion) {
$adSchedule = $criterion->getCriterion();
if ($adSchedule instanceof AdSchedule) {
$adSchedule->getStartHour();
}
}
I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);
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;
}
I am having a very difficult time getting this to work how I want. I am looking to grab all of the videos from a playlist. Currently I can retrieve 20 but there are some playlists that contain over 100 videos. This is where I am having a problem. I am using the following code I found from another user on here because I have exhausted everything I can think of.
This starts the process. Note that I am calling the XML feed through a specific URL as there is minimal information on Googles Dev site for what I am trying to do.
public function saveSpecificVideoFeed($id) {
$url = 'https://gdata.youtube.com/feeds/api/playlists/' . $id . '?v=2';
$feed = $this->yt->getPlaylistVideoFeed($url);
$this->saveEntireFeed($feed, 1);
}
This is what I am passing the above function to:
public function saveEntireFeed($videoFeed, $counter) {
foreach ($videoFeed as $videoEntry) {
if (self::saveVideoEntry($videoEntry)) {
$this->success++;
} else {
$this->failed++;
}
$counter++;
}
// See whether we have another set of results
try {
$videoFeed = $videoFeed->getNextFeed();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage() . "<br/>";
echo "Successfuly Pulled: <b>" . $this->success . "</b> Videos.<br/>";
echo "Failed to Pull: <b>" . $this->failed . "</b> Videos.<br/>";
echo "You Tryed to Insert: <b>" . $this->duplicate . "</b> Duplicate Videos.";
return;
}
if ($videoFeed) {
self::saveEntireFeed($videoFeed, $counter);
}
}
Here is how I am saving the videos individually:
private function saveVideoEntry($videoEntry) {
if (self::videoExists($videoEntry->getVideoId())) {
// Do nothing if it exists
} else {
$videoThumbnails = $videoEntry->getVideoThumbnails();
$thumbs = null;
foreach ($videoThumbnails as $videoThumbnail) {
$thumbs .= $videoThumbnail['url'] . ',';
}
$binds = array(
'title' => $videoEntry->getVideoTitle(),
'videoId' => $videoEntry->getVideoId(),
'updated' => $videoEntry->getUpdated(),
'description' => $videoEntry->getVideoDescription(),
'category' => $videoEntry->getVideoCategory(),
'tags' => implode(", ", $videoEntry->getVideoTags()),
'watchPage' => $videoEntry->getVideoWatchPageUrl(),
'flashPlayerUrl' => $videoEntry->getFlashPlayerUrl(),
'duration' => $videoEntry->getVideoDuration(),
'viewCount' => $videoEntry->getVideoViewCount(),
'thumbnail' => $thumbs,
);
$sql = "INSERT INTO $this->tblName (title, videoId, updated, description, category, tags, watchPage, flashPlayerUrl, duration, viewCount, thumbnail)
VALUES (:title, :videoId, :updated, :description, :category, :tags, :watchPage, :flashPlayerUrl, :duration, :viewCount, :thumbnail)";
$sth = $this->db->prepare($sql);
foreach ($binds as $key => $value) {
if ($value == null) {
$value = '';
}
$sth->bindValue(":{$key}", $value);
}
if ($sth->execute()) {
return true;
} else {
print_r($sth->errorInfo());
return false;
}
}
}
This is what I get from browser output to let me know in an easy to read format what ive gotten from the pull:
Table has been created continuing with extraction. No link to next set
of results found. Successfully Pulled: 20 Videos. Failed to Pull: 0
Videos. You Tried to Insert: 0 Duplicate Videos.
This however is a playlist with 36 videos so my problem is accessing the remaining videos. Is there an easier not so documented way to do this? Any help would be greatly appreciated.
I have already tried using the max-results and the start-index elements in the request URL and increasing them to the needed values when looping through, this however has no effect on the XML output from the YouTube API.
Any help would be greatly appreciated.
So i decided to go a different route and use the following code:
<?php
include('HttpCurl.php');
class YouTube {
public $url;
private $content;
private $videoId = array();
private $Http,$Doc;
function __construct() {
$this->Http = new HttpCurl();
$this->Doc = new DOMDocument();
}
/*
* Sets url to strip the videos from;
* Insert the full URL for the videos YouTube playlist like:
* http://www.youtube.com/watch?v=saVE7pMhaxk&list=EC6F914D0CF944737A
*/
public function setUrl($url) {
$this->url = $url;
if ($this->check($this->url)) {
$this->getPage();
}
}
private function check($item) {
if (isset($item)) {
return true;
} else {
return false;
}
}
/*
* Grab the page that is needed
*/
private function getPage() {
$this->content = $this->Http->getContent($this->url);
if($this->check($this->content)) {
$this->getPlaylistVideos();
}
}
/*
* Parse page for desired result in our case this will default to the
* playlist videos.
*/
private function getPlaylistVideos() {
$this->Doc->preserveWhiteSpace = false;
// Load the url's contents into the DOM (the # supresses any errors from invalid XML)
if (#$this->Doc->loadHTML($this->content) == false) {
die("Failed to load the document you specified.: " . $page);
}
$xpath = new DOMXPath($this->Doc);
if ($hrefs = $xpath->query("//ol[#id='watch7-playlist-tray']//li")) {
//echo "<br/>Grabbing Videos and playlists!";
//Loop through each <a> and </a> tag in the dom and add it to the link array
//$count = count($this->data['link']);
foreach ($hrefs as $link) {
$this->videoId[] = $link->getAttribute('data-video-id');
}
var_dump($this->videoId);
}
}
}
So not quite what I want but returns all of the ids for the videos so that I can parse them for full data from the YouTube API.
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