TeraWurflRemoteClient
[ class tree: TeraWurflRemoteClient ] [ index: TeraWurflRemoteClient ] [ all elements ]

Source for file TeraWurflRemoteClient.php

Documentation is available at TeraWurflRemoteClient.php

  1. <?php
  2. /**
  3.  * Tera_WURFL - PHP MySQL driven WURFL
  4.  * 
  5.  * Tera-WURFL was written by Steve Kamerman, and is based on the
  6.  * Java WURFL Evolution package by Luca Passani and WURFL PHP Tools by Andrea Trassati.
  7.  * This version uses a MySQL database to store the entire WURFL file, multiple patch
  8.  * files, and a persistent caching mechanism to provide extreme performance increases.
  9.  * 
  10.  * @package TeraWurflRemoteClient
  11.  * @author Steve Kamerman <stevekamerman AT gmail.com>
  12.  * @version Stable 2.1.3 $Date: 2010/09/18 15:43:21
  13.  * @license http://www.mozilla.org/MPL/ MPL Vesion 1.1
  14.  */
  15. /**
  16.  * Tera-WURFL remote webservice client for PHP
  17.  * @package TeraWurflRemoteClient
  18.  */
  19.     
  20.     /**
  21.      * XML Data Format - this should only be used to communicate with Tera-WURFL 2.1.1 and older
  22.      * @var String 
  23.      */
  24.     public static $FORMAT_XML 'xml';
  25.     /**
  26.      * The JSON Data Format is the default transport for Tera-WURFL 2.1.2 and newer due to it's smaller size
  27.      * and better performance with the builtin PHP functions
  28.      * @var String 
  29.      */
  30.     public static $FORMAT_JSON 'json';
  31.     /**
  32.      * If you try to use a capability that has not been retrieved yet and this is set to true,
  33.      * it will generate another request to the webservice and retrieve this capability automatically.
  34.      * @var Bool 
  35.      */
  36.     public $autolookup = true;
  37.     /**
  38.      * Flattened version of Tera-WURFL's capabilities array, containing only capability names and values.
  39.      * Since it is 'Flattened', there a no groups in this array, just individual capabilities.
  40.      * @var Array 
  41.      */
  42.     public $capabilities = array();
  43.     /**
  44.      * Array of errors that were encountered while processing the request and/or response.
  45.      * @var Array 
  46.      */
  47.     public $errors;
  48.     /**
  49.      * The HTTP Headers that Tera-WURFL will look through to find the best User Agent, if one is not specified
  50.      * @var Array 
  51.      */
  52.     public static $userAgentHeaders array(
  53.         'HTTP_X_DEVICE_USER_AGENT',
  54.         'HTTP_X_ORIGINAL_USER_AGENT',
  55.         'HTTP_X_OPERAMINI_PHONE_UA',
  56.         'HTTP_X_SKYFIRE_PHONE',
  57.         'HTTP_X_BOLT_PHONE_UA',
  58.         'HTTP_USER_AGENT'
  59.     );
  60.     protected $format;
  61.     protected $userAgent;
  62.     protected $webserviceUrl;
  63.     protected $xml;
  64.     protected $json;
  65.     protected $clientVersion = '2.1.3';
  66.     protected $apiVersion;
  67.     protected $loadedDate;
  68.     protected $timeout;
  69.     
  70.     /**
  71.      * Creates a TeraWurflRemoteClient object.  NOTE: in Tera-WURFL 2.1.2 the default data format is JSON.
  72.      * This format is not supported in Tera-WURFL 2.1.1 or earlier, so if you must use this client with
  73.      * an earlier version of the server, set the second parameter to TeraWurflRemoteClient::$FORMAT_XML
  74.      * @param String URL to the master Tera-WURFL Server's webservice.php
  75.      * @param String TeraWurflRemoteClient::$FORMAT_JSON or TeraWurflRemoteClient::$FORMAT_XML
  76.      */
  77.     public function __construct($TeraWurflWebserviceURL,$data_format='json',$timeout=1){
  78.         $this->format = $data_format;
  79.         if(!self::validURL($TeraWurflWebserviceURL)){
  80.             throw new Exception("TeraWurflRemoteClient Error: the specified webservice URL is invalid.  Please make sure you pass the full url to Tera-WURFL's webservice.php.");
  81.             exit(1);
  82.         }
  83.         $this->capabilities = array();
  84.         $this->errors = array();
  85.         $this->webserviceUrl = $TeraWurflWebserviceURL;
  86.         $this->timeout = $timeout;
  87.     }
  88.     /**
  89.      * Get the requested capabilities from Tera-WURFL for the given user agent
  90.      * @param String HTTP User Agent of the device being detected
  91.      * @param Array Array of capabilities that you would like to retrieve
  92.      * @return bool Success
  93.      */
  94.     public function getDeviceCapabilitiesFromAgent($userAgentArray $capabilities){
  95.         $this->userAgent (is_null($userAgent))self::getUserAgent()$userAgent;
  96.         // build request string
  97.         $uri $this->webserviceUrl (strpos($this->webserviceUrl,'?')===false?'?':'&'
  98.         . 'ua=' urlencode($this->userAgent)
  99.         . '&format=' $this->format
  100.         . '&search=' implode('|',$capabilities);
  101.         $this->callTeraWurfl($uri);
  102.         $this->loadCapabilities();
  103.         $this->loadErrors();
  104.         return true;
  105.     }
  106.     /**
  107.      * Maintains backwards compatibility with Tera-WURFL <= 2.1.2.  This function is an
  108.      * alias for TeraWurflRemoteClient::getDeviceCapabilitiesFromAgent()
  109.      * @param String HTTP User Agent of the device being detected
  110.      * @param Array Array of capabilities that you would like to retrieve
  111.      * @return bool Success
  112.      */
  113.     public function getCapabilitiesFromAgent($userAgentArray $capabilities){
  114.         return $this->getDeviceCapabilitiesFromAgent($userAgent,$capabilities);
  115.     
  116.     /**
  117.      * Returns the value of the requested capability
  118.      * @param String The WURFL capability you are looking for (e.g. "is_wireless_device")
  119.      * @return Mixed String, Numeric, Bool
  120.      */
  121.     public function getDeviceCapability($capability){
  122.         $capability strtolower($capability);
  123.         if(!array_key_exists($capability$this->capabilities)){
  124.             if($this->autolookup){
  125.                 $this->getDeviceCapabilitiesFromAgent($this->userAgentarray($capability));
  126.                 return $this->capabilities[$capability];
  127.             }else{
  128.                 return null;
  129.             }
  130.         }
  131.         return $this->capabilities[$capability];
  132.     }
  133.     /**
  134.      * Get the version of the Tera-WURFL Remote Client (this file)
  135.      * @return String 
  136.      */
  137.     public function getClientVersion(){
  138.         return $this->clientVersion;
  139.     }
  140.     /**
  141.      * Get the version of the Tera-WURFL Webservice (webservice.php on server).  This is only available
  142.      * after a query has been made since it is returned in the response.
  143.      * @return String 
  144.      */
  145.     public function getAPIVersion(){
  146.         return $this->apiVersion;
  147.     }
  148.     /**
  149.      * Get the date that the Tera-WURFL was last updated.  This is only available
  150.      * after a query has been made since it is returned in the response.
  151.      * @return String 
  152.      */
  153.     public function getLoadedDate(){
  154.         return $this->loadedDate;
  155.     }
  156.     /**
  157.      * Make the webservice call to the server using the GET method and load the response.
  158.      * @param String The URI of the master server
  159.      * @return void 
  160.      */
  161.     protected function callTeraWurfl($uri){
  162.         $context_options array(
  163.             'http' => array(
  164.                 'user_agent' => 'Tera-WURFL/RemoteClient v'.$this->clientVersion,
  165.             )
  166.         );
  167.         if(version_compare(PHP_VERSION'5.2.1''>=')){
  168.             $context_options['http']['timeout'$this->timeout;
  169.         }
  170.         $context stream_context_create($context_options);
  171.         try{
  172.             switch($this->format){
  173.                 case self::$FORMAT_JSON:
  174.                     $data file_get_contents($uri,false,$context);
  175.                     $this->json json_decode($data,true);
  176.                     if(is_null($this->json)){
  177.                         // Trigger the catch block
  178.                         throw new Exception("foo");
  179.                     }
  180.                     unset($data);
  181.                     break;
  182.                 default:
  183.                 case self::$FORMAT_XML:
  184.                     if(!$this->xml simplexml_load_string(file_get_contents($uri,false,$context))){
  185.                         throw new Exception("foo");
  186.                     }
  187.                     break;
  188.             }
  189.         }catch(Exception $ex){
  190.             // Can't use builtin logging here through Tera-WURFL since it is on the client, not the server
  191.             throw new Exception("TeraWurflRemoteClient Error: Could not query Tera-WURFL master server.");
  192.             exit(1);
  193.         }
  194.     }
  195.     /**
  196.      * Parse the response into the capabilities array
  197.      * @return void 
  198.      */
  199.     protected function loadCapabilities(){
  200.         switch($this->format){
  201.             case self::$FORMAT_JSON:
  202.                 $this->apiVersion $this->json['apiVersion'];
  203.                 $this->loadedDate $this->json['mtime'];
  204.                 $this->capabilities['id'$this->json['id'];
  205.                 $this->capabilities array_merge($this->capabilities,$this->json['capabilities']);
  206.                 break;
  207.             default:
  208.             case self::$FORMAT_XML:
  209.                 $this->apiVersion $this->xml->device['apiVersion'];
  210.                 $this->loadedDate $this->xml->device['mtime'];
  211.                 foreach($this->xml->device->capability as $cap){
  212.                     $this->capabilities[(string)$cap['name']] self::niceCast((string)$cap['value']);
  213.                 }
  214.                 $this->capabilities['id'= (string)$this->xml->device['id'];
  215.                 break;
  216.         }
  217.     }
  218.     /**
  219.      * Parse the response's errors into the errors array
  220.      * @return void 
  221.      */
  222.     protected function loadErrors(){
  223.         switch($this->format){
  224.             case self::$FORMAT_JSON:
  225.                 $this->errors &= $this->json['errors'];
  226.                 break;
  227.             default:
  228.             case self::$FORMAT_XML:
  229.                 foreach($this->xml->errors->error as $error){
  230.                     $this->errors[(string)$error['name']]=(string)$error['description'];
  231.                 }
  232.                 break;
  233.         }
  234.     }
  235.     /**
  236.      * Cast strings into proper variable types, i.e. 'true' into true
  237.      * @param $value 
  238.      * @return Mixed String, Bool, Float
  239.      */
  240.     protected static function niceCast($value){
  241.         // Clean Boolean values
  242.         if($value === 'true')$value=true;
  243.         if($value === 'false')$value=false;
  244.         if(!is_bool($value)){
  245.             // Clean Numeric values by loosely comparing the (float) to the (string)
  246.             $numval = (float)$value;
  247.             if(strcmp($value,$numval)==0)$value=$numval;
  248.         }
  249.         return $value;
  250.     }
  251.     /**
  252.      * Is the given URL valid
  253.      * @param $url 
  254.      * @return Bool 
  255.      */
  256.     protected static function validURL($url){
  257.         if(preg_match('/^(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',$url)) return true;
  258.         return false;
  259.     }    
  260.     /**
  261.      * Return the requesting client's User Agent
  262.      * @param $source 
  263.      * @return String 
  264.      */
  265.     public static function getUserAgent($source=null){
  266.         if(is_null($source|| !is_array($source))$source $_SERVER;
  267.         $userAgent '';
  268.         if(isset($_GET['UA'])){
  269.             $userAgent $_GET['UA'];
  270.         }else{
  271.             foreach(self::$userAgentHeaders as $header){
  272.                 if(array_key_exists($header,$source&& $source[$header]){
  273.                     $userAgent $source[$header];
  274.                     break;
  275.                 }
  276.             }
  277.         }
  278.         return $userAgent;
  279.     }
  280. }

Documentation generated on Sun, 19 Sep 2010 00:16:03 +0000 by phpDocumentor 1.4.3