Fixed typos in file functions taken over from modules upgrade page
[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|avi|csv|doc|exe|flv|gif|gz|jpe?g|js|mp(3|4|e?g)|mov|pdf|phps|png|ppt|rar|sit|tar|torrent|txt|wma|wmv|xls|xml|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 }
94
95 /**
96 * Implementation of hook_footer() to insert Javascript at the end of the page.
97 */
98 function googleanalytics_footer($main = 0) {
99 global $user;
100
101 $id = variable_get('googleanalytics_account', '');
102
103 if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
104
105 // Add User profile segmentation values.
106 if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {
107
108 $p = module_invoke('profile', 'load_profile', $user);
109
110 $fields = array();
111 foreach ($profile_fields as $field => $title) {
112 $value = $user->$field;
113
114 if (is_array($value)) {
115 $value = implode(',', $value);
116 }
117
118 $fields[$field] = $value;
119 }
120
121 // Only show segmentation variable if there are specified fields.
122 $segmentation = '';
123 if (count($fields) > 0) {
124 $segmentation = 'pageTracker._setVar('. drupal_to_js(implode(':', $fields)) .');';
125 }
126 }
127
128 // Site search tracking support.
129 $url_custom = '';
130 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
131 $url_custom = drupal_to_js(url('search/'. arg(1), array('query' => 'search='. $keys)));
132 }
133
134 // If this node is a translation of another node, pass the original
135 // node instead.
136 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
137 // Check we have a node object, it supports translation, and its
138 // translated node ID (tnid) doesn't match its own node ID.
139 $node = menu_get_object();
140 if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
141 $source_node = node_load($node->tnid);
142 $languages = language_list();
143 $url_custom = drupal_to_js(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language])));
144 }
145 }
146
147 // Track access denied (403) and file not found (404) pages.
148 if (function_exists('drupal_get_headers')) {
149 $headers = drupal_get_headers();
150 if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
151 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
152 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
153 }
154 elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
155 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
156 }
157 }
158
159 // Add any custom code snippets if specified.
160 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
161 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
162
163 // Build tracker code for footer.
164 $script = 'var pageTracker = _gat._getTracker('. drupal_to_js($id) .');';
165 if (!empty($segmentation)) {
166 $script .= $segmentation;
167 }
168 if (!empty($codesnippet_before)) {
169 $script .= $codesnippet_before;
170 }
171 $script .= 'pageTracker._trackPageview('. $url_custom .');';
172 if (!empty($codesnippet_after)) {
173 $script .= $codesnippet_after;
174 }
175
176 drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
177 }
178 }
179
180 /**
181 * Implementation of hook_user().
182 *
183 * Allow users to decide if tracking code will be added to pages or not.
184 */
185 function googleanalytics_user_form(&$edit, &$account, $category = NULL) {
186 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
187 $form['googleanalytics'] = array(
188 '#type' => 'fieldset',
189 '#title' => t('Google Analytics configuration'),
190 '#weight' => 3,
191 '#collapsible' => TRUE,
192 '#tree' => TRUE
193 );
194 $form['googleanalytics']['custom'] = array(
195 '#type' => 'checkbox',
196 '#title' => t('User tracking'),
197 '#default_value' => isset($account->googleanalytics['custom']) ? $account->googleanalytics['custom'] : ($custom == 1)
198 );
199
200 return $form;
201 }
202 }
203
204 /**
205 * Implementation of hook_requirements().
206 */
207 function googleanalytics_requirements($phase) {
208 $requirements = array();
209
210 if ($phase == 'runtime') {
211 // Raise warning if Google user account has not been set yet.
212 if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
213 $requirements['googleanalytics'] = array(
214 'title' => t('Google Analytics module'),
215 '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'))),
216 'severity' => REQUIREMENT_ERROR,
217 'value' => t('Not configured'),
218 );
219 }
220 }
221
222 return $requirements;
223 }
224
225 /**
226 * Implementation of hook_cron().
227 */
228 function googleanalytics_cron() {
229 // Regenerate the google analytics ga.js every day.
230 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
231 // New google analytics version.
232 file_unmanaged_delete(file_directory_path() .'/googleanalytics/ga.js');
233
234 // Clear aggregated JS files.
235 if (variable_get('preprocess_js', 0)) {
236 drupal_clear_js_cache();
237 }
238
239 variable_set('googleanalytics_last_cache', time());
240 }
241 }
242
243 /**
244 * Download and cache the ga.js file locally.
245 * @param $location
246 * The full URL to the external javascript file.
247 * @return mixed
248 * The path to the local javascript file on success, boolean FALSE on failure.
249 */
250 function _googleanalytics_cache($location) {
251 $directory = file_directory_path() .'/googleanalytics';
252 $file_destination = $directory .'/'. basename($location);
253 if (!file_exists($file_destination)) {
254 $result = drupal_http_request($location);
255 if ($result->code == 200) {
256 // Check that the files directory is writable
257 if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
258 return file_unmanaged_save_data($result->data, $directory .'/'. basename($location), FILE_EXISTS_REPLACE);
259 }
260 }
261 }
262 else {
263 return $file_destination;
264 }
265 }
266
267 /**
268 * Tracking visibility check for an user object.
269 *
270 * @param $account
271 * A user object containing an array of roles to check.
272 * @return boolean
273 * A decision on if the current user is being tracked by Google Analytics.
274 */
275 function _googleanalytics_visibility_user($account) {
276
277 $enabled = FALSE;
278
279 // Is current user a member of a role that should be tracked?
280 if (_googleanalytics_visibility_roles($account)) {
281
282 // Use the user's block visibility setting, if necessary.
283 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
284 if ($account->uid && isset($account->googleanalytics['custom'])) {
285 $enabled = $account->googleanalytics['custom'];
286 }
287 else {
288 $enabled = ($custom == 1);
289 }
290 }
291 else {
292 $enabled = TRUE;
293 }
294
295 }
296
297 return $enabled;
298 }
299
300 /**
301 * Based on visibility setting this function returns TRUE if GA code should
302 * be added for the current role and otherwise FALSE.
303 */
304 function _googleanalytics_visibility_roles($account) {
305
306 $enabled = FALSE;
307 $roles = variable_get('googleanalytics_roles', array());
308
309 if (array_sum($roles) > 0) {
310 // One or more roles are selected for tracking.
311 foreach (array_keys($account->roles) as $rid) {
312 // Is the current user a member of one role enabled for tracking?
313 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
314 // Current user is a member of a role that should be tracked.
315 $enabled = TRUE;
316 break;
317 }
318 }
319 }
320 else {
321 // No role is selected for tracking, therefor all roles should be tracked.
322 $enabled = TRUE;
323 }
324
325 return $enabled;
326 }
327
328 /**
329 * Based on visibility setting this function returns TRUE if GA code should
330 * be added to the current page and otherwise FALSE.
331 */
332 function _googleanalytics_visibility_pages() {
333 static $page_match;
334
335 // Cache visibility setting in hook_init for hook_footer.
336 if (!isset($page_match)) {
337
338 $visibility = variable_get('googleanalytics_visibility', 0);
339 $pages = variable_get('googleanalytics_pages', '');
340
341 // Match path if necessary.
342 if (!empty($pages)) {
343 if ($visibility < 2) {
344 $path = drupal_get_path_alias($_GET['q']);
345 // Compare with the internal and path alias (if any).
346 $page_match = drupal_match_path($path, $pages);
347 if ($path != $_GET['q']) {
348 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
349 }
350 // When $visibility has a value of 0, the block is displayed on
351 // all pages except those listed in $pages. When set to 1, it
352 // is displayed only on those pages listed in $pages.
353 $page_match = !($visibility xor $page_match);
354 }
355 else {
356 $page_match = drupal_eval($pages);
357 }
358 }
359 else {
360 $page_match = TRUE;
361 }
362
363 }
364 return $page_match;
365 }