You are not logged in.
Pages: 1
Reference implementation of a client - imsapiclient.php
<?php
class IMSApiClientException extends Exception {}
class IMSApiActionException extends IMSApiClientException {}
class IMSApiUsageException extends IMSApiClientException {}
class IMSApiClient
{
private $m_strSessionKey;
private $m_strIMSUrl;
private $m_rCurl;
private $m_arrExtraParams;
private $m_Debug;
public function __construct($strIMSUrl, $strApiKey = null, $arrOpts = null)
{
if(!function_exists("curl_init"))
{
throw new IMSApiClientException("cURL extension not available");
}
if (0 !== strpos($strIMSUrl, "http"))
{
$strIMSUrl = "http://".$strIMSUrl;
}
$arrParts = parse_url($strIMSUrl);
if(!$arrParts || empty($arrParts["host"]))
{
throw new IMSApiClientException("Unable to parse IMS URL");
}
$arrParts["scheme"] = empty($arrParts["scheme"]) ? "http" : $arrParts["scheme"];
$arrParts["path"] = (empty($arrParts["path"]) ? "" : preg_replace("|/api.json.tlx$|","",$arrParts["path"]))."/api.json.tlx";
$strFinalURL = $arrParts["scheme"]."://".$arrParts["host"].(empty($arrParts["port"]) ? "" : ":".$arrParts["port"]).$arrParts["path"];
$this->m_arrExtraParams = array();
$this->m_rCurl = curl_init($strFinalURL);
$arrHeaders = array(
'Accept: application/json',
'Content-Type: application/json'
);
curl_setopt($this->m_rCurl, CURLOPT_HTTPHEADER, $arrHeaders);
curl_setopt($this->m_rCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->m_rCurl, CURLOPT_POST, true);
$this->m_Debug = null;
if(is_array($arrOpts))
{
if(!empty($arrOpts["NO_VERIFY_SSL"]))
{
curl_setopt($this->m_rCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($this->m_rCurl, CURLOPT_SSL_VERIFYPEER, false);
}
if(!empty($arrOpts["EXTRA_PARAMS"]))
{
$this->m_arrExtraParams = $arrOpts["EXTRA_PARAMS"];
}
if(!empty($arrOpts["CURL_SETUP"]))
{
if(!is_callable($arrOpts["CURL_SETUP"]))
{
throw new IMSApiClientException("Supplied cURL setup callback is not callable");
}
call_user_func($arrOpts["CURL_SETUP"],$this->m_rCurl);
}
if(!empty($arrOpts["DEBUG"]))
{
if(!is_callable($arrOpts["DEBUG"]))
{
throw new IMSApiClientException("Supplied DEBUG callback is not callable");
}
$this->m_Debug = $arrOpts["DEBUG"];
}
}
if(isset($strApiKey))
{
$this->LoginWithKey(array("apikey"=>$strApiKey));
}
}
public function __call($method,$args)
{
if(preg_match("/^([a-zA-Z]+)(_)(.+)$/", $method, $arrMatches))
{
$module = strtolower($arrMatches[1]);
$method = $arrMatches[3];
}
else
{
$module = "core";
}
$arrRequest = array(
"apiVersion" => "1.0.1",
"action" => "$module.$method",
"inParams" => empty($args[0]) ? array() : $args[0]
);
if(isset($this->m_strSessionKey))
{
$arrRequest["sessionId"] = $this->m_strSessionKey;
}
curl_setopt($this->m_rCurl, CURLOPT_POSTFIELDS, json_encode(array_merge($arrRequest,$this->m_arrExtraParams)));
$arrResponse = @json_decode(curl_exec($this->m_rCurl), true);
if($this->m_Debug)
{
call_user_func($this->m_Debug, $arrRequest,$arrResponse);
}
if(!$arrResponse || empty($arrResponse["result"]) || empty($arrResponse["result"]["api"]))
{
throw new IMSApiClientException("Invalid server response");
}
if($arrResponse["result"]["api"] != "OK")
{
throw new IMSApiUsageException($arrResponse["result"]["api"]);
}
if($arrResponse["result"]["action"] != "OK")
{
throw new IMSApiActionException($arrResponse["result"]["action"]);
}
if($module == "core")
{
if(!empty($arrResponse["outParams"]) && isset($arrResponse["outParams"]["sessionId"]))
{
$this->m_strSessionKey = $arrResponse["outParams"]["sessionId"];
}
}
return isset($arrResponse["outParams"]) ? $arrResponse["outParams"] : null;
}
public function GetSessionKey()
{
if(isset($this->m_strSessionKey))
{
return $this->m_strSessionKey;
}
}
}
Ancillary display and debugging functions - displaysupport.php
<?php
function BeginHTMLPage()
{
?>
<html>
<head>
<style type="text/css">
table
{
color: #333; /* Lighten up font color */
font-family: Helvetica, Arial, sans-serif; /* Nicer font */
width: 100%;
border-collapse: separate;
collapse; border-spacing: 0;
}
td, th { border: 1px solid #CCC; height: 30px; } /* Make cells a bit taller */
th
{
background: #F3F3F3; /* Light grey background */
font-weight: bold; /* Make sure they're bold */
}
td
{
background: #FAFAFA; /* Lighter grey background */
text-align: left; /* Center our text */
}
</style>
</head>
<body>
<?php
}
function DisplayOutput($arrOutput, $strDescription="")
{
echo "<pre>";
echo $strDescription . "<p></p>";
print_r($arrOutput);
echo "</pre>";
}
function DisplayOutputString($strOutput="")
{
echo "<pre>";
echo $strOutput;
echo "</pre>";
}
function DisplayOutputHTML($strOutput="", $strDescription="")
{
echo "<table>";
echo "<tr><td><b>$strDescription</b><td></tr>";
echo "<tr><td>$strOutput</td></tr>";
echo "</table>";
}
function DisplayOutputArrayHTML($arrOutput=array(), $strDescription="")
{
echo "<table>";
echo "<tr><td><b>$strDescription</b><td></tr>";
echo "<tr><td>";
echo "<pre>";
print_r($arrOutput);
echo "</pre>";
echo "</td></tr>";
echo "</table>";
}
function DisplayRequestAndResponseJSON($arrRequest=array(), $arrResponse=array())
{
echo "<table>";
echo "<tr><td>Request</td><td>". json_encode($arrRequest,JSON_PRETTY_PRINT) ."</td></tr>";
echo "<tr><td>Response</td><td>". json_encode($arrResponse,JSON_PRETTY_PRINT) ."</td></tr>";
echo "</table>";
echo "<p></p>";
}
function DisplayRequestAndResponseJSONTxt($arrRequest=array(), $arrResponse=array())
{
echo "\nRequest\n";
echo json_encode($arrRequest,JSON_PRETTY_PRINT);
echo "\nResponse\n";
echo json_encode($arrResponse,JSON_PRETTY_PRINT);
echo "\n##############\n";
}
function DisplayRequestAndResponseArray($arrRequest=array(), $arrResponse=array())
{
echo "<table>";
echo "<tr><td>Request</td><td><pre>";
print_r($arrRequest);
echo "</pre></td>";
echo "<td>Response</td><td><pre>";
print_r($arrResponse);
echo "</pre></td></tr>";
echo "</table>";
echo "<p></p>";
}
function DisplayRequestAndResponseArrayTxt($arrRequest=array(), $arrResponse=array())
{
echo "\nRequest\n";
print_r($arrRequest);
echo "\nResponse\n";
print_r($arrResponse);
echo "\n##############\n";
}
function EndHTMLPage()
{
echo "</body>";
echo "</html>";
}
?>
Using the PHP client
The IMSApiClient class transparently handles API interactions with the IMS server. Creating an API object is as simple as the following:
$myIMSClient = new IMSApiClient("IMS_SITE_URL");
You can optionally provide an IMS API key as the second parameter (these can be created on the Configuration > Site Options page ). If provided, the client will use the key to log in to IMS.
API methods are called in the following manner:
$myIMSClient->Login(array("username"=>"user","password"=>"pass"));
For methods outside the 'Core' module, prefix with the module name as follows:
$searchResults = $myIMSClient->Search_GeneralSearch(array("query"=>"Search String"));
Error Handling
If the PHP client encounters an error, it will throw one of three possible exceptions:
IMSApiClientException - Cannot initialise the client, or cannot communicate with the server. This typically indicates that a required extension (cURL for PHP) is missing, or that the IMS site URL was invalid.
IMSApiUsageException - The request is missing required parameters, the session has expired or an internal error occurred on the server.
IMSApiActionException - File not found, permission denied, etc.
Calling getMessage on an exception will return a brief message stating the cause of the error (e.g. BAD_INPUT, ACTION_NOT_PERMITTED etc.).
Options
The optional third parameter to the IMS API client constructor accepts an array of options
CURL_SETUP - A callback that will be executed with the cURL resource as its only parameter. Valid formats are "function_name" or array($object,"method_name"). Useful for applying proxy settings.
EXTRA_PARAMS - Used to pass extra parameters with API calls. Could be used to override the session key sent, via the sessionId key.
NO_VERIFY_SSL - Skip SSL verification by cURL: this may be useful during testing, before a valid certificate is configured, but it is strongly discouraged in production use.
Debugging
The client can be instructed to display Request and Response data allowing you to inspect the input and output of the client. You can choose to display this in array or JSON format. Set the "DEBUG" variable to one of the following:
"" (no debug)
DisplayRequestAndResponseJSON
DisplayRequestAndResponseArray
$arrExtraParams = array("DEBUG"=> "DisplayRequestAndResponseJSON");
Pass the debug options to the client like this:
$objAPI = new IMSApiClient("http://yoursite.com", $APIKey, $arrExtraParams);
Offline
Putting it all together - Using the client to view thumbnail details - GetThumbDetails.php
<?php
// Files_GetThumbDetails
ob_start(); //buffer output
// Customise these values to match your system
// URL of the IMS site
$strIMSSite = "http://yoursite.com";
// API key generated from Configuration -> Site Options -> IMS API
$strAPIKey = "IJPtL39u8vMfntBgVm7bvGDGUXRRu8FC";
// File references of a few example images
$arrFiles = array(6424384772, 7012757301);
// Sizes start from 1
$nThumbnailSize=6;
// Display request and response data
// Choices are "DisplayRequestAndResponseJSON", "DisplayRequestAndResponseArray" or ""
$arrExtraParams = array("DEBUG"=> "DisplayRequestAndResponseJSON");
// End of custom section
chdir(__DIR__);
require_once("../imsapiclient.php");
require_once("displaysupport.php");
try
{
BeginHTMLPage();
$objAPI = new IMSApiClient($strIMSSite, $strAPIKey, $arrExtraParams);
$arrInParams =
array(
"assetIds" => $arrFiles,
"thumbsize" => $nThumbnailSize,
"navigationContext" => ""
);
$arrOutParams = $objAPI->Files_GetThumbDetails($arrInParams);
foreach($arrOutParams as $key=>$objAsset)
{
echo "<table>";
echo "<th>Asset: $key</th>";
foreach($objAsset as $key=>$value)
{
if($key == "url")
{
echo "<tr><td colspan='2'><img src=" . $value . "></td></tr>";
}
echo "<tr><td>$key</td><td>$value</td></tr>";
}
echo "<p></p>";
}
echo "</table>";
EndHTMLPage();
}
catch(IMSApiClientException $e)
{
header("HTTP/1.1 500 Internal Server Error");
echo "<!DOCTYPE html>\n<html><head><title>Error</title></head><body><h1>Error: ".get_class($e)."</h1><p>".$e->getMessage()."</p></body></html>";
echo"<pre>";
print_r($e);
echo"</pre>";
}
?>
By setting the DEBUG option set to DisplayRequestAndResponseJSON we can see the API requests and responses produced by GetThumbDetails.php
Request { "apiVersion": "1.0.1", "action": "core.LoginWithKey", "inParams": { "apikey": "IJPtL39u8vMfntBgVm7bvGDGUXRRu8FC" } }
Response { "result": { "api": "OK", "action": "OK" }, "outParams": { "sessionId": "fVt2D5AHTRnsYsnmprnZEq7Ly,VRH9xG" } }
Request { "apiVersion": "1.0.1", "action": "files.GetThumbDetails", "inParams": { "assetIds": [ 6424384772, 7012757301 ], "thumbsize": 6, "navigationContext": "" }, "sessionId": "fVt2D5AHTRnsYsnmprnZEq7Ly,VRH9xG" }
Response { "result": { "api": "OK", "action": "OK" }, "outParams": { "6424384772": { "url": "http:\/\/yoursite.com\/t.tlx?tUL7ALXthsTh5Nt.tp_.tg..t127tJb0r8", "width": 480, "height": 320, "previewUrl": "http:\/\/yoursite.com\/viewpicture.tlx?pictureid=6424384772" }, "7012757301": { "url": "http:\/\/yoursite.com\/t.tlx?BGDdIDjB56fv1pB.BV5.B0..ByRdBI.vKmB", "width": 478, "height": 320, "previewUrl": "http:\/\/yoursite.com\/viewpicture.tlx?pictureid=7012757301" } } }
Offline
Pages: 1