-
Notifications
You must be signed in to change notification settings - Fork 2
/
islandora_matomo.module
997 lines (941 loc) · 33.7 KB
/
islandora_matomo.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
<?php
/**
* @file
* The main Piwik module file.
*/
define(
'ISLANDORA_MATOMO_ISLANDORA_PERSON_REPORT_VIEW_PERMISSION',
'view islandora matomo person report'
);
define(
'ISLANDORA_MATOMO_ISLANDORA_ORGANIZATION_REPORT_VIEW_PERMISSION',
'view islandora matomo organization report'
);
define(
'ISLANDORA_MATOMO_ISLANDORA_OBJECT_REPORT_VIEW_PERMISSION',
'view islandora matomo reports'
);
define(
'ISLANDORA_MATOMO_ISLANDORA_OBJECT_USAGE_VIEW_PERMISSION',
'view islandora matomo usage'
);
define(
'ISLANDORA_MATOMO_ISLANDORA_OBJECT_COUNT_VIEW_PERMISSION',
'view islandora matomo count report'
);
/**
* Implements hook_menu().
*/
function islandora_matomo_menu() {
$items = [];
$items['admin/islandora/tools/matomo'] = [
'title' => 'Islandora Matomo',
'description' => 'Configure Islandora Matomo.',
'page callback' => 'drupal_get_form',
'page arguments' => ['islandora_matomo_admin_settings'],
'access arguments' => ['administer site configuration'],
'file' => 'includes/config.inc',
'type' => MENU_NORMAL_ITEM,
];
$items['admin/reports/islandora_matomo_reports'] = [
'title' => 'Islandora Matomo Reports',
'description' => 'Makes Matomo reports available to authorized users.',
'page callback' => 'drupal_get_form',
'file' => 'includes/reports.form.inc',
'page arguments' => ['islandora_matomo_report_form'],
'access arguments' => [ISLANDORA_MATOMO_ISLANDORA_OBJECT_REPORT_VIEW_PERMISSION],
'type' => MENU_NORMAL_ITEM,
];
$items['islandora/object/%islandora_object/readership'] = [
'title' => 'Readership Dashboard',
'type' => MENU_LOCAL_TASK,
'page callback' => 'drupal_get_form',
'file' => 'includes/reports.form.inc',
'page arguments' => ['islandora_matomo_readershipreport_form', 2],
'access callback' => 'islandora_matomo_readership_access_callback',
'access arguments' => [2],
];
$items['islandora/object/%islandora_object/matomo_usage'] = [
'title' => 'Usage Statistics',
'type' => MENU_LOCAL_TASK,
'page callback' => 'islandora_matomo_page_empty',
'page arguments' => [2],
'access callback' => 'islandora_matomo_usage_access_callback',
'access arguments' => [2],
];
return $items;
}
/**
* Access callback for Usage reports.
*/
function islandora_matomo_usage_access_callback(AbstractObject $object) {
return islandora_object_access(
ISLANDORA_VIEW_OBJECTS,
$object
) && !array_intersect($object->models, ['islandora:personCModel']) &&
user_access(ISLANDORA_MATOMO_ISLANDORA_OBJECT_USAGE_VIEW_PERMISSION);
}
/**
* Access callback limiting to profile Objects and enabled permissions.
*/
function islandora_matomo_readership_access_callback(AbstractObject $object) {
return islandora_object_access(
ISLANDORA_VIEW_OBJECTS,
$object
) && array_intersect($object->models, ['islandora:personCModel']) &&
(user_access(
ISLANDORA_MATOMO_ISLANDORA_PERSON_REPORT_VIEW_PERMISSION
) || user_access(
ISLANDORA_MATOMO_ISLANDORA_OBJECT_REPORT_VIEW_PERMISSION
));
}
/**
* Implements hook_form_alter().
*/
function islandora_matomo_form_alter(&$form, $form_state, $form_id) {
if ($form_id == "user_profile_form") {
// Hides the timestamp tracking field from input.
$form['field_islandoramatomo_lastreport']['#access'] = 0;
}
}
/**
* Implements hook_permission().
*/
function islandora_matomo_permission() {
return [
ISLANDORA_MATOMO_ISLANDORA_OBJECT_REPORT_VIEW_PERMISSION => [
'title' => t('View Islandora Matomo reports'),
'description' => t('View reports managed by the Islandora Matomo module'),
],
ISLANDORA_MATOMO_ISLANDORA_ORGANIZATION_REPORT_VIEW_PERMISSION => [
'title' => t('View Islandora Matomo by Organization reports'),
'description' => t('View reports managed by the Islandora Matomo module'),
],
ISLANDORA_MATOMO_ISLANDORA_PERSON_REPORT_VIEW_PERMISSION => [
'title' => t('View Islandora Matomo by Person reports'),
'description' => t('View reports managed by the Islandora Matomo module'),
],
ISLANDORA_MATOMO_ISLANDORA_OBJECT_USAGE_VIEW_PERMISSION => [
'title' => t('View Islandora Usage Stats on each Object'),
'description' => t(
'View usage stats widgets managed by the Islandora Matomo module'
),
],
ISLANDORA_MATOMO_ISLANDORA_OBJECT_COUNT_VIEW_PERMISSION => [
'title' => t('View Islandora View Count on each Object'),
'description' => t(
'View Object Visit/download Block managed by the Islandora Matomo module'
),
],
];
}
/**
* Empty Page callback's returnin an empty content.
*
* @return string
* Just an Empty.
*/
function islandora_matomo_page_empty() {
// Return at least an empty. People will have to setup blocks here.
// @see \islandora_matomo_block_info
return ' ';
}
/**
* Returns the PIDs of all collections that the Islandora object belongs to.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return array
* A list of PIDS.
*/
function islandora_matomo_get_ancestor_collections($islandora_object) {
$collection_pids = [];
// 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
* A list of PIDS.
*/
function islandora_matomo_get_ancestorviasolr_collections($islandora_object) {
module_load_include('inc', 'islandora_solr', 'query_processor');
$collection_pids = [];
// 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 Matomo fetch Solr ancestors Error',
nl2br(check_plain($e->getMessage()))
),
NULL,
WATCHDOG_WARNING
);
}
}
return $collection_pids;
}
/**
* Returns the Authors and Department for an Islandora Object.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return array
* An associative array in the form of:
* $dimensions['authors'] = array()
* $dimensions['departments'] = array()
*/
function islandora_matomo_get_dimensionsviasolr($islandora_object) {
module_load_include('inc', 'islandora_solr', 'query_processor');
$dimensions = [];
// 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.
$author_field = variable_get(
'islandora_matomo_author_solrfield',
'mods_identifier_u1_ms'
);
$department_field = variable_get(
'islandora_matomo_department_solrfield',
'mods_identifier_u2_ms'
);
$query_processor->solrParams['fl'] = "PID, {$author_field}, {$department_field}";
$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'][$author_field])) {
$dimensions['authors'] = (array) $solr_results['objects'][0]['solr_doc'][$author_field];
}
if (isset($solr_results['objects'][0]['solr_doc'][$department_field])) {
$dimensions['departments'] = (array) $solr_results['objects'][0]['solr_doc'][$department_field];
}
}
}
catch (Exception $e) {
watchdog(
t(
'Islandora Matomo fetch Solr Authors and Departments Error',
nl2br(check_plain($e->getMessage()))
),
NULL,
WATCHDOG_WARNING
);
}
}
return $dimensions;
}
/**
* Returns the Matomo site ID to use for the current object using.
*
* @param object $islandora_object
* The Islandora object being inspected.
*
* @return string
* The site ID to use.
*/
function islandora_matomo_get_site_id($islandora_object) {
$general_site_id = variable_get('islandora_matomo_site_id', '1');
$collection_site_ids_setting = variable_get(
'islandora_matomo_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 = [];
$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 Matomo site ID to use for the current object using.
*
* @param string $pid
* The Islandora object PID being inspected.
*
* @return array
* The PIWIK IDs to use for this PID.
*/
function islandora_matomo_get_site_ids_bypid($pid) {
$general_site_id = variable_get('islandora_matomo_site_id', '1');
$collection_site_ids_setting = variable_get(
'islandora_matomo_collection_site_ids',
''
);
// If there are no collection-specific site IDs, use the general one.
if (!strlen(trim($collection_site_ids_setting))) {
return [$general_site_id];
}
else {
$collection_ids = [];
$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 [$general_site_id];
}
}
/**
* Implements hook_page_alter().
*/
function islandora_matomo_page_alter(&$page) {
module_load_include('inc', 'islandora', 'includes/utilities');
global $_islandora_solr_queryclass;
$matomo_url = rtrim(
variable_get('islandora_matomo_url', 'http://matomo.example.com'),
'/'
) . '/';
$endpoint = $matomo_url . 'matomo.php';
$general_site_id = $siteId = variable_get('islandora_matomo_site_id', '1');
$script = "var _paq = window._paq || [];";
// Enables link tracking.
$script .= "_paq.push(['alwaysUseSendBeacon']);";
$script .= "_paq.push(['enableLinkTracking']);";
$script .= "(function() {
var u='{$matomo_url}';
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', {$general_site_id}]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();";
$siteIds = [];
$script2 = '';
$script3 = '';
$inOtherIds = FALSE;
// Assume 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_matomo_get_site_ids_bypid(
$object->id
) : [$general_site_id];
}
// Check if we are using facets.
$keywordlist = isset($_islandora_solr_queryclass->internalSolrParams['f']) ? (array) $_islandora_solr_queryclass->internalSolrParams['f'] : [];
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,
[
'type' => 'inline',
'scope' => 'header',
'weight' => 50,
]
);
}
else {
// Refactor to allow path alias.
$path = current_path();
$path_args = explode('/', $path);
if (isset($path_args[0]) && $path_args[0] == 'islandora' && isset($path_args[1]) && $path_args[1] == 'object') {
$object = menu_get_object('islandora_object', 2);
if ($object) {
$collections = [];
$idtocollectionmapping = [];
// 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;
}
$script3 .= 'window.piwikAsyncInit = function () { try {';
if (variable_get('islandora_matomo_track_collection_usage', 1)) {
$collections += islandora_matomo_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_matomo_get_site_ids_bypid($collection);
foreach ($siteIds2 as $siteId2) {
$idtocollectionmapping[$siteId2][] = $collection;
}
}
}
foreach ($idtocollectionmapping as $siteId => $collectionpids) {
$script3 .= "var piwikTracker{$siteId} = Piwik.getTracker('{$endpoint}', {$siteId});";
$collectionpid_unique = array_unique($collectionpids);
// Tracks Dimension per Object ID.
$script3 .= "piwikTracker{$siteId}.setCustomDimension(2, '{$object->id}');";
foreach ($collectionpid_unique as $collectionpid) {
$collectionpidURL = urlencode($collectionpid);
// Tracks Dimension per Collection Membership ID.
$script3 .= "piwikTracker{$siteId}.setCustomDimension(1, '{$collectionpidURL}');";
}
$script3 .= "piwikTracker{$siteId}.trackPageView();";
$script3 .= "console.log('tracking site {$siteId}');";
}
}
// Track Author and Department Dimensions.
$extradimensions = [];
$extradimensions += islandora_matomo_get_dimensionsviasolr($object);
$siteIdForExtraDimension = variable_get(
'islandora_matomo_moredimensions_site_id',
'2'
);
$script3 .= "var piwikTracker{$siteIdForExtraDimension} = Piwik.getTracker('{$endpoint}', {$siteIdForExtraDimension});";
$script3 .= "piwikTracker{$siteIdForExtraDimension}.enableLinkTracking();";
if (isset($extradimensions['authors']) && !empty($extradimensions['authors'])) {
foreach ($extradimensions['authors'] as $author) {
$script2 .= "_paq.push(['trackEvent','Readership', 'Author', '{$author}']);";
$script3 .= "piwikTracker{$siteIdForExtraDimension}.setCustomDimension(3, '{$author}');";
$script3 .= "piwikTracker{$siteIdForExtraDimension}.trackPageView();";
$script3 .= "console.log('tracking author {$author}');";
}
}
if (isset($extradimensions['departments']) && !empty($extradimensions['departments'])) {
// Get rid of dimension 3 when starting tracking Dimension 4.
$script3 .= "piwikTracker{$siteIdForExtraDimension}.deleteCustomDimension(3);";
foreach ($extradimensions['departments'] as $department) {
$script3 .= "console.log('tracking department {$department}');";
$script3 .= "piwikTracker{$siteIdForExtraDimension}.setCustomDimension(4, '{$department}');";
$script3 .= "piwikTracker{$siteIdForExtraDimension}.trackPageView();";
}
}
$script3 .= '} catch( err ) {console.log(err);}}';
$script .= $script2 . $script3;
drupal_add_js(
$script,
[
'type' => 'inline',
'scope' => 'header',
'weight' => 50,
]
);
}
}
}
if (arg(0) != 'islandora' && arg(1) != 'object' && isset($page['footer'])) {
$tracking_code = variable_get(
'islandora_matomo_javascript_tracking_code',
''
);
$page['footer']['islandora_matomo']['#markup'] = $tracking_code;
}
}
/**
* Implements hook_theme().
*/
function islandora_matomo_theme($existing, $type, $theme, $path) {
return [
'islandora_matomo_widget' => [
'file' => 'theme/theme.inc',
'template' => 'theme/islandora-matomo-widget',
'pattern' => 'islandora-matomo-widget__',
'variables' => [
'pid' => NULL,
],
],
'islandora_matomo_count' => [
'file' => 'theme/theme.inc',
'template' => 'theme/islandora-matomo-count',
'pattern' => 'islandora-matomo-count__',
'variables' => [
'pid' => NULL,
],
],
];
}
/**
* Implements hook_block_info().
*/
function islandora_matomo_block_info() {
$blocks['matomo_object_widget'] = [
'info' => t('Islandora Matomo Real time visitors widget'),
'visibility' => BLOCK_VISIBILITY_LISTED,
'pages' => 'islandora/object/*/readership/*',
'cache' => DRUPAL_NO_CACHE,
];
$blocks['matomo_object_visitscount'] = [
'info' => t('Islandora Matomo Visits Counts and Downloads Block'),
'visibility' => BLOCK_VISIBILITY_LISTED,
'pages' => 'islandora/object/*',
'cache' => DRUPAL_NO_CACHE,
];
return $blocks;
}
/**
* Implements hook_block_view().
*/
function islandora_matomo_block_view($delta = '') {
$block = [];
switch ($delta) {
case 'matomo_object_widget':
$object = menu_get_object('islandora_object', 2);
if ($object) {
if (islandora_matomo_show_for_cmodel($object)) {
module_load_include('inc', 'islandora_matomo', 'includes/blocks');
$block['subject'] = NULL;
$block['content'] = islandora_matomo_widgetonobject_block($object);
}
}
break;
case 'matomo_object_visitscount':
if (user_access(ISLANDORA_MATOMO_ISLANDORA_OBJECT_COUNT_VIEW_PERMISSION)){
$object = menu_get_object('islandora_object', 2);
if ($object) {
if (islandora_matomo_showcount_for_cmodel($object)) {
module_load_include('inc', 'islandora_matomo', 'includes/blocks');
$block['subject'] = NULL;
$block['content'] = islandora_matomo_countonobject_block($object);
}
}
}
default:
}
return $block;
}
/**
* Implements hook_block_configure().
*/
function islandora_matomo_block_configure($delta = '') {
$form = [];
switch ($delta) {
case 'matomo_object_widget':
module_load_include('inc', 'islandora', 'includes/utilities');
$options = islandora_get_content_models();
$selected = variable_get(
'islandora_matomo_report_enabled_content_models',
['ir:citationCModel', 'ir:thesisCModel']
);
foreach ($selected as $cmodel) {
if (isset($options[$cmodel])) {
$options = [$cmodel => $options[$cmodel]] + $options;
}
}
foreach ($options as $key => $value) {
$rows[$key] = [
'pid' => $key,
'title' => $value['label'],
];
in_array(
$key,
$selected
) ? $defaults[$key] = TRUE : $defaults[$key] = FALSE;
}
$header = [
'pid' => ['data' => t('PID')],
'title' => ['data' => t('Content Model')],
];
$form['intro'] = [
'#type' => 'item',
'#title' => 'Select allowed Islandora Content Models.',
'#description' => t(
'Objects defined by selected Content Models will show this block. The block "Pages" configuration can limit this option further.'
),
];
$form['the_table'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#default_value' => $defaults,
];
break;
case 'matomo_object_visitscount':
module_load_include('inc', 'islandora', 'includes/utilities');
$options = islandora_get_content_models();
$selected = variable_get(
'islandora_matomo_count_enabled_content_models',
['ir:citationCModel', 'ir:thesisCModel']
);
foreach ($selected as $cmodel) {
if (isset($options[$cmodel])) {
$options = [$cmodel => $options[$cmodel]] + $options;
}
}
foreach ($options as $key => $value) {
$rows[$key] = [
'pid' => $key,
'title' => $value['label'],
];
in_array(
$key,
$selected
) ? $defaults[$key] = TRUE : $defaults[$key] = FALSE;
}
$header = [
'pid' => ['data' => t('PID')],
'title' => ['data' => t('Content Model')],
];
$form['intro'] = [
'#type' => 'item',
'#title' => 'Select allowed Islandora Content Models.',
'#description' => t(
'Objects defined by selected Content Models will show this block. The block "Pages" configuration can limit this option further.'
),
];
$form['the_table'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#default_value' => $defaults,
];
break;
}
return $form;
}
/**
* Implements hook_block_save().
*/
function islandora_matomo_block_save($delta = '', $edit = []) {
switch ($delta) {
case 'matomo_object_widget':
$enabled = array_filter($edit['the_table']);
variable_set('islandora_matomo_report_enabled_content_models', $enabled);
break;
case 'matomo_object_visitscount':
$enabled = array_filter($edit['the_table']);
variable_set('islandora_matomo_count_enabled_content_models', $enabled);
break;
}
}
/**
* Implements hook_islandora_datastream_filename_alter().
*
* We don't use this to alter the filename but to track file downloads
* Since this is the only hook invoked in islandora_datastream_view.
*
* @param string $filename
* The filename being created.
* @param AbstractDatastream $datastream
* The datastream object being downloaded.
*/
function islandora_matomo_islandora_datastream_filename_alter(&$filename, AbstractDatastream $datastream) {
global $base_url;
// We use the internal URL for this
$matomo_url = rtrim(
variable_get('islandora_matomo_internal_url', 'http://matomo.example.com'),
'/'
) . '/';
$endpoint = $matomo_url . 'matomo.php';
$pid = $datastream->parent->id;
$general_site_id = $siteId = variable_get('islandora_matomo_site_id', '1');
$timeout = (int) variable_get('islandora_matomo_timeout', '2');
// We track here the real, not aliased datastream path.
$current_path = $base_url . '/' . current_path();
$query = '?apiv=1&rec=1';
$query .= '&idsite=' . $general_site_id;
$query .= '&rand='.uniqid();
$query .= '&action_name=datastream_download';
$query .= '&url=' . $current_path;
$query .= '&download=' . $current_path;
$query .= '&dimension2=' . $pid;
$uri = $endpoint . $query;
try {
$return = drupal_http_request($uri, array('timeout' => $timeout));
}
catch (Exception $e) {
watchdog('islandora_matomo', "Error connecting to Matomo server to track datastream download for file %fn belonging to Object with PID %pid: %message", array(
"%fn" => $filename, "%pid" => $pid, "%message" => $e->getMessage()),
WATCHDOG_ERROR);
}
}
/**
* Determine if the object has allowed CMODEL Object.
*
* @param \AbstractObject $object
* The object we are viewing.
*
* @return bool
* Whether $object has a content model to show widgets for.
*/
function islandora_matomo_show_for_cmodel(AbstractObject $object) {
$show_cmodels = variable_get(
'islandora_matomo_report_enabled_content_models',
['ir:citationCModel', 'ir:thesisCModel']
);
return (count(array_intersect($object->models, $show_cmodels)) > 0);
}
/**
* Determine if the object has an allowed CMODEL for the count block.
*
* @param \AbstractObject $object
* The object we are viewing.
*
* @return bool
* Whether $object has a content model to show count for.
*/
function islandora_matomo_showcount_for_cmodel(AbstractObject $object) {
$show_cmodels = variable_get(
'islandora_matomo_count_enabled_content_models',
['ir:citationCModel', 'ir:thesisCModel']
);
return (count(array_intersect($object->models, $show_cmodels)) > 0);
}
/**
* Implements hook_cron().
*
* Gets all users that want a matomo report and send them a gist via email.
*/
function islandora_matomo_cron() {
$now = time();
$to_days = idate('d', $now);
// Will only run if in the first 9 days of a month. That gives enough time.
// @TODO Needs to be documented that Cron will try to send 500 users per run.
if (!variable_get('islandora_matomo_send_emails', 1) || $to_days >=9 ) {
return;
}
module_load_include('inc', 'islandora_matomo', 'includes/mailer_utils');
$lasttime = strtotime("-20DAYS", $now);
// This means will never send anything if already send in last 20 days.
// 20 days diff + 9 days trying to send seems like a sweet combination.
// This gives us enough of a check i guess
// @LASIR can add then skip-condition if needed.
$result = db_query('SELECT userkey.entity_id as entity_id, userkey.field_islandoramatomo_userkey_value as userkey_value, lastreport.field_islandoramatomo_lastreport_value
FROM {field_data_field_islandoramatomo_userkey} userkey
INNER JOIN {users} users ON users.uid = userkey.entity_id
INNER JOIN {field_data_field_islandoramatomo_sendreport} sendreport ON sendreport.entity_type = userkey.entity_type AND sendreport.entity_id = userkey.entity_id
LEFT JOIN {field_data_field_islandoramatomo_lastreport} lastreport ON (lastreport.entity_type = userkey.entity_type
AND lastreport.entity_id = userkey.entity_id) OR (lastreport.entity_type IS NULL)
WHERE userkey.field_islandoramatomo_userkey_value IS NOT NULL
AND sendreport.entity_id = userkey.entity_id
AND userkey.entity_type = sendreport.entity_type
AND sendreport.field_islandoramatomo_sendreport_value = :send
AND userkey.entity_type = :entityid
AND userkey.deleted = :deleted
AND (lastreport.field_islandoramatomo_lastreport_value < :timestamp OR lastreport.field_islandoramatomo_lastreport_value IS NULL)
LIMIT 0,500', array(':entityid' => 'user', ':deleted' => 0, ':send' => 1, ':timestamp' => $lasttime));
// Tries to run 500 users at a time. Not sure if too many, but this all depends on how often cron will run.
while ($record = $result->fetchObject()) {
$realuser = user_load($record->entity_id);
$key = $record->userkey_value;
// Only process stats for users that have Objects and a Scholar Profile.
if ((($pid = islandora_matomo_get_userprofile(
$key
)) != NULL) && ($objectcount = islandora_matomo_get_objectcount_foruser(
$key
))) {
islandora_matomo_user_notify($realuser, $pid, $key, $objectcount);
}
}
}
/**
* Implements hook_mail().
*/
function islandora_matomo_mail($key, &$message, $params) {
$username = format_username($params['user']);
$useruid = $params['user']->uid;
$sitename = variable_get('site_name', 'Islandora Repository');
$upl = user_preferred_language($params['user']);
$month = $params['month'];
$year = $params['year'];
// Query Solr for this.
$numobjects = $params['objectcount'];
$matomo_actions = $params['hits'];
// Make this the Scholar profile Object.
$pid = $params['profile_pid'];
/*
Subject: Your [most recent month] readership report from [Repository name]
Dear [ Jon Jon ],
Here is your monthly readership report provided by [Repository name].
Your work was accessed [x] times in [most recent month].
As of [most recent month], you have deposited [x] works in
[Repository Name] and your work has been accessed a total of [x] times.
Visit your [author dashboard] to learn more about your readership.
[Contact Us] | [Unsubscribe] | Visit [Repository Name]
*/
$message['headers']['MIME-Version'] = '1.0';
$message['headers']['Content-Type'] = 'text/plain;charset=utf-8';
$message['subject'] = t(
'Your !month !year readership report from !sitename',
[
'!month' => $month,
'!year' => $year,
'!sitename' => $sitename,
],
['langcode' => $upl->language]
);
$message['body'][] = t(
'Dear !username,',
[
'!username' => $username,
],
['langcode' => $upl->language]
);
$message['body'][] = t(
'Here is your monthly readership report provided by !sitename.',
[
'!sitename' => $sitename,
],
['langcode' => $upl->language]
);
$message['body'][] = t(
'As of !month, you have deposited !numobjects works in !sitename and your work has been accessed a total of !hits times.',
[
'!month' => $month,
'!numobjects' => $numobjects,
'!sitename' => $sitename,
'!hits' => $matomo_actions,
],
['langcode' => $upl->language]
);
$message['body'][] = t(
'Visit !url to learn more about your readership.',
[
'!url' => url(
'islandora/object/' . $pid . '/readership',
['absolute' => TRUE]
),
],
['langcode' => $upl->language]
);
$message['body'][] = t(
'This is an automatic e-mail from !sitename.',
['!sitename' => variable_get('site_name', 'Drupal')],
['langcode' => $upl->language]
);
$message['body'][] = t(
'To stop receiving these e-mails, change your readership notification preferences at !url.',
[
'!url' => url('user/' . $useruid, ['absolute' => TRUE]),
],
['langcode' => $upl->language]
);
}