Get Started Login Sign Up Contact

API

[ LiveTrack24 API v2 Home ]

File contents of api.v2.lib.php

<?php
// display self if not included - remove the next line if you are going to use this file
if ( get_included_files()[0] == __FILE__ ) exit("<pre>" . htmlspecialchars(file_get_contents(__FILE__)) . "/<pre>");

header('Content-Type: text/html; charset=UTF-8');

// We are using $_SESSION in this example, you can use what you think best to store data on client side.
//
$SID = session_id();
if ( empty($SID) ) session_start() or exit(basename(__FILE__).' Could not start session');

$gzip = ( array_key_exists('gzip', $_GET) && intval($_GET['gzip']+0) ) ? "/gzip/1" : "";
define("LiveTrack24_API", "http://api.livetrack24.com/api/v2" . $gzip . "/op/");

// test key and secret, will be valid for limited time
//
define("LT24_appSecret", "83523469867234672146");    // !!!!!!!!! replace it with yours
define("LT24_appKey", "00DE262");                    // !!!!!!!!! replace it with yours

// if you cannot get the device id create a random one once!
//
if ( !myRead('deviceID') ) myWrite('deviceID', md5( microtime(true) . rand() ) );

// PHP 5.5 like empty()
function empty5($val)   // convert en expression into a variable
{
	return empty($val);
}

// replace this function with one of yours that reads data (client side) from cookies/session/storage/db
//
function myRead($name)
{
	return ( array_key_exists($name, $_SESSION) ) ? $_SESSION[$name] : '';
}

// replace this function with one of yours that writes data (client side) to cookies/session/storage/db
//
function myWrite($name, $val)
{
	return $_SESSION[$name] = $val;
}

// http://php.net/manual/en/function.hash-hmac.php
//
function otpReply($question)
{
	return "/ak/" . LT24_appKey . "/vc/" . substr( hash_hmac('sha256', $question, LT24_appSecret), 0, 16);
}

// You call this and it handles the (re)Login and the OTP for you.
//
// e.g.:  callLiveTrack24old('status');
//
function callLiveTrack24($params, $calledSelf = 0)
{
	$url = LiveTrack24_API . $params . otpReply( myRead('qwe') );

	// on "reLogin:1" or "newqwe:1" we need to add our deviceID and the saved user token to the URL
	if ( $calledSelf ) $url .= "/di/" . myRead('deviceID') . "/ut/" . myRead('ut');

	// BEGIN remove this =========================================================================
	if ( !$calledSelf )
	{
		$from_split = array("/op/", "/ak/", "/di/");
		$to_split = array("\n\t<b>/op/", "</b>\n\t\t/ak/", "\n\t\t\t/di/");
		echo str_replace($from_split, $to_split, $url) . "\n\n";
	}
	// END remove this ===========================================================================

	// get the result from the server
	$reply = file_get_contents( $url );
	$onError = $reply;

	// BEGIN remove this =========================================================================
	myWrite('resLen', strlen($reply));
	// END remove this ===========================================================================

	// handle gzip
	if ( strpos($url, '/gzip/1') )
	{
		$reply = @gzdecode($reply);

		// BEGIN remove this =========================================================================
		myWrite('resLen', myRead('resLen') . ' bytes, decompressed: ' . strlen($reply));
		// END remove this ===========================================================================
	}

	// try to decode the JSON result
	$res = @json_decode($reply, TRUE);

	// if there is something wrong and we did not get a valid JSON reply return to the caller
	if ( !is_array($res) ) return ( strlen($res) ) ? $res : $onError;

	// we have got our valid reply:

	// save the user token if we get one
	if ( array_key_exists('ut', $res) ) myWrite('ut', $res['ut']);

	// save the OTP-question if we get one
	if ( array_key_exists('qwe', $res) ) myWrite('qwe', $res['qwe']);

	if ( !$calledSelf )
	{
		// try once more on 'newqwe' it may catch up and login with the user token ut
		if ( array_key_exists('newqwe', $res) ) $res = callLiveTrack24($params, 1);

		// check if we need to re-login
		if ( is_array($res) && array_key_exists('reLogin', $res) )
		{ 	// try to re-login
			if ( myRead('LT24_username') && myRead('LT24_password') )
			{
				$res = callLiveTrack24('login/username/' . urlencode(myRead('LT24_username'))
					. '/passe/' . myRead('LT24_password'), 1);
			}

			// check if we need to edit username and or password
			if ( is_array($res) && array_key_exists('reLogin', $res) )
			{
				$res['askForLoginInfo'] = "You need to enter your LiveTrack24 login credentials";
			}
			else
			{
				// re-login was successful, now call LiveTrack24 again with the given params
				return callLiveTrack24($params, 1);
			}
		}
	}

	return $res;
}

