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