Nav apraksta

GA.php 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*******************************************************************************
  3. * Copyright (c) 2019, Code Atlantic LLC
  4. ******************************************************************************/
  5. if ( ! defined( 'ABSPATH' ) ) {
  6. exit;
  7. }
  8. /**
  9. * Class PUM_GA
  10. * @package Ahoy
  11. */
  12. class PUM_GA {
  13. /**
  14. * Get PUM_GA uuid.
  15. *
  16. * @return mixed|string
  17. */
  18. public static function get_uuid() {
  19. static $uuid;
  20. if ( ! isset( $uuid ) ) {
  21. $cookie = self::parse_cookie();
  22. if ( is_array( $cookie ) && ! empty( $cookie['cid'] ) ) {
  23. $uuid = $cookie['cid'];
  24. } else {
  25. $uuid = self::generate_uuid();
  26. }
  27. }
  28. return $uuid;
  29. }
  30. /**
  31. * Handle the parsing of the _ga cookie or setting it to a unique identifier
  32. */
  33. public static function parse_cookie() {
  34. static $cookie = false;
  35. if ( ! $cookie && isset( $_COOKIE['_ga'] ) ) {
  36. list( $version, $domainDepth, $cid1, $cid2 ) = preg_split( '[\.]', $_COOKIE["_ga"], 4 );
  37. $cookie = array( 'version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2 );
  38. }
  39. return $cookie;
  40. }
  41. /**
  42. * Generate UUID v4 function - needed to generate a CID when one isn't available
  43. */
  44. public static function generate_uuid() {
  45. return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 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. * Fire a hit to the google analytis collection api.
  61. *
  62. * See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
  63. *
  64. * @param null $data
  65. *
  66. * @return array|bool|WP_Error
  67. */
  68. public static function fire_hit( $data = null ) {
  69. if ( $data ) {
  70. $getString = 'https://ssl.google-analytics.com/collect';
  71. $getString .= '?payload_data&';
  72. $getString .= http_build_query( $data );
  73. $result = wp_remote_get( $getString );
  74. return $result;
  75. }
  76. return false;
  77. }
  78. }