You are here

shurly_analytics.module in ShURLy 8

Same filename and directory in other branches
  1. 7 shurly_analytics/shurly_analytics.module

Analytics ShURLy functionalities.

File

shurly_analytics/shurly_analytics.module
View source
<?php

/**
 * @file
 * Analytics ShURLy functionalities.
 */

/**
 * Implements shurly_redirect_after().
 */
function shurly_analytics_shurly_redirect_after($row) {
  if (\Drupal::config('google_analytics.settings')
    ->get('account')) {
    $ga_id = \Drupal::config('shurly_analytics.settings')
      ->get('shurly_ga_account');
    $cid = _shurly_analytics_cookies();
    $path_args = explode('/', \Drupal::request()
      ->getPathInfo());
    $path = "/" . $path_args[1];
    $destination = $row->destination;
    $z = microtime(TRUE);
    $data = [
      'v' => 1,
      'tid' => $ga_id,
      'cid' => $cid,
      'uip' => $_SERVER['REMOTE_ADDR'],
      't' => 'pageview',
      'dh' => $_SERVER['SERVER_NAME'],
      'dl' => $destination,
      'dp' => $path,
      'aip' => 1,
      'dr' => $_SERVER['HTTP_REFERER'],
      'z' => $z,
    ];
    if ($data) {
      $getString = 'https://ssl.google-analytics.com/collect';
      $getString .= '?payload_data&';
      $getString .= http_build_query($data);
      $request = file_get_contents($getString, FALSE);
      if ($request) {
        return;
      }
      return;
    }
  }
}

/**
 * Function to retrieve the cid from the cookie
 * Taken from
 * http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
 */
function _shurly_analytics_cookies() {
  if (isset($_COOKIE['_ga'])) {
    list($version, $domainDepth, $cid1, $cid2) = preg_split('/[\\.]/', $_COOKIE['_ga'], 4);
    $contents = [
      'version' => $version,
      'domainDepth' => $domainDepth,
      'cid' => $cid1 . '.' . $cid2,
    ];
    $cid = $contents['cid'];
  }
  else {
    $cid = _shurly_analytics_get_uuid();
  }
  return $cid;
}

/**
 * Function to get a unique uuid
 * Taken from
 * http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
 */
function _shurly_analytics_get_uuid() {
  return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
}

Functions