I am searching products on an e-commerce website using their API. The API returns all the information in JSON format as a response. Each JSON response has 50 items and a URL that has 50 other items and so on. So to match the searched string with product titles, I need to parse all the JSON files sequentially. But if the item to be searched is on the last page, it is taking about 40 minutes to reach there. Can you please help on how I can reduce that time?
My website is currently hosted on localhost(XAMPP).
index.php
$fk = new Flipkart();
$fk->getProductFeedJason($fk->result);
for($i=0; $i<51; $i++)
{
if($fk->flag==1)
break;
$fk->curl($fk->links[$i]);
$fk->getProducts($fk->result, $sstring);
}
flipkart.php
<?php
class Flipkart
{
private $baseUrl = "https://affiliate-api.flipkart.net/affiliate/api/psblesson.json";
private $headers = array(
'Fk-Affiliate-Id: id',
'Fk-Affiliate-Token: token'
);
public $result;
public $links;
public $mainLinksCount=0;
public $pc=0;
public $id;
public $title;
public $image;
public $sellingPrice;
public $maximumRetailPrice;
public $productURL;
public $flag=0;
function __construct()
{
ini_set('max_execution_time', 0);
ini_set('memory_limit', '1024M');
$this->curl($this->baseUrl);
}
public function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$this->result = curl_exec($ch);
curl_close($ch);
}
public function getProductFeedJason($res)
{
$i=0;
$productFeeds = json_decode($res, TRUE);
$this->links = $productFeeds['apiGroups']['affiliate']['apiListings'];
foreach($this->links as $keys=>$value)
{
$this->links[$i] = $value['availableVariants']['v0.1.0']['get'];
//echo $this->links[$i];
$i = $i + 1;
}
}
public function getProducts($res, $str)
{
$products = null;
$products = json_decode($res, TRUE);
$outerPart = $products['productInfoList'];
$nextUrl = $products['nextUrl'];
//echo $nextUrl.'<br />';
foreach($outerPart as $data)
{
$t = $data['productBaseInfo']['productAttributes']['title'];
similar_text($str, $t, $percent);
if($percent>70)
{
$this->id[$this->pc] = $data['productBaseInfo']['productIdentifier'] ['productId'];
//echo $this->id[$this->pc].'<br />';
$this->title[$this->pc] = $data['productBaseInfo']['productAttributes']['title'];
//echo $this->title[$this->pc].'<br />';
$this->image[$this->pc] = $data['productBaseInfo']['productAttributes']['imageUrls']['400x400'];
//echo $this->image[$this->pc].'<br />';
$this->sellingPrice[$this->pc] = $data['productBaseInfo']['productAttributes']['sellingPrice']['amount'];
//echo $this->sellingPrice[$this->pc].'<br />';
$this->maximumRetailPrice[$this->pc] = $data['productBaseInfo']['productAttributes']['maximumRetailPrice']['amount'];
//echo $this->maximumRetailPrice[$this->pc].'<br />';
$this->productUrl[$this->pc] = $data['productBaseInfo']['productAttributes']['productUrl'];
//echo $this->productUrl[$this->pc].'<br />';
$this->pc = $this->pc+1;
if($this->pc >=10)
{
$this->flag=1;
break;
}
}
}
if($nextUrl && $this->flag==0)
{
$this->curl($nextUrl);
$this->getProducts($this->result, $str);
}
}
}
?>
Related
I am up and running my E-Commerce website on a server. I use Paypal IPN notifications to send customers with notifications about payments made by them.
I am currently using Paypal sandbox for testing.
I proceed to checkout => paypal developer account => make payment => i receive message in my paypal account as ipn request is sent but i don't get the values of ipn request in my orders table in the database.
What could be the reason for this ?
I have set my IPN details as in the screenshot below.
and
I also have the screenshot of IPN history of my Paypal developer account.
Can anyone please help me and tell me the reason why the values in my database are not updated ?
Following is my code:
classes/Paypal.php
<?php
class PayPal {
private $_environment = 'sandbox';
private $_url_production = 'https://www.paypal.com/cgi-bin/webscr';
private $_url_sandbox = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
private $_url;
private $_cmd;
private $_products = array();
private $_fields = array();
private $_business = 'xxx-xxx#gmail.com';
private $_page_style = 'null';
private $_return;
private $_cancel_payment;
private $_notify_url;
private $_currency_code = 'GBP';
public $_tax_cart = 0;
public $_tax = 0;
public $_populate = array();
private $_ipn_data = array();
private $_log_file = null;
private $_ipn_result;
public function __construct($cmd = '_cart') {
$this->_url = $this->_environment == 'sandbox' ?
$this->_url_sandbox :
$this->_url_production;
$this->_cmd = $cmd;
$this->_return = SITE_URL."/?page=return";
$this->_cancel_payment = SITE_URL."/?page=cancel";
$this->_notify_url = SITE_URL."/?page=ipn";
$this->_log_file = ROOT_PATH.DS."log".DS."ipn.log";
}
public function addProduct($number, $name, $price = 0, $qty = 1) {
switch($this->_cmd) {
case '_cart':
$id = count($this->_products) + 1;
$this->_products[$id]['item_number_'.$id] = $number;
$this->_products[$id]['item_name_'.$id] = $name;
$this->_products[$id]['amount_'.$id] = $price;
$this->_products[$id]['quantity_'.$id] = $qty;
break;
case '_xclick':
if (empty($this->_products)) {
$this->_products[0]['item_number'] = $number;
$this->_products[0]['item_name'] = $name;
$this->_products[0]['amount'] = $price;
$this->_products[0]['quantity'] = $qty;
}
break;
}
}
private function addField($name = null, $value = null) {
if (!empty($name) && !empty($value)) {
$field = '<input type="hidden" name="'.$name.'" ';
$field .= 'value="'.$value.'" />';
$this->_fields[] = $field;
}
}
private function standardFields() {
$this->addField('cmd', $this->_cmd);
$this->addField('business', $this->_business);
if ($this->_page_style != null) {
$this->addField('page_style', $this->_page_style);
}
$this->addField('return', $this->_return);
$this->addField('notify_url', $this->_notify_url);
$this->addField('cancel_payment', $this->_cancel_payment);
$this->addField('currency_code', $this->_currency_code);
$this->addField('rm', 2);
switch($this->_cmd) {
case '_cart':
if ($this->_tax_cart != 0) {
$this->addField('tax_cart', $this->_tax_cart);
}
$this->addField('upload', 1);
break;
case '_xclick':
if ($this->_tax != 0) {
$this->addField('tax', $this->_tax);
}
break;
}
}
private function prePopulate() {
if (!empty($this->_populate)) {
foreach($this->_populate as $key => $value) {
$this->addField($key, $value);
}
}
}
private function processFields() {
$this->standardFields();
if (!empty($this->_products)) {
foreach($this->_products as $product) {
foreach($product as $key => $value) {
$this->addField($key, $value);
}
}
}
$this->prePopulate();
}
private function getFields() {
$this->processFields();
if (!empty($this->_fields)) {
return implode("", $this->_fields);
}
}
private function render() {
$out = '<form action="'.$this->_url.'" method="post" id="frm_paypal">';
$out .= $this->getFields();
$out .= '<input type="submit" value="Submit" />';
$out .= '</form>';
return $out;
}
public function run($transaction_id = null) {
if (!empty($transaction_id)) {
$this->addField('custom', $transaction_id);
}
return $this->render();
}
private function validateIpn() {
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (!preg_match('/paypal\.com$/', $hostname)) {
return false;
}
$objForm = new Form();
$this->_ipn_data = $objForm->getPostArray();
if (
!empty($this->_ipn_data) &&
array_key_exists('receiver_email', $this->_ipn_data) &&
strtolower($this->_ipn_data['receiver_email']) !=
strtolower($this->_business)
) {
return false;
}
return true;
}
private function getReturnParams() {
$out = array('cmd=_notify-validate');
if (!empty($this->_ipn_data)) {
foreach($this->_ipn_data as $key => $value) {
$value = function_exists('get_magic_quotes_gpc') ?
urlencode(stripslashes($value)) :
urlencode($value);
$out[] = "{$key}={$value}";
}
}
return implode("&", $out);
}
private function sendCurl() {
$response = $this->getReturnParams();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, T_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($response)
));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$this->_ipn_result = curl_exec($ch);
curl_close($ch);
}
public function ipn() {
if ($this->validateIpn()) {
$this->sendCurl();
if (strcmp($this->_ipn_result, "VERIFIED") == 0) {
$objOrder = new Order();
if (!empty($this->_ipn_data)) {
$objOrder->approve(
$this->_ipn_data,
$this->_ipn_result
);
}
}
}
}
}
mod/paypal.php
<?php
require_once('../inc/autoload.php');
$token2 = Session::getSession('token2');
$objForm = new Form();
$token1 = $objForm->getPost('token');
if ($token2 == Login::string2hash($token1)) {
// create order
$objOrder = new Order();
if ($objOrder->createOrder()) {
// populate order details
$order = $objOrder->getOrder();
$items = $objOrder->getOrderItems();
if (!empty($order) && !empty($items)) {
$objBasket = new Basket();
$objCatalogue = new Catalogue();
$objPayPal = new PayPal();
foreach($items as $item) {
$product = $objCatalogue->getProduct($item['product']);
$objPayPal->addProduct(
$item['product'],
$product['name'],
$item['price'],
$item['qty']
);
}
$objPayPal->_tax_cart = $objBasket->_vat;
// populate client's details
$objUser = new User();
$user = $objUser->getUser($order['client']);
if (!empty($user)) {
$objCountry = new Country();
$country = $objCountry->getCountry($user['country']);
$objPayPal->_populate = array(
'address1' => $user['address_1'],
'address2' => $user['address_2'],
'city' => $user['town'],
'state' => $user['county'],
'zip' => $user['post_code'],
'country' => $country['code'],
'email' => $user['email'],
'first_name' => $user['first_name'],
'last_name' => $user['last_name']
);
// redirect client to PayPal
echo $objPayPal->run($order['id']);
}
}
}
}
IPN settings
IPN Details
Please help me with this .
IPN is not related to your return URL. If you're adding your code that you expect to run when IPNs are triggered to your return URL you will not get the expected result.
To get data to your return URL you would need to use PDT which is very similar to IPN but is intended to be sent to the return URL. IPN goes to your notify URL, which should not match your return URL.
I have successfully implemented geo-location into my website on localhost. however upon uploading the website to an online server, it doesn't work anymore. i get a bool(false) error.
Geo.php
<?php
class Geo{
protected $api = 'http://www.telize.com/geoip/%s';
protected $properties = [];
public function __get($key){
if (isset($this->properties[$key])){
return $this->properties[$key];
}
return null;
}
public function request($ip){
$url = sprintf($this->api, $ip);
$data = $this->sendRequest($url);
$this->properties = json_decode($data, true);
}
protected function sendRequest($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
return curl_exec($curl);
}
}
?>
index.php
<?php
include ("functions/functions.php");
$ip = getIp();
require 'Geo.php';
$geo = new Geo;
$geo->request('$ip');
$location = $geo->city . ', ' .$geo->region;
?>
getIp() function is located in the function.php file which i included, that works fine so I've excluded it.
Code improvement.
Geo.php
<?php
class Geo {
protected $api = 'http://www.telize.com/geoip/%s';
protected $properties = [];
public function __get($key)
{
if (isset($this->properties[$key]))
return $this->properties[$key];
return null;
}
public function request($ip) {
$url = sprintf($this->api, $ip);
$data = $this->sendRequest($url);
if($data !== false) $this->properties = json_decode($data, true);
return ($data !== false);
}
protected function sendRequest($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
return curl_exec($curl);
}
}
?>
index.php
<?php
include ("functions/functions.php");
$ip = getIp();
require 'Geo.php';
$geo = new Geo;
if($geo->request($ip)) {
$location = $geo->city . ', ' .$geo->region;
}
else {
// Location not found
}
?>
I'm using google maps api v2 and I am sending coordinates to my program. The localisation on the map works fine but I never get the adress...
Here is my class:
class reverseGeoCoding {
//put your code here
private $result;
private $latitude=null;
private $longitude=null;
private $adresse=null;
private $config;
public $contents;
function xml2ary(&$string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$mnary=array();
$ary=&$mnary;
foreach ($vals as $r) {
$t=$r['tag'];
if ($r['type']=='open') {
if (isset($ary[$t])) {
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_c']=array();
$cv['_c']['_p']=&$ary;
$ary=&$cv['_c'];
} elseif ($r['type']=='complete') {
if (isset($ary[$t])) { // same as open
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_v']=(isset($r['value']) ? $r['value'] : '');
} elseif ($r['type']=='close') {
$ary=&$ary['_p'];
}
}
$this->del_p($mnary);
return $mnary;
}
// _Internal: Remove recursion in result array
function del_p(&$ary) {
foreach ($ary as $k=>$v) {
if ($k==='_p') unset($ary[$k]);
elseif (is_array($ary[$k])) $this->del_p($ary[$k]);
}
}
// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
$res=array();
foreach ($cary as $tag=>$r) {
if (isset($r[0])) {
$res[]=ary2xml($r, $d, $tag);
} else {
if ($forcetag) $tag=$forcetag;
$sp=str_repeat("\t", $d);
$res[]="$sp<$tag";
if (isset($r['_a'])) {
foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";
}
$res[]=">".((isset($r['_c'])) ? "\n" : '');
if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
elseif (isset($r['_v'])) $res[]=((!is_numeric($r['_v'])&&$r['_v']) ? '<![CDATA[' : false).$r['_v'].((!is_numeric($r['_v'])&&$r['_v']) ? ']]>' : false);
$res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
}
}
return implode('', $res);
}
function formatGmapXML($xml,$returnXML=false,$error=false) {
$tmp = array();
$tmp['request']= $xml['kml']['_c']['Response']['_c']['name']['_v'];
$tmp['status']= $xml['kml']['_c']['Response']['_c']['Status']['_c']['code']['_v'];
// check our Response code to ensure success
if($tmp['status']=='200') {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['Point']['_c']['coordinates']['_v'];
if($tmp['addressFull']==null) {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['Point']['_c']['coordinates']['_v'];
}
$latlng = explode(',',$tmp['coordinates']);
$tmp['latitude'] = $latlng[1];
$tmp['longitude'] = $latlng[0];
}
// optional outputs
if($error) $tmp['error'] = $error;
if($returnXML) $tmp['xml'] = ary2xml($xml);
return $tmp;
}
/*
$q=$_GET['q'];
$latitude=$_GET['latitude'];
$longitude=$_GET['longitude'];
*/
function reverseGeoCoding() {
$this->config=new configInt();
}
function setLongitude($longitude) {
$this->longitude=$longitude;
}
function setLatitude($latitude) {
$this->latitude=$latitude;
}
function setadresse($adresse) {
$this->adresse=$adresse;
}
function getLongitude() {
return $this->longitude;
}
function getLatitude() {
return $this->latitude;
}
function getadresse() {
return $this->adresse;
}
function exec() {
if($this->longitude && $this->latitude ) {
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&ll={$this->latitude},{$this->longitude}&key={$this->config->clefGoogle}");
}else {
$adresse=rawurlencode($this->adresse);
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&q={$adresse}&key={$this->config->clefGoogle}");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
//curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_VERBOSE, false);
$this->contents=curl_exec($ch);
$this->contents=$this->xml2ary($this->contents);
$this->result=$this->formatGmapXML($this->contents,false);
curl_close($ch);
if($this->longitude && $this->latitude ) {
$this->adresse=utf8_decode($this->result['addressFull']);
}else {
$this->latitude=$this->result['latitude'];
$this->longitude=$this->result['longitude'];
}
return $this->result;
}
}
?>
I'm using getAdress in my programm to save the adress in the database, but it never seems to work properly even though the coordinates are correct...
Try this:
$result = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true'));
echo $result->results[0]->formatted_address;
function getaddress($lat, $lng) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($lat) . ',' . trim($lng) . '&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if ($status == "OK")
return $data->results[0]->formatted_address;
else
return false;
}
So I downloaded a wrapper class from this github link:
https://github.com/ignaciovazquez/Highrise-PHP-Api
and I'm just trying to get any response whatsoever. So far, I can't even authenticate with my credentials so I was wondering if any who has used the API could help me.
I tried running one of the test files on Terminal with no arguments and this is what it told me:
Usage: php users.test.php [account-name] [access-token]
Alright, so then decided to get my credentials. So this is what I understand, and, please, correct if I'm wrong:
the account-name is that part that goes in the url to your highrise account. So if your url is:
https://exampleaccount.highrisehq.com/
then your account name is: "exampleaccount"
and your access token is your authentication token that you can find by going clicking on My info > API token inside your Highrise account.
Is that right?
Well anyways, I enter this info and script terminates with a fatal error and this message:
Fatal error: Uncaught exception 'Exception' with message 'API for User returned Status Code: 0 Expected Code: 200' in /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php:137
Stack trace:
#0 /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php(166): HighriseAPI->checkForErrors('User')
#1 /Users/me/Sites/sandbox/PHP/highrise_api_class/test/users.test.php(13): HighriseAPI->findMe()
#2 {main}
thrown in /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php on line 137
I'm complete n00b and I don't really understand what it's saying so I was wondering if any could help. It would be greatly appreciated.
The source of the test script (users.test.php) is:
<?php
require_once("../lib/HighriseAPI.class.php");
if (count($argv) != 3)
die("Usage: php users.test.php [account-name] [access-token]\n");
$hr = new HighriseAPI();
$hr->debug = false;
$hr->setAccount($argv[1]);
$hr->setToken($argv[2]);
print "Finding my user...\n";
$user = $hr->findMe();
print_r($user);
print "Finding all users...\n";
$users = $hr->findAllUsers();
print_r($users);
?>
and the source to the Highrise API wrapper file (Highrise.API.class) is:
<?php
/*
* http://developer.37signals.com/highrise/people
*
* TODO LIST:
* Add Tasks support
* Get comments for Notes / Emails
* findPeopleByTagName
* Get Company Name, etc proxy
* Convenience methods for saving Notes $person->saveNotes() to check if notes were modified, etc.
* Add Tags to Person
*/
class HighriseAPI
{
public $account;
public $token;
protected $curl;
public $debug;
public function __construct()
{
$this->curl = curl_init();
curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
// curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($this->curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl,CURLOPT_SSL_VERIFYHOST,0);
}
public function setAccount($account)
{
$this->account = $account;
}
public function setToken($token)
{
$this->token = $token;
curl_setopt($this->curl,CURLOPT_USERPWD,$this->token.':x');
}
protected function postDataWithVerb($path, $request_body, $verb = "POST")
{
$this->curl = curl_init();
$url = "https://" . $this->account . ".highrisehq.com" . $path;
if ($this->debug)
print "postDataWithVerb $verb $url ============================\n";
curl_setopt($this->curl, CURLOPT_URL,$url);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $request_body);
if ($this->debug == true)
curl_setopt($this->curl, CURLOPT_VERBOSE, true);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
curl_setopt($this->curl, CURLOPT_USERPWD,$this->token.':x');
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
if ($verb != "POST")
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $verb);
else
curl_setopt($this->curl, CURLOPT_POST, true);
$ret = curl_exec($this->curl);
if ($this->debug == true)
print "Begin Request Body ============================\n" . $request_body . "End Request Body ==============================\n";
curl_setopt($this->curl,CURLOPT_HTTPGET, true);
return $ret;
}
protected function getURL($path)
{
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
curl_setopt($this->curl, CURLOPT_USERPWD,$this->token.':x');
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
$url = "https://" . $this->account . ".highrisehq.com" . $path;
if ($this->debug == true)
curl_setopt($this->curl, CURLOPT_VERBOSE, true);
curl_setopt($this->curl,CURLOPT_URL,$url);
$response = curl_exec($this->curl);
if ($this->debug == true)
print "Response: =============\n" . $response . "============\n";
return $response;
}
protected function getLastReturnStatus()
{
return curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
}
protected function getXMLObjectForUrl($url)
{
$xml = $this->getURL($url);
$xml_object = simplexml_load_string($xml);
return $xml_object;
}
protected function checkForErrors($type, $expected_status_codes = 200)
{
if (!is_array($expected_status_codes))
$expected_status_codes = array($expected_status_codes);
if (!in_array($this->getLastReturnStatus(), $expected_status_codes))
{
switch($this->getLastReturnStatus())
{
case 404:
throw new Exception("$type not found");
break;
case 403:
throw new Exception("Access denied to $type resource");
break;
case 507:
throw new Exception("Cannot create $type: Insufficient storage in your Highrise Account");
break;
default:
throw new Exception("API for $type returned Status Code: " . $this->getLastReturnStatus() . " Expected Code: " . implode(",", $expected_status_codes));
break;
}
}
}
/* Users */
public function findAllUsers()
{
$xml = $this->getUrl("/users.xml");
$this->checkForErrors("User");
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->user as $xml_user)
{
$user = new HighriseUser();
$user->loadFromXMLObject($xml_user);
$ret[] = $user;
}
return $ret;
}
public function findMe()
{
$xml = $this->getUrl("/me.xml");
$this->checkForErrors("User");
$xml_obj = simplexml_load_string($xml);
$user = new HighriseUser();
$user->loadFromXMLObject($xml_obj);
return $user;
}
/* Tasks */
public function findCompletedTasks()
{
$xml = $this->getUrl("/tasks/completed.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
public function findAssignedTasks()
{
$xml = $this->getUrl("/tasks/assigned.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
public function findUpcomingTasks()
{
$xml = $this->getUrl("/tasks/upcoming.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
private function parseTasks($xml)
{
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->task as $xml_task)
{
$task = new HighriseTask($this);
$task->loadFromXMLObject($xml_task);
$ret[] = $task;
}
return $ret;
}
public function findTaskById($id)
{
$xml = $this->getURL("/tasks/$id.xml");
$this->checkForErrors("Task");
$task_xml = simplexml_load_string($xml);
$task = new HighriseTask($this);
$task->loadFromXMLObject($task_xml);
return $task;
}
/* Notes & Emails */
public function findEmailById($id)
{
$xml = $this->getURL("/emails/$id.xml");
$this->checkForErrors("Email");
$email_xml = simplexml_load_string($xml);
$email = new HighriseEmail($this);
$email->loadFromXMLObject($email_xml);
return $email;
}
public function findNoteById($id)
{
$xml = $this->getURL("/notes/$id.xml");
$this->checkForErrors("Note");
$note_xml = simplexml_load_string($xml);
$note = new HighriseNote($this);
$note->loadFromXMLObject($note_xml);
return $note;
}
public function findPersonById($id)
{
$xml = $this->getURL("/people/$id.xml");
$this->checkForErrors("Person");
$xml_object = simplexml_load_string($xml);
$person = new HighrisePerson($this);
$person->loadFromXMLObject($xml_object);
return $person;
}
public function findAllTags()
{
$xml = $this->getUrl("/tags.xml");
$this->checkForErrors("Tags");
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->tag as $tag)
{
$ret[(string)$tag->name] = new HighriseTag((string)$tag->id, (string)$tag->name);
}
return $ret;
}
public function findAllPeople()
{
return $this->parsePeopleListing("/people.xml");
}
public function findPeopleByTagName($tag_name)
{
$tags = $this->findAllTags();
foreach($tags as $tag)
{
if ($tag->name == $tag_name)
$tag_id = $tag->id;
}
if (!isset($tag_id))
throw new Excepcion("Tag $tag_name not found");
return $this->findPeopleByTagId($tag_id);
}
public function findPeopleByTagId($tag_id)
{
$url = "/people.xml?tag_id=" . $tag_id;
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleByEmail($email)
{
return $this->findPeopleBySearchCriteria(array("email"=>$email));
}
public function findPeopleByTitle($title)
{
$url = "/people.xml?title=" . urlencode($title);
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleByCompanyId($company_id)
{
$url = "/companies/" . urlencode($company_id) . "/people.xml";
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleBySearchTerm($search_term)
{
$url = "/people/search.xml?term=" . urlencode($search_term);
$people = $this->parsePeopleListing($url, 25);
return $people;
}
public function findPeopleBySearchCriteria($search_criteria)
{
$url = "/people/search.xml";
$sep = "?";
foreach($search_criteria as $criteria=>$value)
{
$url .= $sep . "criteria[" . urlencode($criteria) . "]=" . urlencode($value);
$sep = "&";
}
$people = $this->parsePeopleListing($url, 25);
return $people;
}
public function findPeopleSinceTime($time)
{
$url = "/people/search.xml?since=" . urlencode($time);
$people = $this->parsePeopleListing($url);
return $people;
}
public function parsePeopleListing($url, $paging_results = 500)
{
if (strstr($url, "?"))
$sep = "&";
else
$sep = "?";
$offset = 0;
$return = array();
while(true) // pagination
{
$xml_url = $url . $sep . "n=$offset";
// print $xml_url;
$xml = $this->getUrl($xml_url);
$this->checkForErrors("People");
$xml_object = simplexml_load_string($xml);
foreach($xml_object->person as $xml_person)
{
// print_r($xml_person);
$person = new HighrisePerson($this);
$person->loadFromXMLObject($xml_person);
$return[] = $person;
}
if (count($xml_object) != $paging_results)
break;
$offset += $paging_results;
}
return $return;
}
}
Sorry it's such a long file but if it helps, then so be it.
EDIT: So I guess I got it to work. I should've said that I was trying to test this library out on my local server and for some reason it would keep failing but when I moved the script to my development server on Rackspace cloud then it would work. This just puzzles me. Both servers have support for PHP curl so I can't really understand where the problem is.
EDIT: I'm not sure what the difference between the two server configurations could be but anyways here's a couple of screenshots from my phpinfo function output from both servers of my curl configuration:
Localhost server:
and the rackspace cloud server:
The fork of the API at...
https://github.com/AppSaloon/Highrise-PHP-Api
...seems more developed and better maintained.
Not so much as to provide an answer, but more a better starting point.
Ah, since there is really no HTTP error code 0 I expect that your request isn't being made to Highrise's website, or you are not correctly passing in the account name and token to the class. Can you include the source of your users.test.php class?
EDIT: tested the class and your code, and it works for me. You probably either copied the library file wrong or have your token copied wrong.
I had the same issue. I definitely had the wrong account. I had https://foo.highrisehq.com instead of just foo.
<?php
error_reporting(E_ALL);
$url = 'saved_report.xml';
define('XML_HEADER', '*RWRESPONSE*RESPONSE*DATA*HEADER*COLUMN');
define('XML_ROW', '*RWRESPONSE*RESPONSE*DATA*ROW*COLUMN');
$headers = array();
$rows = array();
function startTag($parser, $data) {
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data) {
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
function contents($parser, $data) {
global $current_tag, $headers, $rows;
switch($current_tag) {
case XML_HEADER:
array_push($headers, $data);
break;
case XML_ROW:
array_push($rows, $data);
break;
}
}
// fetch the report
$curl_object = curl_init();
curl_setopt($curl_object, CURLOPT_URL, $url);
curl_setopt($curl_object, CURLOPT_HEADER, 0);
curl_setopt($curl_object, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($curl_object);
$error = curl_error($curl_object);
$info = curl_getinfo($curl_object);
curl_close($curl_object);
if ($error) {
die("An error occured while fetching the report\n");
}
// process the report
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
if(!(xml_parse($xml_parser, $result))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
for($i = 0; $i \n";
}
echo '';
echo "$headers[3]: $rows[3]\n";
echo "$headers[4]: $rows[4]\n";
?>
while running this script , i am getting an error
"Could not resolve host: saved_report.xml; No data record of requested type"
i am not able to resolve this .
You need to specify full path of the file, e.g.:
$url = 'http://example.com/saved_report.xml';
as curl doesn't work with relative URLs