Skip to content

Instantly share code, notes, and snippets.

@swinton
Last active December 22, 2015 20:41
Show Gist options
  • Select an option

  • Save swinton/5f8f130b8d6209f67585 to your computer and use it in GitHub Desktop.

Select an option

Save swinton/5f8f130b8d6209f67585 to your computer and use it in GitHub Desktop.
Example PHP web app for downloading a document from Igloo using their API.
CONFIG_API_APP_APIVERSION: 1
CONFIG_API_APP_ID: e829896b-0c31-488c-93c1-33952ebad173
CONFIG_API_APP_PASS: familiar-foreign-deeply-tube
CONFIG_API_COMMUNITY: resources.bluezonesproject.com
CONFIG_API_PASSWORD: BlueZonesAPIAdmin943!
CONFIG_API_USERNAME: bluezonesprojectusa@healthways.com
<?php
define('CONFIG_API_APP_ID', getenv('CONFIG_API_APP_ID'));
define('CONFIG_API_APP_PASS', getenv('CONFIG_API_APP_PASS'));
define('CONFIG_API_APP_APIVERSION', getenv('CONFIG_API_APP_APIVERSION'));
define('CONFIG_API_USERNAME', getenv('CONFIG_API_USERNAME'));
define('CONFIG_API_PASSWORD', getenv('CONFIG_API_PASSWORD'));
define('CONFIG_API_COMMUNITY', getenv('CONFIG_API_COMMUNITY'));
class API{
public $SecretKey;
public $SessionKey;
public $Nonce;
public $BaseUrl = "http://api.iglooplatform.com/.api/api.svc/";
public $BaseUrlSSL = "https://api.iglooplatform.com/.api/api.svc/";
public $Community;
public $Username;
public $UserPassword;
public $UserId;
public $ApiPassword;
public $ApiId;
public $ApiVersion;
public $Debug = false;
public $LastRenew = 0;
public $TimeoutTime = 600; // API timeout time before we refresh, in seconds
static private $instance = NULL;
public function __construct() {
$this->ApiId = CONFIG_API_APP_ID;
$this->ApiPassword = CONFIG_API_APP_PASS;
$this->ApiVersion = CONFIG_API_APP_APIVERSION;
}
public static function getInstance() {
if (self::$instance == NULL) {
self::$instance = new API;
}
return self::$instance;
}
public function setInstance($o) {
self::$instance = $o;
}
public function __sleep() {
return array_keys(get_object_vars($this));
}
public function __wakeup() { }
public function resetLastRenew() {
$now = time();
$this->LastRenew = $now;
}
public function isExpired() {
return ((time() - ($this->LastRenew)) > $this->TimeoutTime);
}
//Builds the full URL for the request
//Also creates the signature to authenticate request
function BuildUri($uri, $method, $SSL, $postData = null, $useCommunityUri = false){
//If there is no secret key, there is no session key or nonce (signing in)
$baseUrl = $this->BaseUrl;
if($SSL){
$baseUrl = $this->BaseUrlSSL;
}else if($useCommunityUri){
$baseUrl = 'http://' . $this->Community . '/.api/api.svc/';
}
if(!$this->SecretKey){
return $baseUrl . $uri;
}
//Signautre generation uses this order
$data = $method . ":" . $baseUrl . $uri . $this->SessionKey . $this->Nonce;
//append post data if there is any
if($postData){
$data .= $postData;
}
if($this->Debug){
echo "THIS:" . $data . "<Br>";
}
/*
if(strstr ($data, "update"))
{
echo $data . "<Br>";exit;
}*/
//Make sure data and key are UTF-8 encoded
$data = utf8_encode($data);
$secretKey = utf8_encode($this->SecretKey);
//Create the signature
$hash = hash_hmac("sha1", $data, $secretKey, true);
$signature = base64_encode($hash);
//create the URL
$uri = $baseUrl . $uri;
if(!strpos($uri, "?")){
$uri .= "?";
}else{
$uri .= "&";
}
$uri .= "sessionKey=" . $this->SessionKey;
$uri .= "&nonce=" . $this->Nonce;
$uri .= "&signature=" . urlencode($signature);
return $uri;
}
//Builds the full URL for the request
//Also creates the signature to authenticate request
function BuildUriForFile($uri, $method, $SSL, $postData = null, $useCommunityUri = false){
//If there is no secret key, there is no session key or nonce (signing in)
$baseUrl = $this->BaseUrl;
if($SSL){
$baseUrl = $this->BaseUrlSSL;
}else if($useCommunityUri){
$baseUrl = 'http://' . $this->Community . '/.api/api.svc/';
}
if(!$this->SecretKey){
return $baseUrl . $uri;
}
//Signautre generation uses this order
$data = $method . ":" . $baseUrl . $uri . $this->SessionKey . $this->Nonce;
//append post data if there is any
if($postData){
$data .= $postData;
}
//Make sure data and key are UTF-8 encoded
$secretKey = utf8_encode($this->SecretKey);
//Create the signature
$hash = hash_hmac("sha1", $data, $secretKey, true);
$signature = base64_encode($hash);
//create the URL
$uri = $baseUrl . $uri;
if(!strpos($uri, "?")){
$uri .= "?";
}else{
$uri .= "&";
}
$uri .= "sessionKey=" . $this->SessionKey;
$uri .= "&nonce=" . $this->Nonce;
$uri .= "&signature=" . urlencode($signature);
return $uri;
}
//Builds the full URL for the request
//Also creates the signature to authenticate request
function BuildUriPath($uri, $method, $SSL, $postData = null, $useCommunityUri = false){
//If there is no secret key, there is no session key or nonce (signing in)
$baseUrl = $this->BaseUrl;
if($SSL){
$baseUrl = $this->BaseUrlSSL;
}else if($useCommunityUri){
$baseUrl = 'http://' . $this->Community . '/.api/api.svc/';
}
if(!$this->SecretKey){
return $baseUrl . $uri;
}
//Signautre generation uses this order
$data = $method . ":" . $baseUrl . $uri . $this->SessionKey . $this->Nonce;
//append post data if there is any
if($postData){
$data .= $postData;
}
//Make sure data and key are UTF-8 encoded
$data = utf8_encode($data);
$secretKey = utf8_encode($this->SecretKey);
//Create the signature
$hash = hash_hmac("sha1", $data, $secretKey, true);
$signature = base64_encode($hash);
//create the URL
if(!strpos($uri, "?")){
$uri .= "?";
}else{
$uri .= "&";
}
$uri .= "sessionKey=" . $this->SessionKey;
$uri .= "&nonce=" . $this->Nonce;
$uri .= "&signature=" . urlencode($signature);
return $uri;
}
function GetResponseBin($uri, $SSL = true, $useCommunityUri = false)
{
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
//get the url
$uri = $this->BuildUri($uri, "GET", $SSL, null, $useCommunityUri);
//start request
$ch = curl_init($uri);
//Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//make the request
$response = curl_exec($ch);
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
return $response;
}
function GetResponseTextJSON($uri, $SSL = true, $useCommunityUri = false)
{
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
//get the url
$uri = $this->BuildUri($uri, "GET", $SSL, null, $useCommunityUri);
//start request
$ch = curl_init($uri);
//Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
//make the request
$response = curl_exec($ch);
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
return $response;
}
//GET request behaviour
function GetResponseText($uri, $SSL, $useCommunityUri = false)
{
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
//get the url
$uri = $this->BuildUri($uri, "GET", $SSL, null, $useCommunityUri);
if($this->Debug){
echo "URI: " . $uri . "<br>";
}
//start request
$ch = curl_init($uri);
//Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//make the request
$response = curl_exec($ch);
if($this->Debug){
echo "Response: " . $response . "<br>";
}
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
//$response = utf8_encode($response);
/*
if($useCommunityUri){
echo $response;
exit;
}
*/
//get XML
try{
$xml = new SimpleXMLElement($response);
}catch(Exception $e){
if($this->Debug){
echo nl2br(print_r($e,true)) . "<br><br><hr><br><br>";
}
throw $e;
}
if($xml->exception){
if($this->Debug){
echo nl2br(print_r($xml,true)) . "<br><br><hr><br><br>";
}
//If there is an exception, then throw it
throw new Exception($xml->exception->message);
}else{
//No exception, so return the XML
return $xml;
}
}
//POSTS request to the API URI, and returns XML
//uri = the relative uri (API command)
//postData = the data to include in POST data
function PostResponseText($uri, $SSL, $postData)
{
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
//get the url
$uri = $this->BuildUri($uri, "POST", false, $postData, false);
if($this->Debug){
echo "<br>PostResponseText: URI\n" . $uri . "\n";
echo "<br>PostResponseText: PostData<br>" . $postData . "\n";
}
//start request
$ch = curl_init($uri);
//SSL Settings
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//POST settings and data
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
//make the request
$response = curl_exec($ch);
if($this->Debug || $_GET["test"] == "true"){
echo "<br>PostResponseText: Response\n" . $response . "\n\n";
}
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
if(strstr($uri, "wikiarticles") !== false){
echo $uri + "<br>" + $postData;
}
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
try{
//get XML
$xml = new SimpleXMLElement($response);
}catch(Exception $e){
if($this->Debug){
echo $response;exit;
//echo print_r($e,true) . "\r\n\r\n<hr>\r\n\r\n";
}
throw new Exception($e);
}
if($xml->exception){
if($this->Debug && $_GET["test"] == "true"){
echo "no";
echo nl2br(print_r($e,true)) . "<br><br><hr><br><br>";
}
echo nl2br(print_r($e,true));
throw new Exception($xml->exception->message);
}else{
//No exception, so return the XML
return $xml;
}
}
function PostFileTest($uri, $fileString, $fileName, $fileType)
{
$boundary = "-----------------------------212922023727530";
$request .= $boundary . "\r\n";
$request .= "Content-Disposition: form-data; name=\"document\"; filename=\"" . $fileName . "\"";
$request .= "\r\n";
$request .= "Content-Type: " . $fileType . "\r\n\r\n";
$endBoundary = "\r\n-----------------------------212922023727530--\r\n";
$data = $request . $fileString . $endBoundary;
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
$host = str_replace(array("http://", "/.api/api.svc/"), "", $this->BaseUrl);
$path = "/.api/api.svc/" . $this->BuildUriPath($uri, "POST", false, $data, true);
// open a socket connection on port 80
$fp = fsockopen($host, 80);
if(!$fp){
return false;
}
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-Type: multipart/form-data; boundary=---------------------------212922023727530\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
echo $result;
return;
$ch = curl_init($uri);
//SSL Settings
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//POST settings and data
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data; boundary=---------------------------212922023727530'
));
$response = curl_exec($ch);
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
//$response = utf8_encode($response);
//get XML
$xml = new SimpleXMLElement($response);
if($xml->exception){
//If there is an exception, then throw it
throw new Exception($xml->exception->message);
}else{
//No exception, so return the XML
return $xml;
}
}
function PostFile($uri, $fileString, $fileName, $fileType)
{
$boundary = "-----------------------------212922023727530";
$request .= $boundary . "\r\n";
$request .= "Content-Disposition: form-data; name=\"document\"; filename=\"" . $fileName . "\"";
$request .= "\r\n";
$request .= "Content-Type: " . $fileType . "\r\n\r\n";
$endBoundary = "\r\n-----------------------------212922023727530--\r\n";
$data = $request . $fileString . $endBoundary;
//Set Nonce
$this->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
$uri = $this->BuildUriForFile($uri, "POST", false, $data, true);
//start request
$ch = curl_init($uri);
//SSL Settings
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//POST settings and data
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data; boundary=---------------------------212922023727530'
));
$response = curl_exec($ch);
if(curl_error($ch)){
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
curl_close($ch);
throw new Exception($curl_error, $curl_error_number);
}
//close transfer
curl_close($ch);
//$response = utf8_encode($response);
//get XML
$xml = new SimpleXMLElement($response);
if($xml->exception){
//If there is an exception, then throw it
throw new Exception($xml->exception->message);
}else{
//No exception, so return the XML
return $xml;
}
}
//Signs into the community
//appId = the API application Id
//appPass = password for application
//community = community context
//apiVersion = version of API this is running
function SignIn()
{
try{
if($this->Username && $this->UserPassword){
$postData =
"appId=" . urlencode($this->ApiId) .
"&appPass=" . urlencode($this->ApiPassword) .
"&username=" . urlencode($this->Username) .
"&password=". urlencode($this->UserPassword) .
"&community=" . urlencode($this->Community) .
"&apiversion=" . urlencode($this->ApiVersion);
$uri = "session/create";
$xml = $this->PostResponseText($uri, true, $postData);
if($xml->exception){
echo "A";exit;
return false;
}
$this->SessionKey = (string) $xml->response->sessionKey;
$this->SecretKey = (string) $xml->response->secretKey;
$this->BaseUrl = (string) $xml->response->baseUri;
$this->BaseUrlSSL = (string) $xml->response->baseUriHttps;
$this->UserId = (string) $xml->response->userId;
$this->resetLastRenew();
return true;
}
return false;
} catch (Exception $e) {
return false;
}
}
//Signs into the community
//appId = the API application Id
//appPass = password for application
//community = community context
//apiVersion = version of API this is running
function SignOut()
{
try{
$uri = "session/delete";
$xml = $this->PostResponseText($uri, true, $postData);
$this->SessionKey = null;
$this->SecretKey = null;
return true;
} catch (Exception $e) {
return false;
}
}
//TOOD: CheckSession()
function RenewTransfer()
{
try{
if($igloo){
$apiPass = "igloo1234";
}else{
$apiPass = $this->ApiPassword;
}
$postData =
"oldSession=" . $this->SessionKey .
"&appPass=" . $apiPass;
$uri = "session/renew";
$xml = $this->PostResponseText($uri, true, $postData);
$this->SessionKey = (string) $xml->response->sessionKey;
$this->SecretKey = (string) $xml->response->secretKey;
$this->BaseUrl = (string) $xml->response->baseUri;
$this->BaseUrlSSL = (string) $xml->response->baseUriHttps;
$this->UserId = (string) $xml->response->userId;
return true;
} catch (Exception $e) {
$this->SecretKey = null;
$this->SessionKey = null;
return $this->SignIn();
}
}
//Renews the Session
function RenewSession($igloo = false)
{
try{
if (!$this->isExpired() &&
$this->SessionKey && $this->SessionKey != "" &&
$this->SecretKey && $this->SecretKey != "") {
return true;
}
if($igloo){
$apiPass = "igloo1234";
}else{
$apiPass = $this->ApiPassword;
}
$postData =
"oldSession=" . $this->SessionKey .
"&appPass=" . $apiPass;
$uri = "session/renew";
$xml = $this->PostResponseText($uri, true, $postData);
$this->SessionKey = (string) $xml->response->sessionKey;
$this->SecretKey = (string) $xml->response->secretKey;
$this->BaseUrl = (string) $xml->response->baseUri;
$this->BaseUrlSSL = (string) $xml->response->baseUriHttps;
$this->UserId = (string) $xml->response->userId;
$this->resetLastRenew();
return true;
} catch (Exception $e) {
$this->SecretKey = null;
$this->SessionKey = null;
return $this->SignIn();
}
}
function ViewSession($sessionKey, $userId, $apiPass = 'igloo1234')
{
$postData =
"oldSession=" . $sessionKey .
"&appPass=" . $apiPass;
$uri = "session/renew";
$xml = $this->PostResponseText($uri, true, $postData);
$session = array();
$session["sessionKey"] = (string) $xml->response->sessionKey;
$session["secretKey"] = (string) $xml->response->secretKey;
$session["userId"] = (string) $xml->response->userId;
$session["admin"] = false;
if($userId == $session["userId"]){
$groups = Member::GetMemberGroups($session["userId"]);
$session["groups"] = $groups;
if($groups){
foreach($groups AS $group){
if($group->Type == "Admin"){
$session["admin"] = true;
}
}
}
return $session;
}
return false;
}
function ViewSessionClassifieds($sessionKey, $userId, $apiPass = 'igloo1234')
{
try{
$postData =
"oldSession=" . $sessionKey .
"&appPass=" . $apiPass;
$uri = "session/renew";
$xml = $this->PostResponseText($uri, true, $postData);
$session = array();
$session["sessionKey"] = (string) $xml->response->sessionKey;
$session["secretKey"] = (string) $xml->response->secretKey;
$session["userId"] = (string) $xml->response->userId;
return $session;
}catch (Exception $e) { return false; }
}
function TransferSession()
{
try{
$postData =
"appId=" . $this->ApiId;
$uri = "session/transfer";
$xml = $this->PostResponseText($uri, false, $postData);
return $session;
}catch (Exception $e) { return false; }
}
}
$client = API::getInstance();
$client->Username = CONFIG_API_USERNAME;
$client->UserPassword = CONFIG_API_PASSWORD;
$client->Community = CONFIG_API_COMMUNITY;
$success = $client->SignIn();
// Set nonce
$client->Nonce = ceil(substr(microtime(true) * 1000, 0, 12));
// Build document URI
$uri = sprintf("documents/%s/view_binary", $_GET["id"]);
$uri = $client->BuildUri($uri, "GET", true, null, false);
// Redirect to document
header('Location: ' . $uri);
die();
?>
<html>
<head>
<title>BZ Resources</title>
</head>
<body>
<h1>Downloads</h1>
<ol>
<li><a href="/doc.php?id=a0d48cfe-87ff-4720-be79-b715617e24ff">Pledge_Worksite_040813.pdf</a>.</li>
<li><a href="/doc.php?id=e4ef8978-275c-4224-b67c-9aeb6230c361">Blue Zones Project Pledge Overview_2014.pdf</a>.</li>
<li><a href="/doc.php?id=abccbf2a-485f-47a0-85fc-202ad7bb4309">01 Pledge_School_2013_Final.pdf</a>.</li>
</ol>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment