-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathding_webtrekk.module
537 lines (492 loc) · 19.1 KB
/
ding_webtrekk.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
537
<?php
/**
* @file
* Include basic hooks for the module functionality.
*/
// Constants for Webtrekk tracking parameters.
define('DING_WEBTREKK_PARAMETER_RESERVE', 50);
define('DING_WEBTREKK_PARAMETER_SEE_ONLINE', 51);
define('DING_WEBTREKK_PARAMETER_RENEW_ALL', 56);
define('DING_WEBTREKK_PARAMETER_CAMPAIGN_PLUS_TITLE', 62);
define('DING_WEBTREKK_PARAMETER_CAMPAIGN_PLUS_ID', 63);
/**
* Implements hook_menu().
*/
function ding_webtrekk_menu() {
$items = [];
$items['admin/config/ding/webtrekk'] = [
'title' => 'Webtrekk',
'description' => 'Settings for the Webtrekk analytics tool.',
'page callback' => 'drupal_get_form',
'page arguments' => ['ding_webtrekk_admin_settings_form'],
'access arguments' => ['administer site configuration'],
'file' => 'ding_webtrekk.admin.inc',
];
return $items;
}
/**
* Implements hook_page_alter().
*/
function ding_webtrekk_page_alter(&$page) {
global $user;
$domain = variable_get('webtrekk_ti_domain', '');
$id = variable_get('webtrekk_ti_id', '');
if (empty($domain) && empty($id)) {
return;
}
// @codingStandardsIgnoreStart
$tag_integration_logic = '/** start TagIntegration loader */
(function(c,d,a,f){c.wts=c.wts||[];var g=function(b){var a="";b.customDomain&&b.customPath?a=b.customDomain+"/"+b.customPath:b.tiDomain&&b.tiId&&(a=b.tiDomain+"/resp/api/get/"+b.tiId+"?url="+encodeURIComponent(c.location.href)+"&v=5");if(b.option)for(var d in b.option)a+="&"+d+"="+encodeURIComponent(b.option[d]);return a};if(-1===d.cookie.indexOf("wt_r=1")){var e=d.getElementsByTagName(a)[0];a=d.createElement(a);a.async=!0;a.onload=function(){if("undefined"!==typeof c.wt_r&&!isNaN(c.wt_r)){var b=new Date,a=b.getTime()+1E3*parseInt(c.wt_r);b.setTime(a);d.cookie="wt_r=1;path=/;expires="+b.toUTCString()}};a.onerror=function(){"undefined"!==typeof c.wt_mcp_hide&&"function"===typeof c.wt_mcp_hide.show&&(c.wt_mcp_hide.show(),c.wt_mcp_hide.show=function(){})};a.src="//"+g(f);e.parentNode.insertBefore(a,e)}})(window,document,"script",_tiConfig);
/** end TagIntegration loader */';
// @codingStandardsIgnoreEnd
$page['page_bottom']['webtrekk']['#attached']['js'] = [
[
'data' => 'window._tiConfig = window._tiConfig || {
tiDomain: ' . "'$domain'," .
'tiId: ' . "'$id'," .
'option: {}
};' . $tag_integration_logic,
'type' => 'inline',
// We want the webtrekk loader as high as possible in the HTML-head, as
// recommended in the implementation guidelines. We therefore use the
// JS_LIBRARY group and choose a weight lower than the weights in
// system_library().
// See: ding_webtrekk_preprocess_html().
// See: system_library().
'group' => JS_LIBRARY,
'weight' => -21,
],
];
// Here we collect and add the general page parameters that aren't dependant
// on data and timing from a specific hook implementation.
$params = [];
// Tracks whether the user is logged in and, if logged in, what login provider
// was used.
if (user_is_logged_in()) {
// Note that this separation of logged in users might be problematic if some
// pages are also cached for authenticated users.
if (module_exists('ding_gatewayf') && _ding_gatewayf_is_logged_in_with_gatewayf()) {
$params['p_isloggedin'] = 'NemId';
// This is the landing page for successful user registration with gatewayf.
// If the registration was successful, the users will be automatically
// logged in. So by also requiring a logged in user before setting parameter
// we reduce the chances of false positives. For example, it will prevent
// random access to the URL from anonymous users, from being tracked.
if (strpos(current_path(), DING_GATEWAYF_REGISTRATION_SUCCESS_URL) === 0) {
$params['p_usercreate'] = 'NemId';
}
}
// Fallback to cpr+pin if none the modules we know about was used to log in.
else {
$params['p_isloggedin'] = 'cpr+pinkode';
}
}
// Track ting search results. We take advantage of the fact that ting_search
// module stores the result in a static variable when search is triggered via
// search_data() function from core search module. Since this is not tied to
// any path, we also check current_path().
if (strpos(current_path(), 'search/ting') === 0) {
if ($search_result = drupal_static('ting_search_results')) {
$params += [
'OSS' => $search_result->search_key,
'OSSr' => $search_result->numTotalObjects,
];
// Track filters used in the search request. They are called facets, since
// for opensearch these will be search facet filters, selected by the user
// in the UI.
$filters = isset($_COOKIE['facets']) ? json_decode($_COOKIE['facets']) : array();
if (!empty($filters)) {
foreach ($filters as $key => $value) {
$val = explode(':', $value);
$indexes[$val[0]] = $val[1];
}
$params['p_s_Facets'] = implode(';', $indexes);
}
// Track the page of the search result.
$params['p_s_Page'] = pager_find_page();
// Track the size of the search result. We already track the total size
// of the search result in OSSr parameter, but this is the number of
// results on the current search page.
$params['p_s_Size'] = $search_result->numTotalCollections;
/** Needs work for OC
// Track the sort used in the search request.
if (!empty($search_result->sort)) {
$current_sort = $search_result->getSearchRequest()->getSorts()[0];
$params['p_s_Sort'] = ting_search_sort_key_from_sort($current_sort);
}
else {
$params['p_s_Sort'] = variable_get('ting_search_default_sort', 'rank');
// If search provider is opensearch we know how to get the actual
// ranking used. If not the value 'rank' will need to do.
if ($params['p_s_Sort'] === 'rank') {
if (ding_provider_get_provider_module_name('search') === 'opensearch') {
$params['p_s_Sort'] = variable_get('opensearch_sort_default', 'rank_frequency');
}
}
}
// Track the ting_field_search profile used in the request. Is the module
// enablet and is extended search with profiles activated?
if (module_exists('ting_field_search') && variable_get('ting_field_search_search_style', FALSE)) {
if ($profile = ting_field_search_get_active_profile()) {
$params['p_OSSprofile'] = $profile->name;
}
}
}
}
if (strpos(current_path(), 'user/password') === 0) {
$params = [];
}
if (!empty($params)) {
ding_webtrekk_add_page_parameters($params);
}
}
**/
}
}
if (strpos(current_path(), 'user/password') === 0) {
$params = [];
}
if (!empty($params)) {
ding_webtrekk_add_page_parameters($params);
}
}
/**
* Implements hook_views_post_execute().
*
* Track internal search results.
*/
function ding_webtrekk_views_post_execute(&$view) {
// We also check current_path to ensure we're tracking on the correct page.
// For example, the view is also executed on ting_search search page to show
// the number of results to the user, if they searched in content instead.
// See search_backend.inc ctools content type plugin from ting_search.
if (strpos(current_path(), 'search/node') === 0) {
// This view is loaded 2 times. Prevent from loading params multiple times.
$loaded = &drupal_static(__FUNCTION__);
if (!empty($loaded)) {
return;
}
$loaded = TRUE;
$params = [
'OSS' => array_shift($view->args),
'OSSr' => $view->total_rows,
];
// If using views pager; track the current search result page here also.
if (isset($view->query->pager->current_page)) {
$params['p_s_Page'] = ++$view->query->pager->current_page;
}
ding_webtrekk_add_page_parameters($params);
}
}
function ding_webtrekk_form_ding_reservation_reserve_form_alter(&$form, &$form_state, $form_id)
{
ding_webtrekk_attach_event(
$form['submit']['#attributes'],
'Reserver',
[DING_WEBTREKK_PARAMETER_RESERVE => $form['reservable']['#value']->entity->ding_entity_id]
);
}
/**
* Implements hook_ding_entity_view().
* OC specidifc moved to theme & form_ding_reservation_reserve_form_alter
function ding_webtrekk_ding_entity_view($entity, $view_mode) {
$entity_path = entity_uri('ting_object', $entity)['path'];
// The page parametes for the ting object view should only be added on the
// full page view for the material.
if ($view_mode == 'full' && current_path() == $entity_path) {
// TingObjectInterface doesn't allow us determine fiction/nonfiction in a
// clean way, but if the search provider is opensearch we can use a provider
// specific mehtod to get value.
$p_mat_ficnonfic = FALSE;
if (module_exists('opensearch')) {
$p_mat_ficnonfic = $entity->getTingObject()->isFiction() ? 'fiktion' : 'nonfiktion';
}
// Process array values so they are ready to be inserted in parameter.
$p_mat_audience = FALSE;
if (!empty($entity->getTingObject()->getAudience())) {
$p_mat_audience = $entity->getTingObject()->getAudience();
// Here we can only have one value so we need to pick the first element
// out of the array.
$p_mat_audience = reset($p_mat_audience);
}
$p_mat_category = FALSE;
if (!empty($entity->getTingObject()->getGenre())) {
// Here we can have multiple values so we implode the values to a comma
// separated list.
$p_mat_category = implode(', ', $entity->getTingObject()->getGenre());
}
$params = [
'p_mat_type' => $entity->getType(),
'p_mat_indexno' => $entity->getClassification(),
'p_mat_lang' => $entity->getLanguage(),
'p_mat_source' => $entity->getAc_source(),
'p_mat_ficnonfic' => $p_mat_ficnonfic,
'p_mat_category' => $p_mat_category,
'p_mat_audience' => $p_mat_audience,
];
ding_webtrekk_add_page_parameters($params);
}
// Look for at reserve button on this ding entity and setup a Webtrekk event
// if present. These could be added in every view_mode and page.
if (isset($entity->content['ding_entity_buttons'])) {
foreach (element_children($entity->content['ding_entity_buttons']) as $delta) {
foreach ($entity->content['ding_entity_buttons'][$delta] as $key => &$button) {
// Reserve button.
if (isset($button['#path']) && $button['#path'] == $entity_path . '/reserve') {
ding_webtrekk_attach_event(
$button['#options']['attributes'],
'Reserver',
[DING_WEBTREKK_PARAMETER_RESERVE => $entity->getId()]
);
}
// See online button.
elseif (isset($button['#attributes']) && in_array('button-see-online', $button['#attributes']['class'])) {
ding_webtrekk_attach_event(
$button['#attributes'],
'Se online',
[DING_WEBTREKK_PARAMETER_SEE_ONLINE => $entity->getId()]
);
}
}
}
}
}
*/
/**
* Implements hook_preprocess_node().
*/
function ding_webtrekk_preprocess_node(&$variables) {
$node = $variables['node'];
if ($node->type == 'ding_campaign_plus') {
// Create event that tracks when a campaign is viewed sending the title and
// internal ID.
$event_data = ding_webtrekk_create_event_data('Kampagne', [
DING_WEBTREKK_PARAMETER_CAMPAIGN_PLUS_TITLE => check_plain($node->title),
DING_WEBTREKK_PARAMETER_CAMPAIGN_PLUS_ID => $node->nid,
]);
// We can't use the catch-all event handler for this, since it relies on
// being triggered by a user interaction. Instead we send event when
// behaviours are attached in frontend.
$event_data = json_encode($event_data);
$variables['attributes_array']['data-ding-webtrekk-event'] = $event_data;
}
}
/**
* Implements hook_process_node().
*/
function ding_webtrekk_process_node(&$variables) {
$node = $variables['node'];
if ($node->type == 'ding_campaign_plus') {
// Add u_navigatedby_kp URL-parameter to campaign URLs, to be able to track
// page views triggered from campaigns. We use a process for this because
// campaign plus adds the variable in preprocess.
$url = drupal_parse_url($variables['campaign_url']);
$url['query']['u_navigatedby_kp'] = check_plain($node->title);
$variables['campaign_url'] = url($url['path'], [
'query' => $url['query'],
'fragment' => $url['fragment'],
]);
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function ding_webtrekk_form_search_block_form_alter(&$form, &$form_state) {
$form['#attributes']['class'][] = 'js-ding-webtrekk-autocomplete';
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Attached Webtrekk events to the renew loan buttons.
*/
function ding_webtrekk_form_ding_loan_loans_form_alter(&$form, &$form_state) {
// We'll only attach the renew events if there's loans that can be renewed.
// Ding loan form checks this and only sets this element if that's the case.
// OC fix
/*
if (!isset($form['actions_container']['select_all'])) {
return;
}
*/
// Ding loan stores the loans in the this form element and we take advantage
// of that to get the material ids for the renewable loans.
$loans = $form['items']['#value'];
$material_ids = [];
foreach ($loans as $loan) {
if ($loan->renewable) {
if (is_object($loan->entity)) {
$material_ids[$loan->id] = $loan->entity->getId();
}
// For inter library loans the material may not reachable in the well and
// therefore we can't get a well ID to display. We'll note that it's an
// ILL and use the title instead.
else {
$material_ids[$loan->id] = t('Interlibrary Loan: %title', array(
'%title' => $loan->display_name,
));
}
}
}
// The renew all button is straight forward. We can attach the event in
// backend and just pass all renewable ids to the event data attribute.
// OC fix
/*
ding_webtrekk_attach_event(
$form['actions_container']['actions_top']['renew_all']['#attributes'],
'Forny alle materialer',
[DING_WEBTREKK_PARAMETER_RENEW_ALL => implode(';', $material_ids)]
);
*/
// The renew selected button is more complicated, since we need data about
// which materials the user has selected in the UI.
$renew_selected = &$form['actions']['submit'] ;
$renew_selected['#attributes']['class'][] = 'js-ding-webtrekk-event-renew-selected';
// Oc fix
/*
$groups = _ding_loan_loans_group_loans_by_date($loans);
foreach ($groups as $gid => $group) {
foreach ($form['loans'][$gid] as $key => &$material_item) {
// Skip the title element.
if ($key === 'title') {
continue;
}
// For all other elements, the key will be a loan id and we pass it to the
// client if it's in our renewable list.
if (isset($material_ids[$key])) {
$material_item['#attributes']['data-ding-webtrekk-event'] = $material_ids[$key];
}
}
}
*/
}
/**
* Helper function to group loans by their due dates.
*/
function _ding_loan_loans_group_loans_by_date($loans) {
$groups = array();
$today = date('Y-m-d', REQUEST_TIME);
foreach ($loans as $loan) {
if ($loan->expiry < $today) {
// Loans that are overdue.
if (!isset($groups['overdue'])) {
$groups['overdue'] = array(
'title' => t('Loans overdue'),
'loans' => array(),
);
}
$groups['overdue']['loans'][$loan->id] = $loan;
}
elseif ($loan->expiry == $today) {
// Loans that should be handed in today.
if (!isset($groups['due'])) {
$groups['due'] = array(
'title' => t('Loans due today'),
'loans' => array(),
);
}
$groups['due']['loans'][$loan->id] = $loan;
}
else {
// Loans that are to be handed in in x days.
if (!isset($groups[$loan->expiry])) {
$time = strtotime($loan->expiry);
$due_in = t('Due in @count, @date', array(
'@count' => format_interval($time - strtotime("-1 Day"), 2),
'@date' => date('d/m/y', $time),
));
$groups[$loan->expiry] = array(
'title' => $due_in,
'loans' => array(),
);
}
$groups[$loan->expiry]['loans'][$loan->id] = $loan;
}
}
return $groups;
}
/**
* Use this function to attach webtrekk events to an elements attribute array.
*
* @param array $attributes
* Attributes array of the element that needs event attached.
* @param string $link_id
* The link ID of the event. For example 'Forny alle materialer'.
* @param array $data
* The parameter values for the event keyed by the Webtrekk parameter ID.
*/
function ding_webtrekk_attach_event(&$attributes, $link_id, $data) {
$event_data = [
'linkId' => $link_id,
'customClickParameter' => $data,
];
$attributes['class'][] = 'js-ding-webtrekk-event';
$attributes['data-ding-webtrekk-event'] = json_encode($event_data);
}
/**
* Adds Webtrekk page parameters to the current page.
*
* @see ding_webtrekk_preprocess_html()
*/
function ding_webtrekk_add_page_parameters(array $parameters = NULL) {
$stored_parameters = &drupal_static(__FUNCTION__, array());
if (isset($parameters)) {
$stored_parameters = array_merge($stored_parameters, $parameters);
}
return $stored_parameters;
}
/**
* Returns all the Webtrekk page parameters collected during the request.
*
* @see ding_webtrekk_preprocess_html()
*/
function ding_webtrekk_get_page_parameters() {
$parameters = ding_webtrekk_add_page_parameters();
// Give other modules a last chance to alter the webtrekk page parameters
// before they are added to the current page load.
drupal_alter('ding_webtrekk_page_parameters', $parameters);
return $parameters;
}
/**
* Implements hook_process_html().
*
* If any Webtrekk page parameters was stored during the request, we'll apply
* them here. We use this hook since it's run late in the request.
*/
function ding_webtrekk_preprocess_html() {
$parameters = ding_webtrekk_get_page_parameters();
$script_lines = array_map(function($key, $value) {
// We require a non-empty value but would also like to track values such as
// 0 and '0'. For example if there was 0 search results.
if (!empty($value) || (string) $value === '0') {
return "window._ti['$key'] = '$value'";
}
}, array_keys($parameters), $parameters);
// Remove empty values.
$script_lines = array_filter($script_lines);
$script_lines = array_merge(
['window._ti = window._ti || {}'],
$script_lines
);
$script = implode(";\n", $script_lines);
drupal_add_js($script, [
'type' => 'inline',
// Use the JS_LIBRARY group to add script at the top of head. Use -22 weight
// to ensure it's added above the Webtrekk loader which has -21.
// See: ding_webtrekk_page_alter()
'group' => JS_LIBRARY,
'weight' => -22,
]);
// Add script that tracks Webtrekk events in client and adds URL parameters
// to elements which is problematic to handle on the server.
drupal_add_js(drupal_get_path('module', 'ding_webtrekk') . '/ding_webtrekk.js', array(
'scope' => 'footer',
// Ensure we have a higher weight that EU cookie compliance script, since
// we use the hasAgreed() function from it.
'weight' => 1,
));
drupal_add_js([
'dingWebtrekk' => [
'debugMode' => variable_get('webtrekk_debug', FALSE),
],
], 'setting');
}