// encryptWithKey($str,$key) is used to encrypt passwords.
// It supports character codes from 32 (inclusive) to 224 (exclusive).
// For key you should use your appSecret and it returns the encrypted string in URL-friendly base64 format.
//
function encryptWithKey($str,$key) {

	$offset = rand(0,255);
	$multi = rand(0,255);
	$final= chr($offset) . chr($multi);
	$helpKey = '!' . $key;
	for($i = 0; $i < strlen($str) ; $i++ )
	{
		$keypos = ( $i * $multi + $offset ) % strlen($key);
		// if the previous digit from the key is odd, 1 , else -1
		$sign = ( ord($helpKey[$keypos]) & 1 ) ? 1 : -1;
		$final .= chr( ord($str[$i]) + ( ord($key[$keypos]) & 0x3f ) * $sign );
	}
	return rtrim(strtr(base64_encode($final), '+/=', '-_,'), ',');
}

function decryptWithKey($str,$key) {
	$str = base64_decode(strtr($str, '-_,', '+/='));
	$final="";
	$offset = ord($str[0]);
	$multi = ord($str[1]);
	$str = substr($str, 2);
	$helpKey = '!' . $key;
	for($i=0; $i< strlen($str); $i++ )
	{
		$keypos = ( $i * $multi + $offset ) % strlen($key);
		// if the previous digit from the key is odd, 1 , else -1
		$sign = ( ord($helpKey[$keypos]) & 1 ) ? 1 : -1;
		$goodCode = ord($str[$i]) - ( ord($key[$keypos]) & 0x3f ) * $sign ;

		$final.=chr($goodCode);
	}
	return $final;
}

// BEGIN output functions
//
// The rest of the functions are only needed for these examples, are not needed in your implementation.
//
function demo($title, $help, $params = '', $notes = '')
{
	$cleanName = str_replace(" ", "_", $title);
	$anchorLink = "<a name='$cleanName' href='#$cleanName'>$title</a>";
	echo "<hr><h3>$anchorLink</h3><p>$help</p>";
	if ( !empty($params) )
	{
		echo "Example: <i>$notes</i><p><pre>";
		$res = callLiveTrack24($params) ;
		echo "Returns (" . myRead('resLen') ." bytes): \n\n";
		$res = is_array($res)
			? htmlspecialchars(json_encode(str_replace("\n", "<br>",$res),
				JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))
			: $res;
		echo str_replace(array('\\r','\\n', '\\t'),array("\r","\n","\t"), $res);
	}
	echo '</pre></p>';
	return $res;
}

function checkLoggedIn()
{
	$username = '';
	$password = '';

	if ( empty($username) ) $username = myRead('LT24_username');
	if ( empty($password) ) $password = decryptWithKey( myRead('LT24_password'), LT24_appSecret);

	define('INTO_LT24', array_key_exists('file', $_GET));
	$home = INTO_LT24 ? '' : ' [ <a href="../../index.html">Home</a>  ] ';

	if ( myRead('ut') )
	{
		echo "<h4>You are logged in to the API examples as: '<b>" . myRead('LT24_username')
			. "</b>' (user ID: " . myRead('userID') . ")$home</h4>"
			. "<p><b>Note</b>: These dynamic examples use actual API calls and the current non-cached replies are displayed.</p>";
	}
	else
	{
		$baseDir = 'http://www.livetrack24.com/';
		$apiDir = substr( __DIR__, strpos( __DIR__, '/api/') + 5) . '/';
		$apiFile = $apiDir . 'api.v2.demo.php';
		$redirect = INTO_LT24
			? $baseDir . 'docs/api?file='
			. base64_encode($apiFile . "?qs=" . base64_encode($baseDir . 'docs/api?file=' . $_GET['file']))
			: 'api.v2.demo.php?qs=' . base64_encode(basename($_SERVER['SCRIPT_NAME']) . '?' . $_SERVER['QUERY_STRING']);
		header('Location: ' . $redirect);
	}
}

?>