-
Notifications
You must be signed in to change notification settings - Fork 0
/
deviceTracker.php
1157 lines (944 loc) · 39.9 KB
/
deviceTracker.php
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
998
999
1000
<?php namespace STPH\deviceTracker;
use Exception;
use REDCap;
use Records;
use ExternalModules\ExternalModules;
// Require composer dependencies during development only
if( file_exists("vendor/autoload.php") ){
require 'vendor/autoload.php';
}
// Require custom classes
if (!class_exists("Tracking")) require_once("classes/tracking.class.php");
class deviceTracker extends \ExternalModules\AbstractExternalModule {
//======================================================================
// Overview
//======================================================================
/**
* module support for different project setups
*
* from single instrument single-event single arm ~ supported @1.0.0
* from single instrument multiple-event single arm ~ supported @1.4.0
* from repeating instrument multiple-event single arm ~ invalidated @1.4.0
* * * * * multiple arms ~ unsupported (tbd: invalidated)
*
*/
//======================================================================
// Variables
//======================================================================
public $devices_project_id;
private $devices_event_id;
private $tracking_record;
private $tracking_page;
private $tracking_fields;
private $tracking_event;
//======================================================================
// Methods
//======================================================================
# Base
# Ajax Calls
# Controllers
//-----------------------------------------------------
// Base
//-----------------------------------------------------
private function initModule() {
// Setup Project Context if pid is available through request and constant is not yet defined
if(isset($_GET["pid"]) && !defined('PROJECT_ID')) {
define('PROJECT_ID', $this->escape($_GET["pid"]));
}
// Set Device Project variables
$this->setDeviceProject();
}
/**
* Set Device Project variables
*
* Covers test context
* @since 1.0.0
*/
private function setDeviceProject() {
$this->devices_project_id = $this->getSystemSetting("devices-project");
if(!empty($this->devices_project_id)) {
$this->devices_event_id = (new \Project( $this->devices_project_id ))->firstEventId;
}
}
/**
* Hooks Device Tracker module to redcap_data_entry_form
*
* @since 1.0.0
*/
public function redcap_data_entry_form_top($project_id = null) {
if($this->isValidTrackingPage()) {
if(!$this->isValidDevicesProject()) {
$this->renderAlertInvalidDevices();
$this->renderDisableTrackingField();
}
elseif(!$this->isValidTrackingProject()) {
$this->renderAlertInvalidTracking();
$this->renderDisableTrackingField();
}
else {
$this->renderTrackingInterface();
}
}
}
/**
* Allows custom actions to be performed on any of the pages in REDCap's Control Center
*
*/
public function redcap_control_center() {
if($this->isPage("ExternalModules/manager/control_center.php")) {
$this->initModule();
$config = $this->getConfig();
$invalids = array_filter($config, function($el){
return $el["valid"] == false;
});
$count = count($invalids);
if($count > 0) {
$this->includeControlCenterJS($count);
}
}
}
/**
* Ajax
*
*/
public function redcap_module_ajax($action, $payload, $project_id, $record, $instrument, $event_id, $repeat_instance, $survey_hash, $response_id, $survey_queue_hash, $page, $page_full, $user_id, $group_id) {
$this->initModule();
switch ($action) {
case 'get-tracking-data':
$result = $this->ajax_getTrackingData($payload, $project_id);
break;
case 'get-additional-fields':
$result = $this->ajax_getAdditionalFields($payload, $project_id);
break;
case 'get-tracking-logs':
$result = $this->ajax_getTrackingLogs($payload, $project_id);
break;
case 'validate-device':
$result = $this->ajax_validateDevice($payload);
break;
case 'handle-tracking':
$result = $this->ajax_handleTracking($payload);
break;
case 'delete-tracking':
$result = $this->ajax_deleteTracking($payload, $project_id, $event_id, $repeat_instance, $record, $user_id);
break;
default:
// Action not defined
throw new Exception ("Action $action is not defined");
}
return $result;
}
private function ajax_deleteTracking($payload, $project_id, $event_id, $repeat_instance, $record, $user_id){
$affected_rows_tracking = 0;
$tracking_data = $payload["tracking"];
$field = $payload["field"];
if(empty($tracking_data)) {
throw new Exception("'tracking' must be set!");
}
if(empty($field)) {
throw new Exception("'field' must be set!");
}
// check user rights
$user = $this->getUser($user_id);
$record_delete_right = (bool) $user->getRights([$project_id])["record_delete"];
$isSuperUser = $user->isSuperUser();
if(!$record_delete_right && !$isSuperUser) {
throw new Exception("user '".$user_id."' has not required user right 'record_delete' to delete a tracking.");
}
$tracking_settings = $this->getTrackingSettingsForField($field);
// start deletion
try {
// Begin database transaction
$this->beginDbTx();
/**
* Delete data in tracking project:
* tracking field
* sync fields
* additional fields
*
*/
$sync_fields = array_values(array_filter($tracking_settings, function($key){
return strpos($key, 'sync-') === 0;
},ARRAY_FILTER_USE_KEY));
$additional_fields = [];
foreach ($tracking_settings as $i => $v) {
if(strpos($i, 'additional-fields-') === 0) {
foreach ($tracking_settings[$i] as $j => $w) {
foreach ($w as $k => $x) {
$additional_fields[] = $x;
}
}
}
}
$fields_to_delete = array_merge(array($field), $sync_fields, $additional_fields);
$field_names = implode("','", $fields_to_delete);
$data_table = method_exists('\REDCap', 'getDataTable') ? \REDCap::getDataTable($project_id) : "redcap_data";
$sqlTrackingProject = "DELETE FROM $data_table WHERE project_id = ? AND event_id = ? AND record = ? AND field_name IN ('$field_names')";
$query = $this->createQuery();
$query->add($sqlTrackingProject, [$project_id, $event_id, $record]);
$query->execute();
$affected_rows_tracking = $query->affected_rows;
// 2. delete in devices project
/**
* Delete record instance from devices project
*
*/
$project_id_d = $this->devices_project_id;
$record_d = $tracking_data["record_id"];
$instrument_d = strtolower($tracking_data["redcap_repeat_instrument"]);
$event_id_d = $this->devices_event_id;
$instance_d = $tracking_data["redcap_repeat_instance"];
$log_event_id = Records::deleteForm($project_id_d, $record_d, $instrument_d, $event_id_d, $instance_d);
// Write to log
$logId = $this->log(
"tracking-delete",
[
"action"=> 'tracking-delete',
"field" => $field,
"value" => $record_d,
"record" => $record,
"event" => $event_id,
"user" => $user_id,
"date" => date("Y-m-d H:i:s")
]
);
// End database transaction
$this->endDbTx();
return array(
"tracking_id" => $tracking_data["session_tracking_id"],
"deleted_data_count" => $affected_rows_tracking
);
} catch(\Throwable $th) {
// Rollback database
$this->rollbackDbTx();
return array("error" => $th->getMessage());
}
}
private function ajax_handleTracking($payload){
if(empty($payload["device_id"])) {
throw new Exception("'device_id' must be set!");
}
if(empty($payload["field_id"])) {
throw new Exception("'field_id' must be set!");
}
if(empty($payload["owner_id"])) {
throw new Exception("'owner_id' must be set!");
}
if(empty($payload["action"])) {
throw new Exception("'action' must be set!");
}
if( !in_array( $payload["action"], array('assign', 'return', 'reset'))){
throw new Exception("Invalid tracking action!");
}
$tracking = new Tracking($payload);
try {
// Begin database transaction
$this->beginDbTx();
// Retrieve current device instance info (assuming that current instance is last instance)
list($lastSessionId, $lastSessionState, $isLastSessionUntracked) = $this->getSessionData($tracking->device);
// Validate session data
// Do checks and determine ID of session to be saved
$saveSessionId = $tracking->validateSessionData($lastSessionId, $lastSessionState, $isLastSessionUntracked);
// Retrieve tracking ID
$currentTrackingId = $this->getCurrentTrackingId($tracking->project, $tracking->field, $tracking->owner, $tracking->event);
// Validate tracking ID
$tracking->validateTrackingId($currentTrackingId);
/**
* 1. Save data to devices project
*
*/
$saved_d = $tracking->saveDataToDevices($this->devices_project_id, $this->devices_event_id, $saveSessionId);
// Throw error if there were errors during save
if(is_array($saved_d["errors"]) && count($saved_d["errors"]) !== 0) {
throw new Exception(implode(", ", $saved_d["errors"]));
} elseif(!empty($saved_d["errors"])) {
throw new Exception($saved_d["errors"]);
}
/**
* 2. Save data to tracking project
*
*/
// Get tracking settings
$tracking_settings = $this->getTrackingSettingsForField($tracking->field);
list($saved_t, $hasExtra, $sync_data) = $tracking->saveDataToTracking($tracking_settings);
// Check if there were any errors during save and throw error
if(is_array($saved_t["errors"]) && count($saved_t["errors"]) !== 0) {
throw new Exception(implode(", ", $saved_t["errors"]));
} elseif(!empty($saved_t["errors"])) {
throw new Exception($saved_t["errors"]);
}
// Write to log
$logId = $this->log(
"tracking-action",
[
"action"=> $tracking->action,
"field" => $tracking->field,
"value" => $tracking->device,
"record" => $tracking->owner,
"event" => $tracking->event,
"session" => $lastSessionId,
"user" => $tracking->user,
"date" => $tracking->timestamp,
"valid" => true,
"extra" => json_encode($tracking->extra),
"timestamp" => $tracking->timestamp
]
);
// End database transaction
$this->endDbTx();
} catch (\Throwable $th) {
// Rollback database
$this->rollbackDbTx();
// Handle Error
// Save to logs
$this->log("tracking-error", [
"error" => $th->getMessage(),
"action"=> $tracking->action,
"field"=> $tracking->field,
"event" => $tracking->event,
"value"=> $tracking->device,
"record" => $tracking->owner,
"user" => $tracking->user,
"date" => $tracking->timestamp
]);
throw new Exception("<br><br><b>".$th->getMessage() . "</b><br>Exception thrown at line <i>" . $th->getLine(). "</i> in file <i>" . $th->getFile() . "</i>");
}
$response = array(
"tracking" => $tracking,
"devices_project" => $this->devices_project_id,
"saved_devices" => $saved_d,
"saved_tracking" => $saved_t ?? [],
"log_id" => $logId,
"extra" => array(
"hasExtra" => $hasExtra,
"data" => $tracking->extra,
"use"=>(bool) $tracking_settings["use-additional-assign"] // unclear
),
"sync" => $sync_data ?? [],
"settings" => $tracking_settings
);
return $response;
}
private function ajax_validateDevice($payload){
$trackingField = $payload["tracking_field"];
$device_id = $payload["device_id"];
if(empty($trackingField)) {
throw new Exception("tracking field must be set!");
}
if(empty($device_id)) {
throw new Exception("device id must be set!");
}
$types = $this->getDeviceTypesForField($trackingField);
$availableDevices = $this->getAvailableDevices($types);
$device = $availableDevices[$device_id];
// Check if device is within available devices
if(!isset($device)){
return array("validation_message" => "Device is not available.");
}
// Check if suspension date was set and invalidated when suspension time has passed
$suspension_date = reset($device)["device_suspension_date"];
if(!empty($suspension_date)){
$suspension_date_time = strtotime(reset($device)["device_suspension_date"]);
if( $suspension_date_time < time()) {
return array("validation_message" => "Device (ID:".$device_id.") has been suspended: " . $suspension_date);
}
}
// return device_id in case the device is valid
if(isset($device)) {
return array("device_id" => $device_id);
}
return false;
}
private function ajax_getTrackingData($payload, $project_id){
$response = [];
$record = $payload["record"];
$field = $payload["field"];
$event_id = $payload["event_id"];
if(empty($record)) {
throw new Exception("Record must be set!");
}
if(empty($field)) {
throw new Exception("Field must be set!");
}
if(empty($event_id)) {
throw new Exception("Event must be set!");
}
// query redcap_dataX directly instead of calling REDCap::getData()
// this seems to resolve performance issues: https://github.com/vanderbilt-redcap/external-module-framework/issues/619
$data_table = method_exists('\REDCap', 'getDataTable') ? \REDCap::getDataTable($project_id) : "redcap_data";
$sql = "SELECT value as session_tracking_id FROM $data_table WHERE project_id = ? AND event_id= ? AND record = ? AND field_name = ?";
$result = $this->query($sql, [$project_id, $event_id, $record, $field]);
while($row = $result->fetch_assoc()){
$session_tracking_id = $row['session_tracking_id'];
}
if(empty($session_tracking_id)) {
return $response;
}
// $params = [
// 'project_id' => $project_id,
// 'records' => $record,
// 'fields' => $field,
// 'events' => $event_id,
// 'return_format' => 'json'
// ];
// $data_t = json_decode( REDCap::getData($params), true);
// Ensure this check is secure for multiple and single events! (Also cover the case when event has data inside other instrument)
// if(empty($data_t[0][$field])) {
// return $response;
// }
// $session_tracking_id = reset($data_t)[$field];
$filterLogic = "[session_tracking_id] = '" . $session_tracking_id . "'";
$params = array(
'return_format' => 'json',
'project_id' => $this->devices_project_id,
'exportAsLabels' => true,
'filterLogic' => $filterLogic,
'fields' => []
);
$json = REDCap::getData($params);
$response = reset(json_decode($json));
return $response;
}
private function ajax_getAdditionalFields($payload, $project_id){
$field = $payload["field"];
$mode = $payload["mode"];
if(empty($field)) {
throw new Exception("Field must be set!");
}
if(empty($mode)) {
throw new Exception("Mode must be set!");
}
$additionalFields = [];
$tracking = $this->getTrackingSettingsForField($field);
if($tracking["use-additional-" . $mode]) {
foreach ($tracking["additional-fields-" . $mode] as $key => $additionalField) {
$additionalFields[] = $this->getFieldMetaData($additionalField["add-field-" . $mode]);
}
}
return $additionalFields;
}
/**
* Get Tracking Logs for Tracker and Monitor App
*
*/
private function ajax_getTrackingLogs($payload, $project_id) {
$logs = [];
$record = $payload["record"];
$field = $payload["field"];
$event_id = $payload["event_id"];
// system/project context
if($record === null) {
$sql = "select log_id, message, project_id, event, date, user, action, field, value, record, instance, error";
$parameters = [];
// project context
if($project_id !== null) {
$sql = "select log_id, message, event,date, user, action, field, value, record, instance, error WHERE project_id = ?";
$parameters = [$project_id];
}
$result = $this->queryLogs($sql, $parameters);
while($row = $result->fetch_assoc()){
$logs[] = $this->escape($row);
}
$result->close();
} else {
if($field === null) {
throw new Exception("Field must be set.");
}
// record context
$sql = "select log_id, message, user, action, field, date, record where message = ? AND record = ? AND field = ?";
$parameters = ['tracking-action', $record, $field];
$project = new \Project($project_id);
// longitudinal project
if($project->longitudinal === true && $event_id !== null) {
$sql .= " AND event = ?";
$parameters = ['tracking-action', $record, $field, $event_id];
}
$result = $this->queryLogs($sql, $parameters);
while($row = $result->fetch_object()){
$entry = [
"action" => $this->escape($row->action),
"date" => $this->escape($row->date),
"user"=> $this->escape($row->user)
];
$logs[] = $entry;
}
}
return $logs;
}
/**
* Include Javascript to embed module configuration error messages and link to module config check page
*
*/
private function includeControlCenterJS($count) {
$box = '<div class="red" style="margin-bottom:15px;padding:10px 15px;"><div style="color:#A00000;"><i class="fas fa-bell"></i> <span style="margin-left:3px;font-weight:bold;"><span id="module-config-error-count">'.$count.'</span> module configuration errors for Device Tracker are blocking its proper functionality. <a style="color:white;text-decoration:none;font-weight:normal;" href="'.$this->getUrl('link-control-center.php').'" class="btn btn-danger btn-xs ml-2">View config</a></span></div></div></div></div>';
?>
<script type='text/javascript'>
$(function() {
$('#external-modules-enable-modules-button').before('<?= $box ?>');
//$('#external-modules-enabled').find('tr[data-module="device_tracker"] td').first().find(".external-modules-byline").append("Foo");
})
</script>
<?php
}
/**
* Check if is a valid page for tracking and sets parameters as variables
*
*
* @since 1.4.0
*/
private function isValidTrackingPage() {
// Check if valid Data Entry page
if(isset( $_GET['id']) && defined('USERID')) {
$this->initModule();
$all_tracking_fields = $this->getAllTrackingFields();
// Check if is a valid Form Page with Tracking field
if($_GET["page"] && in_array($_GET["page"], array_keys($all_tracking_fields))) {
// Set tracking variables
$this->tracking_record = $this->escape($_GET["id"]);
$this->tracking_page = $this->escape($_GET["page"]);
$this->tracking_event = $this->escape($_GET["event_id"]);
$this->tracking_fields = $all_tracking_fields[$this->tracking_page];
return true;
}
}
return false;
}
/**
* Check if module configuration is correct
*
* 1. Check Device Tracking Project Configuration
* 1.0 pid not null
* 1.1 project->longitudinal is false
* 1.2 project->multiple_arms is false
*
* 2. Check forms
* 2.0 Check if form exists
* 2.1 Check if form fullfills repeating
*
* 3. Check fields
* 3.0 Check if field exist
*
* 4. Check field settings
* 4.0 Check if settings are valid
*
*/
public function getConfig() {
$config = array();
// Get project id in correct context
$pid = $this->getSystemSetting("devices-project");
/**
* 1.0 Check if Device Project has been set
* should not be null
*
* */
$config[] = array( "id" => "1-0", "valid" => $pid !== null, "rule" => "Device Project is defined.");
// abort further checking if project unset or invalid
if($pid !== null ) {
// Get project object (does not populate repeating forms..)
$project = new \Project($pid);
/**
* 1.0.1 Check if Device Project id is valid
*
*
*/
$config[] = array( "id" => "1-0-1", "valid" => $this->getProjectStatus($pid) !== null, "rule" => "Device Project is valid.");
if($this->getProjectStatus($pid) === null){
return $config;
}
/**
* 1.1 Check if Device Project is longitudinal
* should be false
*
*/
$config[] = array( "id" => "1-1", "valid" => $project->longitudinal === false, "rule" => "Device Project is not longitudinal");
/**
* 1.2 Check if Device Project has multiple arms
* should be false
*
*/
$config[] = array( "id" => "1-2", "valid" => $project->multiple_arms === false, "rule" => "Device Project has no multiple arms");
// Get repeating forms
$repeatingForms = array_keys(reset($project->getRepeatingFormsEvents()));
// Load rule schema from json file
$schema_json = file_get_contents( dirname(__FILE__) . "/schema.json");
$schema = json_decode($schema_json, true);
// Loop through all forms
foreach ($schema["forms"] as $key_form => $form) {
/**
* 2.1.x Check if form exists
* should be true
*
*/
$config[] = array( "id" => "2-1-".$key_form, "valid" => in_array($form["name"], array_keys( $project->forms)), "rule" => "Form '" . $form["name"] . "' exists");
/**
* 2.2.x Check if form is repeating
* should be bool of repeating
*
*/
$config[] = array( "id" => "2-2-".$key_form, "valid" => in_array($form["name"], $repeatingForms) == $form["repeating"], "rule" => "Form '" . $form["name"] . "' is" . ($form["repeating"] ? "": " not") . " repeating");
// Loop through all fields for each form
foreach ($form["fields"] as $key_field => $field) {
/**
* 3.0.x Check if field exists
* should be true
*
*/
$config[] = array(
"id" => "3-0-".$key_form."-".$key_field,
"valid" => $project->metadata[$field["name"]] && $project->metadata[$field["name"]]["form_name"] == $form["name"],
"rule" => "Field '" . $field["name"] . "' exists in form '" . $form["name"] . "'");
// Loop through all settings for each field
foreach ($field["settings"] as $key_setting => $setting) {
/**
* 4.0.x Check if field settings are valid
* should be true
*
*/
$setting_name = key($setting);
$setting_value = current($setting);
$config[] = array(
"id" => "4-0-".$key_form."-".$key_field."-".$key_setting,
"valid" => $project->metadata[$field["name"]][$setting_name] == $setting_value,
"rule" => "Field '" . $field["name"] . "' has setting '". $setting_name . "' with value '" . $setting_value . "'",
// only shows diff of setting values, does not cover differences in setting names!
"diff" => join(' ', array_diff(explode(" ",$project->metadata[$field["name"]][$setting_name]), explode(" ", $setting_value)))
);
}
}
}
}
return $config;
}
/**
* Validate Devices project
* Fetch config, count invalid rules
*
*
* @since 1.4.0
*/
private function isValidDevicesProject() {
$invalids = array_filter($this->getConfig(), function($el){
return $el["valid"] == false;
});
return count($invalids) == 0;
}
/**
* Validate Tracking project
*
*
* @since 1.4.0
*/
private function isValidTrackingProject() {
$project = new \Project(PROJECT_ID);
$longitudinal = $project->longitudinal;
$multiple_arms = $project->multiple_arms;
$RULE_SINGLE_EVENT_SINGLE_ARM = $longitudinal == false && $multiple_arms == false;
$RULE_MULTIP_EVENT_SINGLE_ARM = $longitudinal == true && $multiple_arms == false;
// TBD: Check that tracking field is NOT repeating
// Is valid if any of those rules is true
return $RULE_SINGLE_EVENT_SINGLE_ARM || $RULE_MULTIP_EVENT_SINGLE_ARM;
}
/**
* Render HTML and Javascript to insert Vue Instance
*
*
* @since 1.0.0
*/
private function renderTrackingInterface() {
$this->initializeJavascriptModuleObject();
// Loop through all tracking fields for each form and insert for each a wrapper into DOM,
// so that vue can actually mount an there.
foreach ($this->tracking_fields as $key => $tracking_field) {
?>
<div id="STPH_DT_WRAPPER_<?= $tracking_field ?>" style="display: none;">
<div id="STPH_DT_FIELD_<?= $tracking_field ?>"></div>
</div>
<?php
}
// move mounted vue instances to correct position (=vue target)
// within DOM for each field
?>
<script type='text/javascript'>
$(function() {
$(document).ready(function() {
var trackings = <?=json_encode($this->tracking_fields) ?>;
trackings.forEach(function(tracking_field){
// Insert vue target
var target = $('tr#'+tracking_field+'-tr').find('input');
var wrapper = $('#STPH_DT_WRAPPER_' + tracking_field);
// Prepend
target.parent().prepend(wrapper);
wrapper.show();
target.hide();
console.log('Device Tracker initiated on field "' + tracking_field + '"');
});
})
});
</script>
<!-- backend data passthrough -->
<script type='text/javascript'>
const stph_dt_getDataFromBackend = function () {
return <?= $this->getDataFromBackend() ?>
}
const stph_dt_getModuleFromBackend = function() {
return <?=$this->getJavascriptModuleObjectName()?>;
}
</script>
<!-- actual vue scripts -->
<script src="<?= $this->getUrl('./dist/appTracker.js') ?>"></script>
<?php
}
private function renderDisableTrackingField() {
?>
<script type='text/javascript'>
$(function() {
$(document).ready(function() {
console.log("Disable tracking field due to invalid devices project.");
var tracking_fields = <?= json_encode($this->tracking_fields) ?>;
tracking_fields.forEach(field => {
var field_tr = $('tr#'+field+'-tr');
field_tr.find('td').css('background-color', '#f8d7da');
field_tr.find('input').prop('disabled', true);
});
});
});
</script>
<?php
}
private function renderAlertInvalid($msg) {
?>
<script type='text/javascript'>
$(function() {
$(document).ready(function() {
console.log("Invalid tracking project.")
var msg = '<?= $msg ?>'
var alert_html = '<div class="alert alert-danger alert-dismissible fade show" role="alert">'+msg+'<button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button></div>';
$('form#form div').first().prepend(alert_html);
});
});
</script>
<?php
}
private function renderAlertInvalidDevices() {
$msg = "Invalid <b>Devices Project</b><br>The current devices project is not a valid Devices Project. Please notify a REDCap administrator and check the documentation to correctly setup your devices project with Device Tracker module.";
$this->renderAlertInvalid($msg);
}
/**
* Render invalid Tracking Page
*
* @since 1.4.0
*/
private function renderAlertInvalidTracking() {
$msg = "Invalid <b>Tracking Project</b><br>The current tracking project is not a valid Tracking Project. Please check the documentation to correctly setup your tracking project with Device Tracker module.";
$this->renderAlertInvalid($msg);
}
/**
* Get data from backend to pass into vue instance(s)
*
* @since 1.0.0
*/
private function getDataFromBackend() {
$timeout = $this->getSystemSetting("timeout") ?? 1500;
// Validate Timout Setting
if(!is_numeric($timeout) || $timeout < 500) {
$timeout = 1500;
}
// Initialize
$data = [];
// Base URL for Axios Requests
$data["base_url"] = $this->getUrl("requestHandler.php");
// Page Data
$data["page"] = [
"path" => PAGE_FULL,
"user_id" => USERID,
"project_id" => PROJECT_ID,
"record_id" => $this->tracking_record,
"name" => $this->tracking_page,
"event_id" => $this->tracking_event,
"timeout" => $timeout
];
$data["fields"] = $this->tracking_fields;
return json_encode($data);
}
//-----------------------------------------------------
// Controllers
//-----------------------------------------------------
/**
* Get a list of all available devices by [device_type]
* where [session_device_state] is blank or 0
*
* @since 1.0.0
*/
private function getAvailableDevices(array $types=[]) :array {
// General filter logic
$filterLogic = '([session_device_state][last-instance] = 0 or isblankormissingcode([session_device_state][last-instance]))';
// Add filter by type(s) if given
$filterForTypes = "";
if(!empty($types)) {
if(count($types) == 1) {
$filterForTypes = "[device_type] = " . $types[0];
} else {
$filterForTypes = "(";
foreach ($types as $key => $type) {
if($key == 0) {
$filterForTypes .= "[device_type] = " . $type ;
} else {
$filterForTypes .= " or [device_type] = " . $type;
}
}
$filterForTypes .= ")";
}
$filterLogic .= " and " . $filterForTypes;
}
$params = array(
'project_id' => $this->getSystemSetting("devices-project"),
'filterLogic'=> $filterLogic,
'fields'=>array('record_id', 'device_type', 'session_device_state', 'device_registration_date' ,'device_suspension_date')
);
return REDCap::getData($params);
}
/**
* Get Tracking Settings for a Tracking Field
*
* @since 1.0.0
*/
private function getTrackingSettingsForField($tracking_field) {
$trackings = $this->getSubSettings('trackings');
$trackings_filtered = array_filter($trackings, function($tracking) use ($tracking_field){
return $tracking["tracking-field"] == $tracking_field;