zwetan

Google Universal Analytics PHP

Oct 13th, 2014
633
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.82 KB | None | 0 0
  1. <?php
  2.  
  3. /* Usage:
  4.    $trackingID = "UA-000000-0";
  5.    $useSSL = FALSE;
  6.    $useCacheBuster = FALSE;
  7.    $ga = new \Corsaair\GoogleAnalytics( $trackingID, "api.domain.com", $useSSL, $useCacheBuster );
  8.  
  9.    $ga->pageview( "/path/hello/world" );
  10.  
  11.    see: https://developers.google.com/analytics/devguides/collection/protocol/v1/
  12. */
  13.  
  14. namespace Corsaair;
  15.  
  16. class GoogleAnalytics
  17. {
  18.     public $trackingID;
  19.     public $hostname;
  20.     public $clientID;
  21.  
  22.     public $useSSL;
  23.     public $useCacheBuster;
  24.  
  25.     public function __construct( $trackingID, $hostname = "", $useSSL = FALSE, $useCacheBuster = FALSE )
  26.     {
  27.         //UA-ID: Tracking ID
  28.         $this->trackingID = $trackingID;
  29.  
  30.         //hostname
  31.         $this->hostname   = $hostname;
  32.  
  33.         //Client ID
  34.         $this->clientID   = $this->getCliendID();
  35.  
  36.  
  37.         //options
  38.         $this->useSSL         = $useSSL;
  39.         $this->useCacheBuster = $useCacheBuster;
  40.     }
  41.  
  42.     public function generateUUID()
  43.     {
  44.         return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  45.                         // 32 bits for "time_low"
  46.                         mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
  47.                         // 16 bits for "time_mid"
  48.                         mt_rand( 0, 0xffff ),
  49.                         // 16 bits for "time_hi_and_version",
  50.                         // four most significant bits holds version number 4
  51.                         mt_rand( 0, 0x0fff ) | 0x4000,
  52.                         // 16 bits, 8 bits for "clk_seq_hi_res",
  53.                         // 8 bits for "clk_seq_low",
  54.                         // two most significant bits holds zero and one for variant DCE1.1
  55.                         mt_rand( 0, 0x3fff ) | 0x8000,
  56.                         // 48 bits for "node"
  57.                         mt_rand( 0, 0xffff ), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
  58.         );
  59.     }
  60.  
  61.     public function getCliendID()
  62.     {
  63.         if( isset($_COOKIE['_ga']) )
  64.         {
  65.             list( $version, $domainDepth, $cid1, $cid2 ) = split( '[\.]', $_COOKIE["_ga"], 4 );
  66.             $contents = [ 'version' => $version,
  67.                           'domainDepth' => $domainDepth,
  68.                           'cid' => $cid1 . '.' . $cid2 ];
  69.             $cid = $contents['cid'];
  70.         }
  71.         else if( isset($_SERVER["HTTP_X_UUID"]) )
  72.         {
  73.             $cid = $_SERVER["HTTP_X_UUID"];
  74.         }
  75.         else
  76.         {
  77.             $cid = $this->generateUUID();
  78.         }
  79.        
  80.         return $cid;
  81.     }
  82.  
  83.     public function socketPost( $url, $post_string, $ua = null )
  84.     {
  85.         $parts = parse_url( $url );
  86.        
  87.         // workout port and open socket
  88.         $port = isset( $parts["port"] ) ? $parts["port"] : 80;
  89.         $host = $parts[ "host" ];
  90.         $path = $parts[ "path" ];
  91.  
  92.         $fp = fsockopen( $host, $port, $errno, $errstr, 30 );
  93.         $success = $fp;
  94.        
  95.         if( $fp )
  96.         {
  97.             // create output string
  98.             $output = "POST $path HTTP/1.1\r\n";
  99.            
  100.             if( is_string($ua) )
  101.             {
  102.                 $output .= "User-Agent: $ua\r\n";
  103.             }
  104.  
  105.             $post_len = strlen( $post_string );
  106.  
  107.             $output .= "Host: $host\r\n";
  108.             $output .= "Content-Type: application/x-www-form-urlencoded\r\n";
  109.             $output .= "Content-Length: $post_len\r\n";
  110.             $output .= "Connection: Close\r\n\r\n";
  111.             $output .= isset($post_string) ? $post_string : "";
  112.            
  113.             // send output to $url handle
  114.             $success = fwrite( $fp, $output );
  115.             fclose( $fp );
  116.         }
  117.         else
  118.         {
  119.             echo "Error [$errno]: $errstr" . PHP_EOL;
  120.         }
  121.  
  122.         return $success ? TRUE : FALSE;
  123.     }
  124.  
  125.     public function sendHit( $data = NULL )
  126.     {
  127.         if( $data )
  128.         {
  129.             $url = "";
  130.  
  131.             if( $this->useSSL )
  132.             {
  133.                 $url .= "https://ssl.google-analytics.com/collect";
  134.             }
  135.             else
  136.             {
  137.                 $url .= "http://www.google-analytics.com/collect";
  138.             }
  139.  
  140.             if( !empty($this->hostname) )
  141.             {
  142.                 $data["dh"] = $this->hostname;
  143.             }
  144.  
  145.             if( isset($_SERVER["REMOTE_ADDR"]) )
  146.             {
  147.                 $data["uip"] = $_SERVER["REMOTE_ADDR"];
  148.             }
  149.  
  150.             if( $this->useCacheBuster && isset($_SERVER["REQUEST_TIME"]) )
  151.             {
  152.                 $data["z"] = $_SERVER["REQUEST_TIME"];
  153.             }
  154.  
  155.             $query  = "?payload_data&";
  156.             $query .= http_build_query( $data );
  157.            
  158.             $UA     = $_SERVER["HTTP_USER_AGENT"];
  159.  
  160.             $result = $this->socketPost( $url, $query, $UA );
  161.             return $result;
  162.         }
  163.  
  164.         return FALSE;
  165.     }
  166.  
  167.     public function pageview( $path, $title = NULL )
  168.     {
  169.         $v   = 1;
  170.         $tid = $this->trackingID;
  171.         $cid = $this->clientID;
  172.  
  173.         $data = [ "v"   => $v,
  174.                   "tid" => $tid,
  175.                   "cid" => $cid,
  176.                   "t"   => "pageview"
  177.                 ];
  178.  
  179.         if( !empty($title) )
  180.         {
  181.             $data[ "dt" ] = $title;
  182.         }
  183.  
  184.         $data[ "dp" ] = $path;
  185.  
  186.         return $this->sendHit( $data );
  187.     }
  188.  
  189.     public function exception( $message, $fatal = FALSE )
  190.     {
  191.         $v   = 1;
  192.         $tid = $this->trackingID;
  193.         $cid = $this->clientID;
  194.  
  195.         $data = [ "v"   => $v,
  196.                   "tid" => $tid,
  197.                   "cid" => $cid,
  198.                   "t"   => "exception"
  199.                 ];
  200.  
  201.         $data[ "exd" ] = $message;
  202.         $data[ "exf" ] = $fatal ? 1: 0;
  203.  
  204.  
  205.         return $this->sendHit( $data );
  206.     }
  207.  
  208. }
  209.  
  210. ?>
Add Comment
Please, Sign In to add comment