uc_googleanalytics.module 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. /**
  3. * @file
  4. * Adds the required Javascript to the checkout completion page to allow
  5. * e-commerce statistics tracking through Google Analytics.
  6. *
  7. * Refer to http://code.google.com/apis/analytics/docs/gaTrackingEcommerce.html
  8. * for documentation on the functions used to submit e-commerce statistics to
  9. * Google Analytics.
  10. */
  11. /**
  12. * Implements hook_enable().
  13. */
  14. function uc_googleanalytics_enable() {
  15. // Get the weight of the Google Analytics module.
  16. $weight = db_query("SELECT weight FROM {system} WHERE name = :module", array(':module' => 'googleanalytics'))->fetchField();
  17. // Update the weight of the UC Google Analytics module so its hooks get called
  18. // after the actual Google Analytics module.
  19. db_update('system')
  20. ->fields(array('weight' => max(1000, $weight + 1)))
  21. ->condition('name', 'uc_googleanalytics')
  22. ->execute();
  23. }
  24. /**
  25. * Check which version of google analytics code is used on the site.
  26. */
  27. function uc_googleanalytics_flush_caches() {
  28. $info = system_get_info('module', 'googleanalytics');
  29. if (preg_match('|7\.x\-[2-9]\.[0-9x]+|', $info['version'])) {
  30. variable_set('uc_googleanalytics_version', 'analytics.js');
  31. }
  32. else {
  33. variable_set('uc_googleanalytics_version', 'ga.js');
  34. }
  35. }
  36. /**
  37. * Implements hook_page_alter().
  38. */
  39. function uc_googleanalytics_page_alter(&$page) {
  40. // Check to see if we are at the order completion page.
  41. if (uc_googleanalytics_display()) {
  42. // If so, then if we can load the order...
  43. if (!empty($_SESSION['ucga_order_id']) && $order = uc_order_load($_SESSION['ucga_order_id'])) {
  44. // Build the GA tracking code.
  45. $script = uc_googleanalytics_ecommerce_js($order);
  46. // Add the code to the footer.
  47. drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer', 'preprocess' => FALSE));
  48. }
  49. // Clean out the session variable.
  50. if (isset($_SESSION['ucga_order_id'])) {
  51. unset($_SESSION['ucga_order_id']);
  52. }
  53. }
  54. }
  55. /**
  56. * Implements hook_uc_order().
  57. */
  58. function uc_googleanalytics_uc_order($op, $order, $arg2) {
  59. // If a new order is created during the checkout process...
  60. if ($op == 'new') {
  61. // Store the order ID for later use.
  62. $_SESSION['ucga_order_id'] = $order->order_id;
  63. }
  64. }
  65. /**
  66. * Determine whether or not to display the e-commerce related JS through GA.
  67. *
  68. * @return
  69. * TRUE or FALSE indicating whether or not to display the GA e-commerce JS.
  70. */
  71. function uc_googleanalytics_display() {
  72. // Display the GA e-commerce JS if the URL is cart/checkout/complete...
  73. if (arg(0) == 'cart' && arg(1) == 'checkout' && arg(2) == 'complete') {
  74. return TRUE;
  75. }
  76. // Or if the URL is the custom completion page.
  77. $completion_page = variable_get('uc_cart_checkout_complete_page', '');
  78. if (!empty($completion_page) && $completion_page == drupal_get_path_alias($_GET['q'])) {
  79. return TRUE;
  80. }
  81. // Or if another module says this is the page through hook_ucga_display().
  82. foreach (module_invoke_all('ucga_display') as $result) {
  83. if ($result === TRUE) {
  84. return TRUE;
  85. }
  86. }
  87. // Otherwise return FALSE.
  88. return FALSE;
  89. }
  90. /**
  91. * Build the e-commerce JS passed to Google Analytics for order tracking.
  92. *
  93. * @param $order
  94. * The fully loaded order object to convert into GA JS.
  95. *
  96. * @return
  97. * The JS that should be added to the page footer.
  98. */
  99. function uc_googleanalytics_ecommerce_js($order) {
  100. $analytics_version = variable_get('uc_googleanalytics_version', 'ga.js');
  101. if ($analytics_version == 'analytics.js') {
  102. $script = 'ga("require", "ecommerce", "ecommerce.js");';
  103. }
  104. else {
  105. $script = '';
  106. }
  107. // Lookup the name of the country or default to the ID if it can't be found
  108. // for some reason.
  109. if ($country_data = uc_get_country_data(array('country_id' => $order->billing_country))) {
  110. $order->billing_country_name = $country_data[0]['country_name'];
  111. }
  112. else {
  113. $order->billing_country_name = $order->billing_country;
  114. }
  115. // Lookup the name of the zone.
  116. $order->billing_zone_name = uc_zone_get_by_id($order->billing_zone);
  117. // Calculate order tax and shipping totals.
  118. $order->tax_total = 0;
  119. $order->shipping_total = 0;
  120. foreach ($order->line_items as $line_item) {
  121. if ($line_item['type'] == 'tax') {
  122. $order->tax_total += $line_item['amount'];
  123. }
  124. elseif ($line_item['type'] == 'shipping') {
  125. $order->shipping_total += $line_item['amount'];
  126. }
  127. }
  128. // Build the transaction arguments.
  129. $trans = array(
  130. 'order_id' => $order->order_id,
  131. 'store' => uc_store_name(),
  132. 'total' => $order->order_total,
  133. 'tax' => $order->tax_total,
  134. 'shipping' => $order->shipping_total,
  135. 'city' => $order->billing_city,
  136. 'state' => $order->billing_zone_name,
  137. 'country' => $order->billing_country_name,
  138. );
  139. // Allow modules to alter the transaction arguments.
  140. drupal_alter('ucga_trans', $trans, $order);
  141. // Create GA-friendly associative array.
  142. $script_args = array(
  143. 'id' => $trans['order_id'],
  144. 'affiliation' => $trans['store'],
  145. 'revenue' => $trans['total'],
  146. 'tax' => $trans['tax'],
  147. 'shipping' => $trans['shipping'],
  148. 'city' => $trans['city'],
  149. 'region' => $trans['state'],
  150. 'country' => $trans['country'],
  151. );
  152. // Add the transaction line to the JS.
  153. if ($analytics_version == 'analytics.js') {
  154. $script .= 'ga("ecommerce:addTransaction", ' . drupal_json_encode($script_args) . ');';
  155. }
  156. else {
  157. foreach ($script_args as &$arg) {
  158. $arg = drupal_json_encode($arg);
  159. }
  160. $script .= '_gaq.push(["_addTrans", ' . implode(', ', $script_args) . ']);';
  161. }
  162. // Loop through the products on the order.
  163. foreach ($order->products as $product) {
  164. $product->category = '';
  165. // Try to find a category (term) for the product. Since products most often
  166. // only have one category, the first one returned (in the
  167. // $node->taxonomy_catalog) is chosen.
  168. if (module_exists('taxonomy')) {
  169. $node = node_load($product->nid);
  170. if (isset($node->taxonomy_catalog[LANGUAGE_NONE][0]['tid'])) {
  171. $term = taxonomy_term_load($node->taxonomy_catalog[LANGUAGE_NONE][0]['tid']);
  172. $product->category = $term->name;
  173. }
  174. }
  175. if (empty($product->category)) {
  176. $product->category = t('No category');
  177. }
  178. // Build the item arguments.
  179. $item = array(
  180. 'order_id' => $order->order_id,
  181. 'sku' => $product->model,
  182. 'name' => $product->title,
  183. 'category' => $product->category,
  184. 'price' => $product->price,
  185. 'qty' => $product->qty,
  186. );
  187. // Allow modules to alter the item arguments.
  188. drupal_alter('ucga_item', $item, $product, $trans, $order);
  189. // Create GA-friendly associative array.
  190. $script_args = array(
  191. 'id' => $item['order_id'],
  192. 'sku' => $item['sku'],
  193. 'name' => $item['name'],
  194. 'category' => (string) $item['category'],
  195. 'price' => $item['price'],
  196. 'quantity' => $item['qty'],
  197. );
  198. // Add the item line to the JS.
  199. if ($analytics_version == 'analytics.js') {
  200. $script .= 'ga("ecommerce:addItem", ' . drupal_json_encode($script_args) . ');';
  201. }
  202. else {
  203. foreach ($script_args as &$arg) {
  204. $arg = drupal_json_encode($arg);
  205. }
  206. $script .= '_gaq.push(["_addItem", ' . implode(', ', $script_args) . ']);';
  207. }
  208. }
  209. // Add the function to submit the transaction to GA.
  210. if ($analytics_version == 'analytics.js') {
  211. $script .= 'ga("ecommerce:send");';
  212. }
  213. else {
  214. $script .= '_gaq.push(["_trackTrans"]);';
  215. }
  216. return $script;
  217. }