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