Translations should no longer exists in projects. They have been moved to l.d.o
[project/google_analytics.git] / googleanalytics.module
CommitLineData
0efd556a 1<?php
430ff5f8 2// $Id$
60b6111f 3
430ff5f8 4/*
97110728 5 * @file
430ff5f8 6 * Drupal Module: GoogleAnalytics
d18f90cc 7 * Adds the required Javascript to the bottom of all your Drupal pages
0efd556a
MC
8 * to allow tracking by the Google Analytics statistics package.
9 *
e755cc10 10 * @author: Alexander Hass <http://drupal.org/user/85918>
0efd556a
MC
11 */
12
e1097f5d 13define('GA_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
430ff5f8 14
5bcdd55b 15function googleanalytics_help($path, $arg) {
16 switch ($path) {
ffbad14e 17 case 'admin/config/system/googleanalytics':
a8664f42 18 return t('<a href="@ga_url">Google Analytics</a> is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'http://www.google.com/analytics/'));
0efd556a
MC
19 }
20}
21
34a9e54b 22function googleanalytics_permission() {
bdff3a24 23 return array(
24 'administer google analytics' => array(
25 'title' => t('Administer Google Analytics'),
26 'description' => t('Perform maintenance tasks for Google Analytics.'),
27 ),
28 'opt-in or out of tracking' => array(
29 'title' => t('Opt-in or out of tracking'),
30 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
31 ),
32 'use PHP for tracking visibility' => array(
33 'title' => t('Use PHP for tracking visibility'),
34 'description' => t('Enter PHP code in the field for tracking visibility settings. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
35 ),
ffbad14e 36 );
60b6111f 37}
5bcdd55b 38
60b6111f 39function googleanalytics_menu() {
ffbad14e 40 $items['admin/config/system/googleanalytics'] = array(
5bcdd55b 41 'title' => 'Google Analytics',
a8664f42 42 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
5bcdd55b 43 'page callback' => 'drupal_get_form',
60b6111f 44 'page arguments' => array('googleanalytics_admin_settings_form'),
45 'access arguments' => array('administer google analytics'),
5bcdd55b 46 'type' => MENU_NORMAL_ITEM,
ffbad14e 47 'file' => 'googleanalytics.admin.inc',
5bcdd55b 48 );
49
834c2715
MC
50 return $items;
51}
52
bcfa518e 53/**
01f3950e 54 * Implementation of hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
bcfa518e 55 */
56function googleanalytics_page_alter(&$page) {
2cc17535
MC
57 global $user;
58
430ff5f8 59 $id = variable_get('googleanalytics_account', '');
0efd556a 60
ea86491a 61 // Get page status code for visibility filtering.
62 $status = drupal_get_http_header('Status');
63 $trackable_status_codes = array(
64 '403 Forbidden',
65 '404 Not Found',
66 );
67
60b6111f 68 // 1. Check if the GA account number has a value.
69 // 2. Track page views based on visibility value.
70 // 3. Check if we should track the currently active user's role.
c5f72148 71 // 4. Ignore pages visibility filter for 404 or 403 status codes.
ea86491a 72 if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
60b6111f 73
b94bc8a9 74 // We allow different scopes. Default to 'header' but allow user to override if they really need to.
01f3950e 75 $scope = variable_get('googleanalytics_js_scope', 'header');
76
01f3950e 77 if (variable_get('googleanalytics_trackadsense', FALSE)) {
f5082081 78 // Custom tracking. Prepend before all other JavaScript.
79 drupal_add_js('window.google_analytics_uacct = ' . drupal_json_encode($id) . ';', array('type' => 'inline', 'weight' => JS_LIBRARY - 21));
01f3950e 80 }
68c107f3 81
60b6111f 82 // Add link tracking.
83 $link_settings = array();
97110728 84 if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
85 $link_settings['trackOutgoing'] = $track_outgoing;
60b6111f 86 }
97110728 87 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
88 $link_settings['trackMailto'] = $track_mailto;
60b6111f 89 }
97110728 90 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS))) {
91 $link_settings['trackDownload'] = $track_download;
60b6111f 92 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
93 }
94 if (!empty($link_settings)) {
f5082081 95 drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
96 drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
60b6111f 97 }
4fe1e402 98
60b6111f 99 // Add User profile segmentation values.
9f1c4438 100 $profile_fields = variable_get('googleanalytics_segmentation', array());
5360409f 101 if (!empty($profile_fields)) {
9f1c4438 102 // Invoke all modules having a hook_user_load() implemented.
103 // If the invoked modules extend the $user object, the additional
104 // data can be tracked.
105 module_invoke_all('user_load', array($user->uid => $user));
d2c2fa2c
MC
106
107 $fields = array();
68c107f3 108 foreach ($profile_fields as $field => $title) {
9f1c4438 109 $fields[$field] = is_array($user->$field) ? implode(',', $user->$field) : $user->$field;
68c107f3 110 }
111
60b6111f 112 // Only show segmentation variable if there are specified fields.
5bcdd55b 113 $segmentation = '';
68c107f3 114 if (count($fields) > 0) {
01f3950e 115 $segmentation = '_gaq.push(["_setVar", ' . drupal_json_encode(implode(':', $fields)) . ']);';
d2c2fa2c 116 }
60b6111f 117 }
5215f4f7 118
60b6111f 119 // Site search tracking support.
120 $url_custom = '';
279fbf35 121 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
122 $url_custom = drupal_json_encode(rawurldecode(url('search/'. arg(1), array('query' => array('search' => $keys)))));
97110728 123 }
124
125 // If this node is a translation of another node, pass the original
126 // node instead.
127 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
128 // Check we have a node object, it supports translation, and its
129 // translated node ID (tnid) doesn't match its own node ID.
130 $node = menu_get_object();
131 if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
132 $source_node = node_load($node->tnid);
133 $languages = language_list();
505b14cf 134 $url_custom = drupal_json_encode(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language])));
97110728 135 }
60b6111f 136 }
137
138 // Track access denied (403) and file not found (404) pages.
bcfa518e 139 if ($status == '403 Forbidden') {
140 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
141 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
142 }
143 elseif ($status == '404 Not Found') {
144 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
68c107f3 145 }
146
60b6111f 147 // Add any custom code snippets if specified.
97110728 148 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
149 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
150
bcfa518e 151 // Build tracker code.
01f3950e 152 $script = 'var _gaq = _gaq || [];';
153 $script .= '_gaq.push(["_setAccount", ' . drupal_json_encode($id) . ']);';
b44fb664 154 if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
43b4bedb 155 // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
156 // a workaround until "_anonymizeIp" has been implemented/fixed.
69ee2449 157 $script .= '_gaq.push(["_gat._anonymizeIp"]);';
b44fb664 158 }
97110728 159 if (!empty($segmentation)) {
160 $script .= $segmentation;
68c107f3 161 }
97110728 162 if (!empty($codesnippet_before)) {
163 $script .= $codesnippet_before;
164 }
01f3950e 165 if (empty($url_custom)) {
166 $script .= '_gaq.push(["_trackPageview"]);';
167 }
168 else {
169 $script .= '_gaq.push(["_trackPageview", ' . $url_custom . ']);';
170 }
97110728 171 if (!empty($codesnippet_after)) {
172 $script .= $codesnippet_after;
68c107f3 173 }
01f3950e 174
175 $script .= '(function() {';
176 $script .= 'var ga = document.createElement("script");';
177 $script .= 'ga.type = "text/javascript";';
178 $script .= 'ga.async = true;';
179
94231a84 180 // A dummy query-string is added to filenames, to gain control over
181 // browser-caching. The string changes on every update or full cache
182 // flush, forcing browsers to load a new copy of the files, as the
183 // URL changed.
184 $query_string = '?' . variable_get('css_js_query_string', '0');
185
01f3950e 186 // Should a local cached copy of ga.js be used?
44a8dfae 187 if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('http://www.google-analytics.com/ga.js')) {
94231a84 188 $script .= 'ga.src = "' . $url . $query_string . '";';
01f3950e 189 }
190 else {
191 $script .= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";';
192 }
193 $script .= 'var s = document.getElementsByTagName("script")[0];';
194 $script .= 's.parentNode.insertBefore(ga, s);';
195 $script .= '})();';
68c107f3 196
f5082081 197 drupal_add_js($script, array('scope'=> $scope, 'type' => 'inline'));
60b6111f 198 }
199}
200
201/**
5034470c 202 * Implement hook_form_FORM_ID_alter().
60b6111f 203 *
204 * Allow users to decide if tracking code will be added to pages or not.
205 */
5034470c 206function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
207 $account = $form['#user'];
208 $category = $form['#user_category'];
209
bdff3a24 210 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
211 $form['googleanalytics'] = array(
212 '#type' => 'fieldset',
213 '#title' => t('Google Analytics configuration'),
214 '#weight' => 3,
215 '#collapsible' => TRUE,
216 '#tree' => TRUE
217 );
d1396871 218
219 switch ($custom) {
220 case 1:
d1396871 221 $description = t('Users are tracked by default, but you are able to opt out.');
222 break;
223
224 case 2:
d1396871 225 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
226 break;
227 }
228
bdff3a24 229 $form['googleanalytics']['custom'] = array(
230 '#type' => 'checkbox',
9ec4587a 231 '#title' => t('Enable user tracking'),
d1396871 232 '#description' => $description,
c018bd81 233 '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1)
bdff3a24 234 );
235
236 return $form;
0efd556a
MC
237 }
238}
239
0efd556a 240/**
c018bd81 241 * Implements hook_user_presave().
242 */
243function googleanalytics_user_presave(&$edit, $account, $category) {
244 if (isset($edit['googleanalytics']['custom'])) {
245 $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
246 }
247}
248
249/**
68c107f3 250 * Implementation of hook_cron().
251 */
252function googleanalytics_cron() {
3be1671e 253 // Regenerate the tracking code file every day.
35b6a781 254 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
3be1671e 255 _googleanalytics_cache('http://www.google-analytics.com/ga.js', TRUE);
60b6111f 256 variable_set('googleanalytics_last_cache', time());
68c107f3 257 }
258}
259
260/**
3be1671e 261 * Download/Synchronize/Cache tracking code file locally.
262 *
68c107f3 263 * @param $location
264 * The full URL to the external javascript file.
3be1671e 265 * @param $sync_cached_file
266 * Synchronize tracking code and update if remote file have changed.
68c107f3 267 * @return mixed
268 * The path to the local javascript file on success, boolean FALSE on failure.
269 */
3be1671e 270function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
ffbad14e 271 $path = 'public://googleanalytics';
3be1671e 272 $file_destination = $path . '/' . basename($location);
273
274 if (!file_exists($file_destination) || $sync_cached_file) {
275 // Download the latest tracking code.
68c107f3 276 $result = drupal_http_request($location);
3be1671e 277
68c107f3 278 if ($result->code == 200) {
3be1671e 279 if (file_exists($file_destination)) {
280 // Synchronize tracking code and and replace local file if outdated.
41359dfc 281 $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
282 $data_hash_remote = drupal_hash_base64($result->data);
3be1671e 283 // Check that the files directory is writable.
2bb12b3b 284 if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
3be1671e 285 // Save updated tracking code file to disk.
286 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
287 watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
288
289 // Change query-strings on css/js files to enforce reload for all users.
290 _drupal_flush_css_js();
291 }
292 }
293 else {
294 // Check that the files directory is writable.
295 if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
296 // There is no need to flush JS here as core refreshes JS caches
297 // automatically, if new files are added.
298 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
299 watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
300
301 // Return the local JS file path.
c26d9ec3 302 return file_create_url($file_destination);
3be1671e 303 }
68c107f3 304 }
305 }
306 }
307 else {
3be1671e 308 // Return the local JS file path.
c26d9ec3 309 return file_create_url($file_destination);
68c107f3 310 }
311}
60b6111f 312
313/**
35b6a781 314 * Delete cached files and directory.
315 */
316function googleanalytics_clear_js_cache() {
317 $path = 'public://googleanalytics';
eac69637 318 if (file_prepare_directory($path)) {
9911c0b4 319 file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
158020df 320 drupal_rmdir($path);
35b6a781 321
8de0b902 322 // Change query-strings on css/js files to enforce reload for all users.
323 _drupal_flush_css_js();
ec15a531 324
325 watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
35b6a781 326 }
327}
328
329/**
279fbf35 330 * Helper function for grabbing search keys. Function is missing in D7.
331 *
332 * http://api.drupal.org/api/function/search_get_keys/6
333 */
334function googleanalytics_search_get_keys() {
335 static $return;
336 if (!isset($return)) {
337 // Extract keys as remainder of path
338 // Note: support old GET format of searches for existing links.
339 $path = explode('/', $_GET['q'], 3);
340 $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
341 $return = count($path) == 3 ? $path[2] : $keys;
342 }
343 return $return;
344}
345
346/**
60b6111f 347 * Tracking visibility check for an user object.
348 *
349 * @param $account
350 * A user object containing an array of roles to check.
351 * @return boolean
352 * A decision on if the current user is being tracked by Google Analytics.
353 */
354function _googleanalytics_visibility_user($account) {
355
356 $enabled = FALSE;
357
358 // Is current user a member of a role that should be tracked?
359 if (_googleanalytics_visibility_roles($account)) {
360
361 // Use the user's block visibility setting, if necessary.
362 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
c018bd81 363 if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
364 $enabled = $account->data['googleanalytics']['custom'];
60b6111f 365 }
366 else {
367 $enabled = ($custom == 1);
368 }
369 }
370 else {
371 $enabled = TRUE;
372 }
373
374 }
375
376 return $enabled;
377}
378
379/**
380 * Based on visibility setting this function returns TRUE if GA code should
381 * be added for the current role and otherwise FALSE.
382 */
383function _googleanalytics_visibility_roles($account) {
384
385 $enabled = FALSE;
386 $roles = variable_get('googleanalytics_roles', array());
387
388 if (array_sum($roles) > 0) {
389 // One or more roles are selected for tracking.
390 foreach (array_keys($account->roles) as $rid) {
391 // Is the current user a member of one role enabled for tracking?
392 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
393 // Current user is a member of a role that should be tracked.
394 $enabled = TRUE;
395 break;
396 }
397 }
398 }
399 else {
97110728 400 // No role is selected for tracking, therefor all roles should be tracked.
60b6111f 401 $enabled = TRUE;
402 }
403
404 return $enabled;
405}
406
407/**
408 * Based on visibility setting this function returns TRUE if GA code should
409 * be added to the current page and otherwise FALSE.
410 */
411function _googleanalytics_visibility_pages() {
412 static $page_match;
413
9a2a2efc 414 // Cache visibility result if function is called more than once.
60b6111f 415 if (!isset($page_match)) {
416
417 $visibility = variable_get('googleanalytics_visibility', 0);
418 $pages = variable_get('googleanalytics_pages', '');
419
420 // Match path if necessary.
421 if (!empty($pages)) {
422 if ($visibility < 2) {
423 $path = drupal_get_path_alias($_GET['q']);
424 // Compare with the internal and path alias (if any).
425 $page_match = drupal_match_path($path, $pages);
426 if ($path != $_GET['q']) {
427 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
428 }
429 // When $visibility has a value of 0, the block is displayed on
430 // all pages except those listed in $pages. When set to 1, it
431 // is displayed only on those pages listed in $pages.
432 $page_match = !($visibility xor $page_match);
433 }
434 else {
435 $page_match = drupal_eval($pages);
436 }
437 }
438 else {
439 $page_match = TRUE;
440 }
441
442 }
443 return $page_match;
444}