-
Notifications
You must be signed in to change notification settings - Fork 3
/
islandora_piwik.module
536 lines (512 loc) · 22.3 KB
/
islandora_piwik.module
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
<?php
/**
* @file
* The main Piwik module file.
*/
/**
* Implements hook_menu().
*/
function islandora_piwik_menu() {
$items = array();
$items['admin/islandora/tools/piwik'] = array(
'title' => 'Islandora Piwik',
'description' => 'Configure Islandora Piwik.',
'page callback' => 'drupal_get_form',
'page arguments' => array('islandora_piwik_admin_settings'),
'access arguments' => array('administer site configuration'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/reports/islandora_piwik_reports'] = array(
'title' => 'Islandora Piwik Reports',
'description' => 'Makes Piwik reports available to authorized users.',
'page callback' => 'islandora_piwik_reports',
'access arguments' => array('view islandora piwik reports'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Implements hook_permission().
*/
function islandora_piwik_permission() {
return array(
'view islandora piwik reports' => array(
'title' => t('View Islandora Piwik reports'),
'description' => t('View reports managed by the Islandora Piwik module'),
),
);
}
/**
* Admin settings form builder.
*/
function islandora_piwik_admin_settings() {
$form['islandora_piwik_endpoint'] = array(
'#title' => t("Piwik API endpoint"),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_piwik_endpoint', 'http://piwik.example.com/piwik.php'),
'#description' => t("Your Piwik instance's API endpoint"),
'#maxlength' => 255,
);
$form['islandora_piwik_site_id'] = array(
'#title' => t('Site ID'),
'#type' => 'textfield',
'#size' => 5,
'#default_value' => variable_get('islandora_piwik_site_id', '1'),
'#description' => t("The Piwik site ID."),
'#maxlength' => 5,
);
$form['islandora_piwik_collection_site_ids'] = array(
'#title' => t('Collection-specific site IDs'),
'#type' => 'textarea',
'#size' => 5,
'#default_value' => variable_get('islandora_piwik_collection_site_ids', ''),
'#description' => t("Piwik site IDs for specific collections, one entry per
row. Each row should be in PID, site ID format
(e.g., \"islandora:mycollection, 5\"). Multiple collections can be
associated with the same site ID."),
);
$form['islandora_piwik_use_javascript'] = array(
'#type' => 'checkbox',
'#title' => t('Use Inline Javascript to track'),
'#default_value' => variable_get('islandora_piwik_use_javascript', 1),
'#description' => t("Check this option if you want to track sites using inline Javascript instead of PIWIK PHP httpd call.
If checked, this will automatically add inline PIWIK tracking Javascript to each drupal and Islandora page, needed
if you run a front end caching mechanism like Varnish or if you want to avoid the httpd call to PIWIK blocks or delays your page load
"),
);
$form['islandora_piwik_timeout'] = array(
'#title' => t('Timeout'),
'#type' => 'textfield',
'#size' => 5,
'#default_value' => variable_get('islandora_piwik_timeout', '2'),
'#description' => t("Number of seconds to use as the timeout for requests to
the Piwki endpoint."),
'#maxlength' => 5,
);
$form['islandora_piwik_track_collection_usage'] = array(
'#type' => 'checkbox',
'#title' => t('Track collection usage'),
'#default_value' => variable_get('islandora_piwik_track_collection_usage', 1),
'#description' => t("Check this option if you want to track collection usage
in addtion to object usage. If enabled, each object's parent collections
are counted every time the object is viewed, and usage reports will be
available under \"Visitors > Custom Variables\" in your Piwik server.
High-traffic or large sites may want to disable this option to improve
performance."),
);
$form['islandora_piwik_api_key'] = array(
'#title' => t("Piwik API key"),
'#type' => 'textfield',
'#size' => 40,
'#default_value' => variable_get('islandora_piwik_api_key', ''),
'#description' => t("Your Piwik 's API key (a.k.a. token_auth). Required if you want to view reports generated by Piwik. It it available under your account on the Piwik server, in the API menu."),
'#maxlength' => 40,
);
$form['islandora_piwik_javascript_tracking_code'] = array(
'#title' => t('Piwik JavaScript tracking code'),
'#type' => 'textarea',
'#size' => 5,
'#default_value' => variable_get('islandora_piwik_javascript_tracking_code', ''),
'#description' => t("If you want to use Piwik to provide analytics for your entire
Islandora site, enter the \"JavaScript Tracking Code\" generated by Piwik here.
Note that if you update any of the options provided by Piwik, you will need to
update this JavaScript code. Islandora objects are not counted twice."),
);
return system_settings_form($form);
}
/**
* Implements hook_islandora_view_object().
*/
function islandora_piwik_islandora_view_object($object) {
if (!variable_get('islandora_piwik_use_javascript', 0)) {
$timeout = (int) variable_get('islandora_piwik_timeout', '2');
$endpoint = variable_get('islandora_piwik_endpoint', 'http://piwik.example.com/piwik.php');
$site_id = islandora_piwik_get_site_id($object);
// Record usage of the object.
global $base_url;
$current_path = $base_url . '/' . current_path();
$query = '?apiv=1&rec=1';
$query .= '&idsite=' . $site_id;
$query .= '&url=' . $current_path;
// We urldecode() the referrer because URLS produced by Islandora
// are usually encoded.
$query .= '&urlref=' . urlencode(urldecode($_SERVER['HTTP_REFERER']));
$uri = $endpoint . $query;
try {
$return = drupal_http_request($uri, array('timeout' => $timeout));
}
catch (Exception $e) {
watchdog('islandora_piwik', "Error connecting to Piwik server at %ep:
%message", array("%ep" => $endpoint, "%message" => $e->getMessage()),
WATCHDOG_ERROR);
}
// Record usage of the object's collection(s).
if (variable_get('islandora_piwik_track_collection_usage', 1)) {
$collections = islandora_piwik_get_ancestor_collections($object);
foreach ($collections as $collection) {
// We don't want to count usage of the islandora:root collection.
if ($collections != 'islandora:root') {
$query = '?apiv=1&rec=1';
$query .= '&idsite=' . $site_id;
// Create the JSON object that holds the custom Piwik variable that
// tracks the collection PID. We do not include the collection URL
// in our request to the Piwik API since doing so would double-count
// usage of the collection.
$cvar_object = new stdClass();
$cvar_object->{1} = array('collection_pid', $collection);
$query .= '&cvar=' . urlencode(json_encode($cvar_object));
$uri = $endpoint . $query;
try {
$return = drupal_http_request($uri, array('timeout' => $timeout));
}
catch (Exception $e) {
watchdog('islandora_piwik', "Error connecting to Piwik server at %ep:
%message", array("%ep" => $endpoint, "%message" => $e->getMessage()),
WATCHDOG_ERROR);
}
}
}
}
}
return array();
}
/**
* Implements hook_islandora_solr_query_result().
*/
function islandora_piwik_islandora_solr_query_result($result) {
if (!variable_get('islandora_piwik_use_javascript', 0)) {
$timeout = (int) variable_get('islandora_piwik_timeout', '2');
$endpoint = variable_get('islandora_piwik_endpoint', 'http://piwik.example.com/piwik.php');
$site_id = variable_get('islandora_piwik_site_id', '1');
global $base_url;
$current_path = $base_url . '/' . current_path();
$query = '?apiv=1&rec=1';
$query .= '&idsite=' . $site_id;
$search_words = $result['responseHeader']['params']['q'];
$search_words = urlencode($search_words);
$query .= '&search=' . $search_words;
if ($result['response']['numFound'] === 0) {
$query .= '&search_count=0';
}
$query .= '&url=' . $current_path;
$uri = $endpoint . $query;
try {
$return = drupal_http_request($uri, array('timeout' => $timeout));
}
catch (Exception $e) {
watchdog('islandora_piwik', "Error connecting to Piwik server at %ep:
%message", array("%ep" => $endpoint, "%message" => $e->getMessage()),
WATCHDOG_ERROR);
}
}
}
/**
* Returns the PIDs of all collections that the Islandora object belongs to.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return array $collection_pids
* A list of PIDS.
*/
function islandora_piwik_get_ancestor_collections($islandora_object) {
$collection_pids = array();
// islandora:is_member_of_collection property.
if ($islandora_object) {
$collections = $islandora_object->relationships->get(FEDORA_RELS_EXT_URI,
'isMemberOfCollection');
// The root collection PID will be a member of 0 collections, so we need
// to check for it.
if (count($collections) > 0) {
foreach ($collections as $collection) {
$collection_pids[] = $collection['object']['value'];
}
}
else {
// If the object is a book page or a newspaper issue, query the RI
// to get its ancestor collection.
$object_cmodel_pids = $islandora_object->models;
$pid = $islandora_object->id;
if ($object_cmodel_pids[0] == 'islandora:newspaperIssueCModel'
|| $object_cmodel_pids[0] == 'islandora:pageCModel') {
$query = <<<EOQ
select ?collection from <#ri> where {
# Get the collection that book pages and newspaper issues belong to.
<info:fedora/$pid> <fedora-rels-ext:isMemberOf> ?parent .
?parent <fedora-rels-ext:isMemberOfCollection> ?collection .
}
EOQ;
$connection = islandora_get_tuque_connection();
$results = $connection->repository->ri->sparqlQuery($query, 1);
if (count($results)) {
$collection_pids[] = $results[0]['collection']['value'];
}
}
// If the object is a newspaper page, query the RI to get the
// its ancestor collection.
if ($object_cmodel_pids[0] == 'islandora:newspaperPageCModel') {
$query = <<<EOQ
select ?collection from <#ri> where {
# Get the collection that newspaper pages belong to.
<info:fedora/$pid> <fedora-rels-ext:isMemberOf> ?issue .
?issue <fedora-rels-ext:isMemberOf> ?newspaper .
?newspaper <fedora-rels-ext:isMemberOfCollection> ?collection .
}
EOQ;
$connection = islandora_get_tuque_connection();
$results = $connection->repository->ri->sparqlQuery($query, 1);
if (count($results)) {
$collection_pids[] = $results[0]['collection']['value'];
}
}
}
return $collection_pids;
}
}
/**
* Returns the PIDs via solr of all collections an Islandora object belongs to.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return array $collection_pids
* A list of PIDS.
*/
function islandora_piwik_get_ancestorviasolr_collections($islandora_object) {
module_load_include('inc', 'islandora_solr', 'query_processor');
$collection_pids = array();
// islandora:is_member_of_collection property.
if ($islandora_object) {
global $user;
$query_processor = new IslandoraSolrQueryProcessor();
$query = '*:*';
$query_processor->buildQuery($query);
// Todo make this solr field configurable.
$query_processor->solrParams['fl'] = 'PID, ancestors_ms';
$query_processor->solrParams['fq'][] = 'PID:' . "\"{$islandora_object->id}\"";
try {
$query_processor->executeQuery(FALSE);
$solr_results = $query_processor->islandoraSolrResult['response'];
if ($solr_results['numFound'] == 1) {
if (isset($solr_results['objects'][0]['solr_doc']['ancestors_ms'])) {
$collection_pids = (array) $solr_results['objects'][0]['solr_doc']['ancestors_ms'];
}
}
}
catch (Exception $e) {
watchdog(t('Islandora PIWIK fetch Solr ancestors Error', nl2br(check_plain($e->getMessage()))), NULL, WATCHDOG_WARNING);
}
}
return $collection_pids;
}
/**
* Returns the Piwik site ID to use for the current object using.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return string $site_id
* The site ID to use.
*/
function islandora_piwik_get_site_id($islandora_object) {
$general_site_id = variable_get('islandora_piwik_site_id', '1');
$collection_site_ids_setting = variable_get('islandora_piwik_collection_site_ids', '');
// If there are no collection-specific site IDs, use the general one.
if (!strlen($collection_site_ids_setting)) {
return $general_site_id;
}
else {
$collection_ids = array();
$entries = array_filter(preg_split('/\r\n|[\r\n]/', $collection_site_ids_setting));
foreach ($entries as &$entry) {
list($pid, $site_id) = explode(',', $entry);
$pid = trim($pid);
$collection_ids[$pid] = trim($site_id);
}
}
// If the object is a collection object, its PID might be in the
// list of collection-specific site IDs. Test this first since
// doing so is less expensive then the following operation.
if (array_key_exists($islandora_object->id, $collection_ids)) {
return $collection_ids[$islandora_object->id];
}
else {
return $general_site_id;
}
}
/**
* Returns the Piwik site ID to use for the current object using.
*
* @param string $pid
* The Islandora object PID being inspected.
*
* @return array $site_ids
* The PIWIK IDs to use for this PID.
*/
function islandora_piwik_get_site_ids_bypid($pid) {
$general_site_id = variable_get('islandora_piwik_site_id', '1');
$collection_site_ids_setting = variable_get('islandora_piwik_collection_site_ids', '');
// If there are no collection-specific site IDs, use the general one.
if (!strlen(trim($collection_site_ids_setting))) {
return array($general_site_id);
}
else {
$collection_ids = array();
$entries = array_filter(preg_split('/\r\n|[\r\n]/', $collection_site_ids_setting));
foreach ($entries as $entry) {
list($pid2, $site_id) = explode(',', $entry);
if ($pid == trim($pid2)) {
$collection_ids[] = trim($site_id);
}
}
}
// If the object is a collection object, its PID might be in the
// list of collection-specific site IDs. Test this first since
// doing so is less expensive then the following operation.
if (count($collection_ids) > 0) {
//Add also the default one to keep general track
$collection_ids[] = $general_site_id;
//In case of duplicates, remove
$collection_ids = array_unique($collection_ids);
return $collection_ids;
}
else {
return array($general_site_id);
}
}
/**
* Implements hook_page_alter().
*/
function islandora_piwik_page_alter(&$page) {
module_load_include('inc', 'islandora', 'includes/utilities');
global $_islandora_solr_queryclass;
$endpoint = variable_get('islandora_piwik_endpoint', 'http://piwik.example.com/piwik.php');
$general_site_id = $siteId = variable_get('islandora_piwik_site_id', '1');
$script = 'var _paq = _paq || [];';
$siteIds = array();
$script2 = '';
$inOtherIds = false;
// Asume this will be true for all Solr Search pages.
if (!empty($_islandora_solr_queryclass)) {
// Searching in a particular collection?
// Cp? Could be anything since it is user provided data.
if (isset($_islandora_solr_queryclass->internalSolrParams['cp']) && islandora_is_valid_pid($_islandora_solr_queryclass->internalSolrParams['cp'])) {
$object = islandora_object_load($_islandora_solr_queryclass->internalSolrParams['cp']);
$collectionsearch = $_islandora_solr_queryclass->internalSolrParams['cp'];
$siteIds = is_object($object) ? islandora_piwik_get_site_ids_bypid($object->id) : array($general_site_id);
}
// Check if we are using facets.
$keywordlist = isset($_islandora_solr_queryclass->internalSolrParams['f']) ? (array) $_islandora_solr_queryclass->internalSolrParams['f'] : array();
array_unshift($keywordlist, $_islandora_solr_queryclass->solrQuery);
if (isset($collectionsearch)) {
array_unshift($keywordlist, $collectionsearch);
}
$searchtype = isset($_islandora_solr_queryclass->internalSolrParams['type']) ? $_islandora_solr_queryclass->internalSolrParams['type'] : 'advanced';
if ($searchtype == 'edismax' || $searchtype == 'dismax') {
$searchtype = "simple";
}
$keywords = urlencode(stripslashes(implode(' ', $keywordlist)));
$script .= "_paq.push(['trackSiteSearch',
\"{$keywords}\",
\"{$searchtype}\",
{$_islandora_solr_queryclass->islandoraSolrResult['response']['numFound']}
]);";
foreach($siteIds as $siteId) {
if ($siteId != $general_site_id) {
$inOtherIds = true;
$script2 .= "var piwikTracker{$siteId} = Piwik.getTracker('{$endpoint}', {$siteId});";
$script2 .= "piwikTracker{$siteId}.trackSiteSearch(\"{$keywords}\",
\"{$searchtype}\",
{$_islandora_solr_queryclass->islandoraSolrResult['response']['numFound']});";
}
}
if ($inOtherIds) {
$script .= 'window.piwikAsyncInit = function () { try {';
$script .= $script2;
$script .= '} catch( err ) {console.log(err);}};';
}
drupal_add_js($script,
array(
'type' => 'inline',
'scope' => 'header',
'weight' => 50,
)
);
}
else {
if ((arg(0) == 'islandora') && (arg(1) == 'object')) {
$object = menu_get_object('islandora_object', 2);
if ($object) {
$collections = array();
$idtocollectionmapping = array();
// Record usage of the object's collection(s).
// Check first if the visited object is a collection,
// because it may not be in the list of ancestors
if (in_array('islandora:collectionCModel', $object->models)) {
$collections[]=$object->id;
}
if (variable_get('islandora_piwik_track_collection_usage', 1)) {
$collections += islandora_piwik_get_ancestorviasolr_collections($object);
foreach ($collections as $collection) {
// We don't want to count usage of the islandora:root collection.
if (($collection != 'islandora:root') && ($collection != 'islandora:featured_collection')) {
$siteIds2 = islandora_piwik_get_site_ids_bypid($collection);
foreach ($siteIds2 as $siteId2) {
$idtocollectionmapping[$siteId2][] = $collection;
}
}
}
$script .= 'window.piwikAsyncInit = function () { try {';
foreach($idtocollectionmapping as $siteId => $collectionpids) {
$script .= "var piwikTracker{$siteId} = Piwik.getTracker('{$endpoint}', {$siteId});";
$collectionpid_unique = array_unique($collectionpids);
$script .= "piwikTracker{$siteId}.setCustomDimension(2, '{$object->id}');";
foreach($collectionpid_unique as $collectionpid) {
$collectionpidURL = urlencode($collectionpid);
$script .= "piwikTracker{$siteId}.setCustomDimension(1, '{$collectionpidURL}');";
}
$script .= "piwikTracker{$siteId}.trackPageView();";
}
$script .= '} catch( err ) {console.log(err);}}';
}
drupal_add_js($script,
array(
'type' => 'inline',
'scope' => 'header',
'weight' => 50,
)
);
}
}
}
if (arg(0) != 'islandora' && arg(1) != 'object' && isset($page['footer'])) {
$tracking_code = variable_get('islandora_piwik_javascript_tracking_code', '');
$page['footer']['islandora_piwik']['#markup'] = $tracking_code;
}
}
/**
* Page callback that dumbly renders Piwik widget iframe markup.
*/
function islandora_piwik_reports() {
$endpoint = variable_get('islandora_piwik_endpoint', 'http://piwik.example.com/piwik.php');
$index_page = preg_replace('/piwik\.php/', 'index.php', $endpoint);
$general_site_id = variable_get('islandora_piwik_site_id', '1');
$token_auth = variable_get('islandora_piwik_api_key', '');
$markup = <<<MARKUP
<div>Using data collected today.</div>
<h3>Real-time map</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=UserCountryMap&actionToWidgetize=realtimeMap&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
<h3>Visitor map</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=UserCountryMap&actionToWidgetize=visitorMap&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
<h3>Site pages</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=Actions&actionToWidgetize=getPageUrls&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
<h3>Islandora collection usage</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=CustomDimensions&actionToWidgetize=getCustomDimension&idDimension=1&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
<h3>Searches</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=Actions&actionToWidgetize=getSiteSearchKeywords&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
<h3>Searches returning no results</h3>
<div id="widgetIframe"><iframe width="100%" height="350" src="$index_page?module=Widgetize&action=iframe&widget=1&moduleToWidgetize=Actions&actionToWidgetize=getSiteSearchNoResultKeywords&idSite=$general_site_id&period=day&date=today&disableLink=1&widget=1&token_auth=$token_auth" scrolling="yes" frameborder="0" marginheight="0" marginwidth="0"></iframe></div>
MARKUP;
return $markup;
}