#188835: reported bjaspan, patch by bjaspan and hass, Local cache is broken
[project/google_analytics.git] / googleanalytics.module
CommitLineData
8369f34c 1<?php
2// $Id$
117c4d98 3
8369f34c 4/*
5 * Drupal Module: GoogleAnalytics
6 * Adds the required Javascript to the bottom of all your Drupal pages
7 * to allow tracking by the Google Analytics statistics package.
8 *
9 * @author: Mike Carter <www.ixis.co.uk/contact>
10 */
11
12define('GA_TRACKFILES', 'pdf|zip|mp3');
13
14function googleanalytics_help($path, $arg) {
15 switch ($path) {
16 case 'admin/settings/googleanalytics':
17 return t('Google Analytics is a free statistics package based on the excellent Urchin system.');
18 }
19}
20
21function googleanalytics_menu() {
22
23 $items['admin/settings/googleanalytics'] = array(
24 'title' => 'Google Analytics',
25 'description' => 'Configure the settings used to generate your Google Analytics site map.',
26 'page callback' => 'drupal_get_form',
27 'page arguments' => array('googleanalytics_admin_settings'),
28 'access arguments' => array('administer site configuration'),
29 'file' => 'googleanalytics.admin.inc',
30 'type' => MENU_NORMAL_ITEM,
31 );
32
33 return $items;
34}
35
8369f34c 36/**
37 * Implementation of hook_footer() to insert Javascript at the end of the page
38 */
39function googleanalytics_footer($main = 0) {
40 global $user;
41
42 $id = variable_get('googleanalytics_account', '');
43
44 // Check if we should track the currently active user's role
117c4d98 45 $track = _googleanalytics_track($user);
8369f34c 46
47 // Don't track page views in the admin sections
48 if ($id && (arg(0) != 'admin') && $track == TRUE) {
49
50 $prefix = '://www';
51
52 // Are we on a secure page?
53 if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) {
54 $prefix = 's://ssl';
55 }
56
117c4d98 57 // Use the old version of Google Analytics?
58 $legacy_version = variable_get('googleanalytics_legacy_version', TRUE);
59
8369f34c 60 // Add User profile segmentation values
61 if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {
62
63 $p = module_invoke('profile', 'load_profile', $user);
64
65 $fields = array();
66 foreach ($profile_fields as $field => $title) {
67 $value = $user->$field;
68
69 if (is_array($value)) {
70 $value = implode(',', $value);
71 }
72
73 $fields[$field] = utf8_encode(addslashes($value));
74 }
75
76 // Only show segmentation variable if there are specified fields
77 $segmentation = '';
78 if (count($fields) > 0) {
117c4d98 79 if ($legacy_version) {
80 $segmentation = "__utmSetVar('". implode(':', $fields) ."');";
81 }
82 else {
83 $segmentation = "pageTracker._setVar('". implode(':', $fields) ."');";
84 }
8369f34c 85 }
86 }
87
88 // Download tracking
89 $path = drupal_get_path('module', 'googleanalytics');
90 if ($trackfiles = variable_get('googleanalytics_trackfiles', GA_TRACKFILES)) {
91 drupal_add_js(array('googleanalytics' => array('trackDownload' => $trackfiles)), 'setting', 'header');
92 drupal_add_js($path .'/downloadtracker.js', 'module', 'footer');
93 }
117c4d98 94
8369f34c 95 // Add any custom code snippets if specified
96 $codesnippet = variable_get('googleanalytics_codesnippet', '');
117c4d98 97
98 // Should a local cached copy of urchin.js or ga.js be used?
8369f34c 99 if (variable_get('googleanalytics_cache', 0) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC)) {
117c4d98 100 if ($legacy_version) {
101 $source = _googleanalytics_cache('http://www.google-analytics.com/urchin.js');
102 }
103 else {
104 $source = _googleanalytics_cache('http://www.google-analytics.com/ga.js');
105 }
106 if (!empty($source)) {
8369f34c 107 $source = base_path() . $source;
108 }
109 }
110 if (!isset($source)) {
117c4d98 111 if ($legacy_version) {
112 $source = 'http'. $prefix .'.google-analytics.com/urchin.js';
113 }
114 else {
115 $source = 'http'. $prefix .'.google-analytics.com/ga.js';
116 }
8369f34c 117 }
118
117c4d98 119 // Should the legacy code be used?
120 if ($legacy_version) {
121 $script = '<script type="text/javascript" src="'. $source ."\"></script>\n";
122 $script .= '<script type="text/javascript">';
c69ed8ef 123 $script .= '_uacct = "'. $id .'";';
124 if (!empty($segmentation)) {
125 $script .= '{'. $segmentation .'}';
126 }
127 if (!empty($codesnippet)) {
128 $script .= '{'. $codesnippet .'}';
129 }
130 $script .= 'urchinTracker();';
131 $script .= "</script>\n";
117c4d98 132 }
133 else {
134 $script = '<script type="text/javascript">';
c69ed8ef 135 $script .= 'document.write(unescape("%3Cscript src=\''. $source .'\' type=\'text/javascript\'%3E%3C/script%3E"));';
136 $script .= "</script>\n";
117c4d98 137 $script .= '<script type="text/javascript">';
c69ed8ef 138 $script .= 'var pageTracker = _gat._getTracker("'. $id .'");';
139 $script .= 'pageTracker._initData();';
d4ebf275 140 if (!empty($segmentation)) {
141 $script .= $segmentation;
142 }
c69ed8ef 143 $script .= $codesnippet;
144 $script .= 'pageTracker._trackPageview();';
145 $script .= "</script>\n";
117c4d98 146 }
8369f34c 147
148 return $script;
149 }
150}
151
152/**
153 * Implementation of hook_requirements().
154 */
155function googleanalytics_requirements($phase) {
156 $requirements = array();
157
158 if ($phase == 'runtime') {
159 // Raise warning if Google user account has not been set yet.
160 if (variable_get('googleanalytics_account', 'UA-') == 'UA-') {
161 $requirements['googleanalytics'] = array(
162 'title' => t('Google Analytics module'),
163 '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'))),
164 'severity' => REQUIREMENT_ERROR,
165 'value' => t('Not configured'),
166 );
167 }
168 }
169
170 return $requirements;
171}
172
173/**
174 * Implementation of hook_cron().
175 */
176function googleanalytics_cron() {
69b3ea65 177 // Regenerate the google analytics urchin.js or ga.js every day.
178 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
117c4d98 179 // Legacy google analytics version.
8369f34c 180 file_delete(file_directory_path() .'/googleanalytics/urchin.js');
117c4d98 181
182 // New google analytics version.
183 file_delete(file_directory_path() .'/googleanalytics/ga.js');
69b3ea65 184 variable_set('googleanalytics_last_cache', time());
8369f34c 185 }
186}
187
188/**
189 * Download and cache the urchin.js file locally.
190 * @param $location
191 * The full URL to the external javascript file.
192 * @return mixed
193 * The path to the local javascript file on success, boolean FALSE on failure.
194 */
08c61b83 195function _googleanalytics_cache($location = 'http://www.google-analytics.com/urchin.js') {
8369f34c 196 $directory = file_directory_path() .'/googleanalytics';
197 $file_destination = $directory .'/'. basename($location);
198 if (!file_exists($file_destination)) {
199 $result = drupal_http_request($location);
200 if ($result->code == 200) {
201 // Check that the files directory is writable
202 if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
203 return file_save_data($result->data, $directory .'/'. basename($location), FILE_EXISTS_REPLACE);
204 }
205 }
206 }
207 else {
208 return $file_destination;
209 }
210}
117c4d98 211
212/**
213 *
214 * @param $account
215 * A user object containing an array of roles to check
216 * @return boolean
217 * A decision on if the current user is being tracked by GAnalytics
218 */
219function _googleanalytics_track($account) {
220 $track = TRUE;
221
222 foreach (array_keys($account->roles) as $role) {
223 if (!variable_get('googleanalytics_track_'. $role, FALSE)) {
224 $track = FALSE;
225 }
226 }
227
228 if ($account->uid == 1 && !variable_get('googleanalytics_track__user1', FALSE)) {
229 $track = FALSE;
230 }
231
232 return $track;
233}