\DeviceAtlasCloudClient

DeviceAtlas Cloud API. This client library can be used to easily get device data from the DeviceAtlas Cloud service. To reduce cloud calls and improve performance the API locally caches the data returned from the cloud service.

This API caches data on the disk.
If the cache path is not writable the APin the I will not proceed even if the device cache is turned off.
It is recommended to set DEBUG = true during implementation so if the cache path is not writable the errors will not be ignored.

The client is queried by passing either nothing (the request's headers will be used) or by manually passing a collection of HTTP headers or a user-agent string. The device properties will then be returned.

Usage (see the provided examples):

  1. Set your DeviceAtlas licence key to the class constant LICENCE_KEY in this file.
  2. Include this file into your application.
  3. To get the best results include the "DeviceAtlas Client Side Component" into your page (that is all you need to do). When available DeviceAtlasCloudClient will automatically find and use the client side properties.
  4. Get the data.
    try {
    $data = DeviceAtlasCloudClient::getDeviceData();
    } catch (Exception $x) {
    // handle exceptions ...
    }
    
    // legacy: (class constant DEBUG = false)
    // the errors have to be checked manually from the returned array
    $data = DeviceAtlasCloudClient::getDeviceData();
    

The returned data is as:

$data[Client::KEY_ERROR]
    will exist if errors happened while fetching data
$data[Client::KEY_PROPERTIES]
    an array of device properties
$data[Client::KEY_USERAGENT]
    the user-agent string that was used to get the properties
$data[Client::KEY_SOURCE]
    shows where the data came from and is one of:
    DeviceAtlasCloudClient::SOURCE_FILE_CACHE
    DeviceAtlasCloudClient::SOURCE_CLOUD
    DeviceAtlasCloudClient::SOURCE_NONE
// get properties for a user-agent
try {
    $data = DeviceAtlasCloudClient::getDeviceData("user-agent-string ...");
} catch (Exception $x) {
    // handle exceptions ...
}
// get properties for a set of headers
$headers = array(
    "User-Agent"      => "Mozilla/5.0 (SymbianOS/9.2; ...",
    "X-Profile"       => "http://nds.nokia.com/uaprof/NN95_8GB-1r100.xml",
    "Accept"          => "text/html,text/css,multipart/mixed,application...",
    "Accept-Language" => "en-us,en;q=0.5",
);
try {
    $data = DeviceAtlasCloudClient::getDeviceData($headers);
} catch (Exception $x) {
    // handle exceptions ...
}

Notes:
1 When in test mode and using cookie cache, changing the user-agent will not update the cookie cache and you have to manually remove the cookie. Because in real life the the cookie is on the system it represents.

2 It is recommended to always use file cache. Using cookie cache will cache device info on the user's browser. You can have both caches on, then if device data is found in the cookie it will be used otherwise if data is cached in the files the file cache will be used.

Summary

Methods
Properties
Constants
getDeviceData()
getCacheBasePath()
getServersLatencies()
getServers()
rankServers()
getCloudUrl()
$SERVERS
$rankingStatus
$calledServers
LICENCE_KEY
DEBUG_MODE
AUTO_SERVER_RANKING
TEST_USERAGENT
CLOUD_SERVICE_TIMEOUT
USE_CLIENT_COOKIE
USE_COOKIE_CACHE
USE_FILE_CACHE
CACHE_ITEM_EXPIRY_SEC
CACHE_NAME
USE_SYSTEM_TEMP_DIR
CUSTOM_CACHE_DIR
CACHE_COOKIE_NAME
SEND_EXTRA_HEADERS
CLIENT_COOKIE_NAME
AUTO_SERVER_RANKING_MAX_FAILURE
AUTO_SERVER_RANKING_NUM_REQUESTS
AUTO_SERVER_RANKING_LIFETIME
SERVER_PHASEOUT_LIFETIME
API_VERSION
MIN_PHP_VERSION
KEY_USERAGENT
KEY_SOURCE
KEY_ERROR
KEY_PROPERTIES
SOURCE_COOKIE
SOURCE_FILE_CACHE
SOURCE_CLOUD
SOURCE_NONE
DA_HEADER_PREFIX
CLIENT_COOKIE_HEADER
CLOUD_PATH
FAILOVER_NOT_REQUIRED
FAILOVER_STOP
FAILOVER_CONTINUE
getNormalisedHeaders()
prepareHeaders()
__rankServers()
$ESSENTIAL_HEADERS
$ESSENTIAL_USER_AGENT_HEADERS
$EXTRA_HEADERS
N/A
getCloudService()
connectCloud()
errorControler()
setCookieCache()
getCookieCache()
getFileCache()
setFileCache()
writeCacheToFile()
getDeviceCachePath()
getServerLatency()
rankSort()
$lastUsedCloudUrl
$selfAutoRanking
$headers
$fatalErrors
N/A

Constants

LICENCE_KEY

LICENCE_KEY = 'ENTER-YOUR-LICENCE-KEY'

Set to your DeviceAtlas licence key

DEBUG_MODE

DEBUG_MODE = true

true = throw exceptions on all errors and failures

AUTO_SERVER_RANKING

AUTO_SERVER_RANKING = true

true: server preference is decided by the API (faster server is preferred) false: server preference is $SERVERS sort order (top server is preferred) *

TEST_USERAGENT

TEST_USERAGENT = 'Mozilla/5.0 (Linux; U; Android 2.3.3; en-gb; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'

Build in test user agent

CLOUD_SERVICE_TIMEOUT

CLOUD_SERVICE_TIMEOUT = 2

Max time (seconds) to wait for each cloud server to give service

USE_FILE_CACHE

USE_FILE_CACHE = true

Cache cloud results in files

CACHE_ITEM_EXPIRY_SEC

CACHE_ITEM_EXPIRY_SEC = 2592000

Cache expire (for both file and cookie) 2592000 = 30 days in seconds

CACHE_NAME

CACHE_NAME = 'deviceatlas_cache'

File cache > directory name

USE_SYSTEM_TEMP_DIR

USE_SYSTEM_TEMP_DIR = true

File cache > leave as true to put cache in systems default temp directory

CUSTOM_CACHE_DIR

CUSTOM_CACHE_DIR = '/path/to/your/cache/'

File cache > this is only used if USE_SYSTEM_TEMP_DIR is false

SEND_EXTRA_HEADERS

SEND_EXTRA_HEADERS = false

true: extra headers are sent with each request to the service false: only select headers which are essential for detection are sent

AUTO_SERVER_RANKING_MAX_FAILURE

AUTO_SERVER_RANKING_MAX_FAILURE = 1

When ranking servers, if a server fails more than this number phase it out

AUTO_SERVER_RANKING_NUM_REQUESTS

AUTO_SERVER_RANKING_NUM_REQUESTS = 3

Number of requests to send when testing server latency

AUTO_SERVER_RANKING_LIFETIME

AUTO_SERVER_RANKING_LIFETIME = 1440

Server preferred list will be updated when older than this amount of minutes

SERVER_PHASEOUT_LIFETIME

SERVER_PHASEOUT_LIFETIME = 1440

Auto ranking = false > if top server fails it will be phased out for this amount of minutes

API_VERSION

API_VERSION = '1.4.3'

DeviceAtlas Cloud API version

MIN_PHP_VERSION

MIN_PHP_VERSION = '5.2.1'

Min DeviceAtlas Cloud API required PHP version

KEY_USERAGENT

KEY_USERAGENT = 'useragent'

A key of array returned by getDeviceData() - the user-agent is set to this key

KEY_SOURCE

KEY_SOURCE = 'source'

A key of array returned by getDeviceData() - the source of data is set to this key

KEY_ERROR

KEY_ERROR = 'error'

A key of array returned by getDeviceData() - the error message is set to this key

KEY_PROPERTIES

KEY_PROPERTIES = 'properties'

A key of array returned by getDeviceData() - the device properties are set to this key

SOURCE_FILE_CACHE

SOURCE_FILE_CACHE = 'file'

Device data source value set to KEY_SOURCE - device data source was file cache

SOURCE_CLOUD

SOURCE_CLOUD = 'cloud'

Device data source value set to KEY_SOURCE - device data source was cloud service

SOURCE_NONE

SOURCE_NONE = 'none'

Device data source value set to KEY_SOURCE - no device data, indicates an error

DA_HEADER_PREFIX

DA_HEADER_PREFIX = 'X-DA-'

For API internal usage

CLOUD_PATH

CLOUD_PATH = '/v1/detect/properties?licencekey=%s&useragent=%s'

For API internal usage

FAILOVER_NOT_REQUIRED

FAILOVER_NOT_REQUIRED = 0

Action to be taken after an end-point responds: If an-endpoint response was fine

FAILOVER_STOP

FAILOVER_STOP = 1

Action to be taken after an end-point responds: If the error controller returns this the fail-over mechanism must stop trying the next end-point

FAILOVER_CONTINUE

FAILOVER_CONTINUE = 2

Action to be taken after an end-point responds: If the error controller returns this the fail-over mechanism must try the next end-point

Properties

$SERVERS

$SERVERS : 

List of cloud service provider end-points The order of this list is par with end-point preference

Type

$rankingStatus

$rankingStatus : 

Type

$calledServers

$calledServers : 

Type

$ESSENTIAL_HEADERS

$ESSENTIAL_HEADERS : 

A list of http-headers to be sent to the DeviceAtlas Cloud. This headers are used for device detection, specially if a third party browser or a proxy changes the original user-agent.

Type

$ESSENTIAL_USER_AGENT_HEADERS

$ESSENTIAL_USER_AGENT_HEADERS : 

A list of http-headers which may contain the original user-agent.

this headers are sent to DeviceAtlas Cloud beside.

Type

$EXTRA_HEADERS

$EXTRA_HEADERS : 

A list of additional http-headers to be sent to the DeviceAtlas Cloud.

This headers are not sent by default. This headers can be used for carrier detection and geoip.

Type

$lastUsedCloudUrl

$lastUsedCloudUrl : 

Type

$selfAutoRanking

$selfAutoRanking : 

Type

$headers

$headers : 

Type

$fatalErrors

$fatalErrors : 

Type

Methods

getDeviceData()

getDeviceData(  $param = false) : array

Parameters

$param

Returns

array —
{
     DeviceAtlasCloudClient::KEY_USERAGENT: "UA" | null,
     DeviceAtlasCloudClient::KEY_SOURCE: "data source",
     DeviceAtlasCloudClient::KEY_PROPERTIES: {"propertyName": "PropertyVal",} | null,
     DeviceAtlasCloudClient::KEY_ERROR: err-msg-string | null,
}

getCacheBasePath()

getCacheBasePath() : string

Get the directory path in which the DeviceAtlas CloudApi puts cache files in (device data cache and server fail-over list).

Returns

string —

The cache directory

getServersLatencies()

getServersLatencies(  $numRequests = self::AUTO_SERVER_RANKING_NUM_REQUESTS) : array

Get a list of cloud end-points and their service latencies.

Parameters

$numRequests

Returns

array —

Cloud end-point info {{avg:, latencies:, host:, port:},}

getServers()

getServers() : array

Get DeviceAtlas cloud end-point list in the same order used by the API.

If auto-ranking is on then the ranked end-point list is returned otherwise the manual or the default fail-over list is returned.
If auto-ranking is on and the end-point list cache is invalid or out of date then the end-points will be ranked and cached first.

Returns

array —

DeviceAtlas cloud End-pont list {host: server-address, port: server-port}

rankServers()

rankServers() : array

If auto-ranking is on then rank the DeviceAtlas cloud end-points and put in cache.

Throws

\Exception

when unable to create cache file or directory

Returns

array —

the ranked end-point list or null=did not rank successfully

getCloudUrl()

getCloudUrl() : string

Get the URL of the last DeviceAtlas cloud end-point which was called to get device properties.

Returns

string —

The end-point URL, null=no call to a cloud end-point was made probably because the data was fetched from cache.

getNormalisedHeaders()

getNormalisedHeaders(  $setHeaders = null) 

normalize the HTTP header keys

Parameters

$setHeaders

prepareHeaders()

prepareHeaders() 

prepare cloud request headers which can help the detection

__rankServers()

__rankServers(  $servers = array()) 

servers=null rank and cache end-points servers=array cache servers (for updating the manual fail-over list)

Parameters

$servers

getCloudService()

getCloudService(  $userAgent,   $cookie) 

get data from the DeviceAtlas Cloud service

Parameters

$userAgent
$cookie

connectCloud()

connectCloud(  $server,   $headers,   $errors) : \(action,

connect to a cloud server and get device data, return data or null

Parameters

$server
$headers
$errors

Returns

\(action, —

props) & errors byref

errorControler()

errorControler(  $server,   $status,   $msg) : \(action,

when an end-point returns an error this method will check it

Parameters

$server
$status
$msg

Returns

\(action, —

error-message)

setCookieCache()

setCookieCache(  $cookie,   $deviceData) 

COOKIE CACHE > cache device data into two cookies on the client cookie cache remains in the API only to be compatible with older versions

Parameters

$cookie
$deviceData

getCookieCache()

getCookieCache(  $cookie) 

COOKIE CACHE > if device data is cached in a cookie then fetch data cookie cache remains in the API only to be compatible with older versions

Parameters

$cookie

getFileCache()

getFileCache(  $userAgent,   $cookie) 

FILE CACHE > if device data is cached in a file then fetch data

Parameters

$userAgent
$cookie

setFileCache()

setFileCache(  $userAgent,   $cookie,   $deviceData) 

FILE CACHE > cache device data into a file

Parameters

$userAgent
$cookie
$deviceData

writeCacheToFile()

writeCacheToFile(  $path,   $data,   $errMsg = null) 

lock cache file and write to it

Parameters

$path
$data
$errMsg

getDeviceCachePath()

getDeviceCachePath(  $userAgent,   $cookie) 

FILE CACHE > get the device data cache file-path

Parameters

$userAgent
$cookie

getServerLatency()

getServerLatency(  $server,   $numRequests) 

send request(s) to a DA cloud server and return the latencies

Parameters

$server
$numRequests

rankSort()

rankSort(  $a,   $b) 

sort by latency

Parameters

$a
$b