forked from discoverygarden/google_analytics_reports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GAFeed.lib.inc
407 lines (347 loc) · 12.2 KB
/
GAFeed.lib.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
/**
* @file
* Provides the GAFeed object type and associated methods.
*/
/**
* GAFeed class to authorize access to and request data from
* the Google Analytics Data Export API.
*/
class GAFeed {
/* Response object */
public $response;
/* Formatted array of request results */
public $results;
/* URL to Google Analytics Data Export API */
public $queryPath;
/* Translated error message */
public $error;
/* Boolean TRUE if data is from the cache tables */
public $fromCache = FALSE;
/* Host and endpoint of Google Analytics API */
protected $host = 'www.googleapis.com/analytics/v3';
/* Request header source */
protected $source = 'drupal';
/* Default is HMAC-SHA1 */
protected $signatureMethod;
/* HMAC-SHA1 Consumer data */
protected $consumer;
/* OAuth token */
protected $token;
/* Google authorize callback verifier string */
protected $verifier;
/* OAuth host */
protected $oAuthHost = 'www.google.com';
/**
* Check if object is authenticated with Google.
*/
public function isAuthenticated() {
return !empty($this->token);
}
/**
* Constructor for the GAFeed class
*/
public function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
/* Allow developers the option of OAuth authentication without using this class's methods */
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
}
}
/**
* Set the verifier property
*/
public function setVerifier($verifier) {
$this->verifier = $verifier;
}
/**
* Set the host property
*/
public function setHost($host) {
$this->host = $host;
}
/**
* Set the queryPath property
*/
protected function setQueryPath($path) {
$this->queryPath = 'https://'. $this->host .'/'. $path;
}
/**
* OAuth step #1: Fetch request token.
*/
public function getRequestToken() {
$this->setHost($this->oAuthHost);
$this->setQueryPath('accounts/OAuthGetRequestToken');
/* xoauth_displayname is displayed on the Google Authentication page */
$params = array(
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'oauth_callback' => url('google-analytics-reports/oauth', array('absolute' => TRUE)),
'xoauth_displayname' => t('Google Analytics Reports Drupal module'),
);
$this->query($this->queryPath, $params, 'GET', array('refresh' => TRUE));
parse_str($this->response->data, $token);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
/**
* OAuth step #2: Authorize request token.
*/
public function obtainAuthorization($token) {
$this->setHost($this->oAuthHost);
$this->setQueryPath('accounts/OAuthAuthorizeToken');
/* hd is the best way of dealing with users with multiple domains verified with Google */
$params = array(
'oauth_token' => $token['oauth_token'],
'hd' => variable_get('google_analytics_reports_hd', 'default'),
);
// Check for the overlay.
if (module_exists('overlay') && overlay_get_mode() == 'child') {
overlay_close_dialog($this->queryPath, array('query' => $params, 'external' => TRUE));
overlay_deliver_empty_page();
}
else {
drupal_goto($this->queryPath, array('query' => $params));
}
}
/**
* OAuth step #3: Fetch access token.
*/
public function getAccessToken() {
$this->setHost($this->oAuthHost);
$this->setQueryPath('accounts/OAuthGetAccessToken');
$params = array(
'oauth_verifier' => $this->verifier,
);
$this->query($this->queryPath, $params, 'GET', array('refresh' => TRUE));
parse_str($this->response->data, $token);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
/**
* Revoke OAuth token.
*/
public function revokeToken() {
$this->setHost($this->oAuthHost);
$this->setQueryPath('accounts/AuthSubRevokeToken');
$this->query($this->queryPath, array(), 'GET', array('refresh' => TRUE));
}
/**
* Public query method for all Data Export API features.
*/
public function query($path, $params = array(), $method = 'GET', $cache_options = array()) {
$params_defaults = array(
'start-index' => 1,
'max-results' => 1000,
);
$params += $params_defaults;
/* Provide cache defaults if a developer did not override them */
$cache_defaults = array(
'cid' => NULL,
'expire' => google_analytics_reports_cache_time(),
'refresh' => FALSE,
);
$cache_options += $cache_defaults;
/* Provide a query MD5 for the cid if the developer did not provide one */
if (empty($cache_options['cid'])) {
$cache_options['cid'] = 'GAFeed:' . md5(serialize(array_merge($params, array($path, $method))));
}
$cache = cache_get($cache_options['cid']);
if (!$cache_options['refresh'] && isset($cache) && !empty($cache->data)) {
$this->response = $cache->data;
$this->results = json_decode($this->response->data);
$this->fromCache = TRUE;
}
else {
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $this->queryPath, $params);
$request->sign_request($this->signatureMethod, $this->consumer, $this->token);
switch ($method) {
case 'GET':
$this->request($request->to_url());
break;
case 'POST':
$this->request($request->get_normalized_http_url(), $request->get_parameters(), 'POST');
break;
}
/* Do not cache erroneous queries */
if (empty($this->error)) {
cache_set($cache_options['cid'], $this->response, 'cache', $cache_options['expire']);
}
}
return (empty($this->error));
}
/**
* Execute a query
*/
protected function request($url, $params = array(), $method = 'GET') {
$data = '';
if (count($params) > 0) {
if ($method == 'GET') {
$url .= '?'. http_build_query($params, '', '&');
}
else {
$data = http_build_query($params, '', '&');
}
}
$headers = array();
$this->response = drupal_http_request($url, $headers, $method, $data);
if ($this->response->code == '200') {
$this->results = json_decode($this->response->data);
}
else {
// data is undefined if the connection failed.
if (!isset($this->response->data)) {
$this->response->data = '';
}
$error_msg = 'Code: !code - Error: !message - Message: !details';
$error_vars = array('!code' => $this->response->code, '!message' => $this->response->error, '!details' => strip_tags($this->response->data));
$this->error = t($error_msg, $error_vars);
watchdog('google analytics reports', $error_msg, $error_vars, WATCHDOG_ERROR);
}
}
/**
* Query Management API - Accounts
*/
public function queryAccounts($params = array(), $cache_options = array()) {
$this->setQueryPath('management/accounts');
$this->query($this->queryPath, $params, 'GET', $cache_options);
return $this;
}
/**
* Query Management API - WebProperties
*/
public function queryWebProperties($params = array(), $cache_options = array()) {
$params += array(
'account-id' => '~all',
);
$this->setQueryPath('management/accounts/' . $params['account-id'] . '/webproperties');
$this->query($this->queryPath, $params, 'GET', $cache_options);
return $this;
}
/**
* Query Management API - Profiles
*/
public function queryProfiles($params = array(), $cache_options = array()) {
$params += array(
'account-id' => '~all',
'web-property-id' => '~all',
);
$this->setQueryPath('management/accounts/' . $params['account-id'] . '/webproperties/' . $params['web-property-id'] . '/profiles');
$this->query($this->queryPath, $params, 'GET', $cache_options);
return $this;
}
/**
* Query Management API - Segments
*/
public function querySegments($params = array(), $cache_options = array()) {
$this->setQueryPath('management/segments');
$this->query($this->queryPath, $params, 'GET', $cache_options);
return $this;
}
/**
* Query Management API - Goals
*/
public function queryGoals($params = array(), $cache_options = array()) {
$params += array(
'account-id' => '~all',
'web-property-id' => '~all',
'profile-id' => '~all',
);
$this->setQueryPath('management/accounts/' . $params['account-id'] . '/webproperties/' . $params['web-property-id'] . '/profiles/' . $params['profile-id'] . '/goals');
$this->query($this->queryPath, $params, 'GET', $cache_options);
return $this;
}
/**
* Query and sanitize report data
*/
public function queryReportFeed($params = array(), $cache_options = array()) {
/* Provide defaults if the developer did not override them */
$params += array(
'profile_id' => 0,
'dimensions' => NULL,
'metrics' => 'ga:visits',
'sort_metric' => NULL,
'filters' => NULL,
'segment' => NULL,
'start_date' => NULL,
'end_date' => NULL,
'start_index' => 1,
'max_results' => 10000,
);
$parameters = array('ids' => $params['profile_id']);
if (is_array($params['dimensions'])) {
$parameters['dimensions'] = implode(',', $params['dimensions']);
}
elseif ($params['dimensions'] !== NULL) {
$parameters['dimensions'] = $params['dimensions'];
}
if (is_array($params['metrics'])) {
$parameters['metrics'] = implode(',', $params['metrics']);
}
else {
$parameters['metrics'] = $params['metrics'];
}
if ($params['sort_metric'] == NULL && isset($parameters['metrics'])) {
$parameters['sort'] = $parameters['metrics'];
}
elseif (is_array($params['sort_metric'])) {
$parameters['sort'] = implode(',', $params['sort_metric']);
}
else {
$parameters['sort'] = $params['sort_metric'];
}
if (empty($params['start_date']) || !is_int($params['start_date'])) {
/* Use the day that Google Analytics was released (1 Jan 2005) */
$start_date = '2005-01-01';
}
elseif (is_int($params['start_date'])) {
/* Assume a Unix timestamp */
$start_date = date('Y-m-d', $params['start_date']);
}
$parameters['start-date'] = $start_date;
if (empty($params['end_date']) || !is_int($params['end_date'])) {
$end_date = date('Y-m-d');
}
elseif (is_int($params['end_date'])) {
/* Assume a Unix timestamp */
$end_date = date('Y-m-d', $params['end_date']);
}
$parameters['end-date'] = $end_date;
/* Accept only strings, not arrays, for the following parameters */
if (!empty($params['filters'])) $parameters['filters'] = $params['filters'];
if (!empty($params['segment'])) $parameters['segment'] = $params['segment'];
$parameters['start-index'] = $params['start_index'];
$parameters['max-results'] = $params['max_results'];
$this->setQueryPath('data/ga');
if ($this->query($this->queryPath, $parameters, 'GET', $cache_options)) {
$this->sanitizeReport();
}
return $this;
}
/**
* Sanitize report data
*/
protected function sanitizeReport() {
if(!$this->results->totalResults){
$this->results->rawRows = array();
}
else {
/* Named keys for report values */
$this->results->rawRows = $this->results->rows;
}
$this->results->rows = array();
foreach ($this->results->rawRows as $row_key => $row_value) {
foreach ($row_value as $item_key => $item_value) {
$this->results->rows[$row_key][str_replace('ga:', '', $this->results->columnHeaders[$item_key]->name)] = $item_value;
}
}
unset($this->results->rawRows);
/* Named keys for report totals */
$this->results->rawTotals = $this->results->totalsForAllResults;
$this->results->totalsForAllResults = array();
foreach ($this->results->rawTotals as $row_key => $row_value) {
$this->results->totalsForAllResults[str_replace('ga:', '', $row_key)] = $row_value;
}
unset($this->results->rawTotals);
}
}