#545886 by hass: update extension list to piwik defaults
[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: Mike Carter <www.ixis.co.uk/contact>
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/settings/googleanalytics':
18 return t('<a href="@ga_url">Google Analytics</a> is a free statistics package based on the excellent Urchin system. This module provides services to better integrate Drupal with Google Analytics.', array('@ga_url' => 'http://www.google.com/analytics/'));
19 }
20 }
21
22 function googleanalytics_perm() {
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/settings/googleanalytics'] = array(
41 'title' => 'Google Analytics',
42 'description' => 'Configure the settings used to generate your Google Analytics tracking code.',
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 );
48
49 return $items;
50 }
51
52 function googleanalytics_init() {
53 global $user;
54
55 $id = variable_get('googleanalytics_account', '');
56
57 // 1. Check if the GA account number has a value.
58 // 2. Track page views based on visibility value.
59 // 3. Check if we should track the currently active user's role.
60 if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
61 $scope = variable_get('googleanalytics_js_scope', 'footer');
62
63 // Should a local cached copy of ga.js be used?
64 $js_file = 'ga.js';
65 $url = 'http://www.google-analytics.com/'. $js_file;
66
67 if (variable_get('googleanalytics_cache', 0) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC) && $source = _googleanalytics_cache($url)) {
68 drupal_add_js($source, array('type' => 'file', 'scope' => $scope));
69 }
70 else {
71 $script = 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
72 $script .= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/'. $js_file .'\' type=\'text/javascript\'%3E%3C/script%3E"));';
73 drupal_add_js($script, array('type' => 'inline', 'scope' => $scope, 'weight' => JS_DEFAULT - 1));
74 }
75
76 // Add link tracking.
77 $link_settings = array();
78 if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
79 $link_settings['trackOutgoing'] = $track_outgoing;
80 }
81 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
82 $link_settings['trackMailto'] = $track_mailto;
83 }
84 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS))) {
85 $link_settings['trackDownload'] = $track_download;
86 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
87 }
88 if (!empty($link_settings)) {
89 drupal_add_js(array('googleanalytics' => $link_settings), array('type' => 'setting', 'scope' => 'header'));
90 drupal_add_js(drupal_get_path('module', 'googleanalytics') .'/googleanalytics.js', array('type' => 'file', 'scope' => $scope));
91 }
92
93 // Custom tracking.
94 if (variable_get('googleanalytics_trackadsense', FALSE)) {
95 drupal_add_js('window.google_analytics_uacct = ' . drupal_to_js($id) . ';', 'inline', 'header');
96 }
97 }
98 }
99
100 /**
101 * Implementation of hook_footer() to insert Javascript at the end of the page.
102 */
103 function googleanalytics_footer($main = 0) {
104 global $user;
105
106 $id = variable_get('googleanalytics_account', '');
107
108 if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
109
110 // Add User profile segmentation values.
111 if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {
112
113 $p = module_invoke('profile', 'load_profile', $user);
114
115 $fields = array();
116 foreach ($profile_fields as $field => $title) {
117 $value = $user->$field;
118
119 if (is_array($value)) {
120 $value = implode(',', $value);
121 }
122
123 $fields[$field] = $value;
124 }
125
126 // Only show segmentation variable if there are specified fields.
127 $segmentation = '';
128 if (count($fields) > 0) {
129 $segmentation = 'pageTracker._setVar('. drupal_to_js(implode(':', $fields)) .');';
130 }
131 }
132
133 // Site search tracking support.
134 $url_custom = '';
135 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
136 $url_custom = drupal_to_js(url('search/'. arg(1), array('query' => 'search='. $keys)));
137 }
138
139 // If this node is a translation of another node, pass the original
140 // node instead.
141 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
142 // Check we have a node object, it supports translation, and its
143 // translated node ID (tnid) doesn't match its own node ID.
144 $node = menu_get_object();
145 if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
146 $source_node = node_load($node->tnid);
147 $languages = language_list();
148 $url_custom = drupal_to_js(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language])));
149 }
150 }
151
152 // Track access denied (403) and file not found (404) pages.
153 if (function_exists('drupal_get_headers')) {
154 $headers = drupal_get_headers();
155 if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
156 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
157 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
158 }
159 elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
160 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
161 }
162 }
163
164 // Add any custom code snippets if specified.
165 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
166 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
167
168 // Build tracker code for footer.
169 $script = 'try{';
170 $script .= 'var pageTracker = _gat._getTracker('. drupal_to_js($id) .');';
171 if (!empty($segmentation)) {
172 $script .= $segmentation;
173 }
174 if (!empty($codesnippet_before)) {
175 $script .= $codesnippet_before;
176 }
177 $script .= 'pageTracker._trackPageview('. $url_custom .');';
178 if (!empty($codesnippet_after)) {
179 $script .= $codesnippet_after;
180 }
181 $script .= '} catch(err) {}';
182
183 drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
184 }
185 }
186
187 /**
188 * Implementation of hook_user().
189 *
190 * Allow users to decide if tracking code will be added to pages or not.
191 */
192 function googleanalytics_user_form(&$edit, &$account, $category = NULL) {
193 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
194 $form['googleanalytics'] = array(
195 '#type' => 'fieldset',
196 '#title' => t('Google Analytics configuration'),
197 '#weight' => 3,
198 '#collapsible' => TRUE,
199 '#tree' => TRUE
200 );
201
202 switch ($custom) {
203 case 1:
204 $description = t('Users are tracked by default, but you are able to opt out.');
205 break;
206
207 case 2:
208 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
209 break;
210 }
211
212 $form['googleanalytics']['custom'] = array(
213 '#type' => 'checkbox',
214 '#title' => t('Enable user tracking'),
215 '#description' => $description,
216 '#default_value' => isset($account->googleanalytics['custom']) ? $account->googleanalytics['custom'] : ($custom == 1)
217 );
218
219 return $form;
220 }
221 }
222
223 /**
224 * Implementation of hook_requirements().
225 */
226 function googleanalytics_requirements($phase) {
227 $requirements = array();
228
229 if ($phase == 'runtime') {
230 // Raise warning if Google user account has not been set yet.
231 if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
232 $requirements['googleanalytics'] = array(
233 'title' => t('Google Analytics module'),
234 'description' => t('Google Analytics module has not been configured yet. Please configure its settings from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/settings/googleanalytics'))),
235 'severity' => REQUIREMENT_ERROR,
236 'value' => t('Not configured'),
237 );
238 }
239 }
240
241 return $requirements;
242 }
243
244 /**
245 * Implementation of hook_cron().
246 */
247 function googleanalytics_cron() {
248 // Regenerate the google analytics ga.js every day.
249 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
250 // New google analytics version.
251 file_unmanaged_delete(file_directory_path() .'/googleanalytics/ga.js');
252
253 // Clear aggregated JS files.
254 if (variable_get('preprocess_js', 0)) {
255 drupal_clear_js_cache();
256 }
257
258 variable_set('googleanalytics_last_cache', time());
259 }
260 }
261
262 /**
263 * Download and cache the ga.js file locally.
264 * @param $location
265 * The full URL to the external javascript file.
266 * @return mixed
267 * The path to the local javascript file on success, boolean FALSE on failure.
268 */
269 function _googleanalytics_cache($location) {
270 $directory = file_directory_path() .'/googleanalytics';
271 $file_destination = $directory .'/'. basename($location);
272 if (!file_exists($file_destination)) {
273 $result = drupal_http_request($location);
274 if ($result->code == 200) {
275 // Check that the files directory is writable
276 if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
277 return file_unmanaged_save_data($result->data, $directory .'/'. basename($location), FILE_EXISTS_REPLACE);
278 }
279 }
280 }
281 else {
282 return $file_destination;
283 }
284 }
285
286 /**
287 * Tracking visibility check for an user object.
288 *
289 * @param $account
290 * A user object containing an array of roles to check.
291 * @return boolean
292 * A decision on if the current user is being tracked by Google Analytics.
293 */
294 function _googleanalytics_visibility_user($account) {
295
296 $enabled = FALSE;
297
298 // Is current user a member of a role that should be tracked?
299 if (_googleanalytics_visibility_roles($account)) {
300
301 // Use the user's block visibility setting, if necessary.
302 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
303 if ($account->uid && isset($account->googleanalytics['custom'])) {
304 $enabled = $account->googleanalytics['custom'];
305 }
306 else {
307 $enabled = ($custom == 1);
308 }
309 }
310 else {
311 $enabled = TRUE;
312 }
313
314 }
315
316 return $enabled;
317 }
318
319 /**
320 * Based on visibility setting this function returns TRUE if GA code should
321 * be added for the current role and otherwise FALSE.
322 */
323 function _googleanalytics_visibility_roles($account) {
324
325 $enabled = FALSE;
326 $roles = variable_get('googleanalytics_roles', array());
327
328 if (array_sum($roles) > 0) {
329 // One or more roles are selected for tracking.
330 foreach (array_keys($account->roles) as $rid) {
331 // Is the current user a member of one role enabled for tracking?
332 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
333 // Current user is a member of a role that should be tracked.
334 $enabled = TRUE;
335 break;
336 }
337 }
338 }
339 else {
340 // No role is selected for tracking, therefor all roles should be tracked.
341 $enabled = TRUE;
342 }
343
344 return $enabled;
345 }
346
347 /**
348 * Based on visibility setting this function returns TRUE if GA code should
349 * be added to the current page and otherwise FALSE.
350 */
351 function _googleanalytics_visibility_pages() {
352 static $page_match;
353
354 // Cache visibility setting in hook_init for hook_footer.
355 if (!isset($page_match)) {
356
357 $visibility = variable_get('googleanalytics_visibility', 0);
358 $pages = variable_get('googleanalytics_pages', '');
359
360 // Match path if necessary.
361 if (!empty($pages)) {
362 if ($visibility < 2) {
363 $path = drupal_get_path_alias($_GET['q']);
364 // Compare with the internal and path alias (if any).
365 $page_match = drupal_match_path($path, $pages);
366 if ($path != $_GET['q']) {
367 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
368 }
369 // When $visibility has a value of 0, the block is displayed on
370 // all pages except those listed in $pages. When set to 1, it
371 // is displayed only on those pages listed in $pages.
372 $page_match = !($visibility xor $page_match);
373 }
374 else {
375 $page_match = drupal_eval($pages);
376 }
377 }
378 else {
379 $page_match = TRUE;
380 }
381
382 }
383 return $page_match;
384 }