-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataEntryTriggerBuilder.php
More file actions
1494 lines (1302 loc) · 68.6 KB
/
DataEntryTriggerBuilder.php
File metadata and controls
1494 lines (1302 loc) · 68.6 KB
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 BCCHR\DataEntryTriggerBuilder;
require_once "vendor/autoload.php";
use Dompdf\Dompdf;
use REDCap;
use Project;
use DateTime;
class DataEntryTriggerBuilder extends \ExternalModules\AbstractExternalModule
{
/**
* Replaces all strings in $text with $replacement
* So "Alice says 'hello'" becomes "Alice says ''" assuming $replacement = ''.
*
* @access private
* @param String $text The text to replace.
* @param String $replacement The replacement text.
* @return String A string with the replaced text.
*/
private function replaceStrings($text, $replacement)
{
$quotes = [];
preg_match_all("/'/", $text, $quotes, PREG_OFFSET_CAPTURE);
$quotes = $quotes[0];
if (sizeof($quotes) % 2 === 0)
{
$i = 0;
$to_replace = array();
while ($i < sizeof($quotes))
{
$to_replace[] = substr($text, $quotes[$i][1], $quotes[$i + 1][1] - $quotes[$i][1] + 1);
$i = $i + 2;
}
$text = str_replace($to_replace, $replacement, $text);
}
return $text;
}
/**
* Parses a syntax string into blocks.
*
* @access private
* @param String $syntax The syntax to parse.
* @return Array An array of blocks that make up the syntax passed.
*/
private function getSyntaxParts($syntax)
{
$syntax = str_replace(array("['", "']"), array("[", "]"), $syntax);
$syntax = $this->replaceStrings(trim($syntax), "''"); // Replace strings with ''
$parts = array();
$previous = array();
$i = 0;
while($i < strlen($syntax))
{
$char = $syntax[$i];
switch($char)
{
case ",":
case "(":
case ")":
case "]":
$part = trim(implode("", $previous));
$previous = array();
if ($part !== "")
{
$parts[] = $part;
}
$parts[] = $char;
$i++;
break;
case "[":
$part = trim(implode("", $previous));
if ($part !== "")
{
$parts[] = $part;
}
$parts[] = $char;
$previous = array();
$i++;
break;
case " ":
$part = trim(implode("", $previous));
$previous = array();
if ($part !== "")
{
$parts[] = $part;
}
$i++;
break;
default:
$previous[] = $char;
if ($i == strlen($syntax) - 1)
{
$part = trim(implode("", $previous));
if ($part !== "")
{
$parts[] = $part;
}
}
$i++;
break;
}
}
return $parts;
}
/**
* Returns the number of minutes it's been since the last time an email was sent
*/
private function get_last_send_time()
{
$last_send_timestamp = $this->getSystemSetting("email_last_sent_timestamp");
if(is_null($last_send_timestamp))
{
return $this->getSystemSetting("det-error-check-frequency");
}
$date_time = new DateTime($last_send_timestamp);
$diff = $date_time->diff(new DateTime());
return $diff->i;
}
/**
* Checks whether a field exists within a project.
*
* @param String $var The field to validate
* @param String $pid The project id the field supposedly belongs to. Use current project if null.
* @return Boolean true if field exists, false otherwise.
*/
public function isValidField($var, $pid = null)
{
$var = trim($var, "'");
if ($pid != null) {
$data_dictionary = REDCap::getDataDictionary($pid, 'array');
}
else {
$data_dictionary = REDCap::getDataDictionary('array');
}
$fields = array_keys($data_dictionary);
$external_fields = array();
$external_fields[] = "redcap_data_access_group";
$instruments = array_unique(array_column($data_dictionary, "form_name"));
foreach ($instruments as $unique_name)
{
$external_fields[] = "{$unique_name}_complete";
}
$checkbox_values = array();
foreach($data_dictionary as $field_name => $data)
{
if ($data["field_type"] == "checkbox")
{
$choices = explode("|", $data["select_choices_or_calculations"]);
foreach($choices as $choice)
{
$choice = trim($choice);
$code = trim(substr($choice, 0, strpos($choice, ",")));
$checkbox_values[] = "{$field_name}___{$code}";
}
}
}
return in_array($var, $external_fields) || in_array($var, $fields) || in_array($var, $checkbox_values);
}
/**
* Checks whether a event exists within a project.
*
* @param String $var The event to validate
* @param String $pid The project id the event supposedly belongs to. Use current project if null.
* @return Boolean true if event exists, false otherwise.
*/
public function isValidEvent($var, $pid = null)
{
$var = trim($var, "'");
$RedcapProj = new Project($pid);
$events = array_values($RedcapProj->getUniqueEventNames());
return in_array($var, $events);
}
/**
* Checks whether a instrument exists within a project.
*
* @param String $var The instrument to validate
* @param String $pid The project id the instrument supposedly belongs to. Use current project if null.
* @return Boolean true if instrument exists, false otherwise.
*/
public function isValidInstrument($var, $pid = null)
{
$var = trim($var, "'");
if ($pid != null) {
$data_dictionary = REDCap::getDataDictionary($pid, 'array');
}
else {
$data_dictionary = REDCap::getDataDictionary('array');
}
$instruments = array_unique(array_column($data_dictionary, "form_name"));
return in_array($var, $instruments);
}
/**
* Validate syntax.
*
* @access private
* @see Template::getSyntaxParts() For retreiving blocks of syntax from the given syntax string.
* @param String $syntax The syntax to validate.
* @since 1.0
* @return Array An array of errors.
*/
public function validateSyntax($syntax)
{
$errors = array();
$logical_operators = array("==", "<>", "!=", ">", "<", ">=", ">=", "<=", "<=", "||", "&&", "=");
$parts = $this->getSyntaxParts($syntax);
$opening_squares = array_keys($parts, "[");
$closing_squares = array_keys($parts, "]");
$opening_parenthesis = array_keys($parts, "(");
$closing_parenthesis = array_keys($parts, ")");
// Check symmetry of ()
if (sizeof($opening_parenthesis) != sizeof($closing_parenthesis))
{
$errors[] = "<b>ERROR</b>Odd number of parenthesis (. You've either added an extra parenthesis, or forgot to close one.";
}
// Check symmetry of []
if (sizeof($opening_squares) != sizeof($closing_squares))
{
$errors[] = "Odd number of square brackets [. You've either added an extra bracket, or forgot to close one.";
}
foreach($parts as $index => $part)
{
switch ($part) {
case "(":
$previous = $parts[$index - 1];
$next_part = $parts[$index + 1];
if ($next_part !== "("
&& $next_part !== ")"
&& $next_part !== "["
&& !is_numeric($next_part)
&& $next_part[0] != "'"
&& $next_part[0] != "\""
&& $next_part[strlen($next_part) - 1] != "'"
&& $next_part[strlen($next_part) - 1] != "\"")
{
$errors[] = "Invalid <strong>$next_part</strong> after <strong>(</strong>.";
}
break;
case ")":
// Must have either a ), ] or logical operator after, if not the last part of syntax
if ($index != sizeof($parts) - 1)
{
$next_part = $parts[$index + 1];
if ($next_part !== ")" && $next_part !== "]" && !in_array($next_part, $logical_operators))
{
$errors[] = "Invalid <strong>$next_part</strong> after <strong>)</strong>.";
}
}
break;
case "==":
case "<>":
case "!=":
case ">":
case "<":
case ">=":
case ">=":
case "<=":
case "<=":
case "=":
if ($index == 0)
{
$errors[] = "Cannot have a comparison operator <strong>$part</strong> as the first part in syntax.";
}
else if ($index != sizeof($parts) - 1)
{
$previous = $parts[$index - 2];
$next_part = $parts[$index + 1];
if (in_array($previous, $logical_operators) && $previous !== "or" && $previous !== "and")
{
$errors[] = "Invalid <strong>$part</strong>. You cannot chain comparison operators together, you must use an <strong>and</strong> or an <strong>or</strong>";
}
if (!empty($next_part)
&& !is_numeric($next_part)
&& $next_part[0] != "'"
&& $next_part[0] != "\""
&& $next_part[strlen($next_part) - 1] != "'"
&& $next_part[strlen($next_part) - 1] != "\"")
{
$errors[] = "Invalid <strong>$next_part</strong> after <strong>$part</strong>.";
}
}
else
{
$errors[] = "Cannot have a comparison operator <strong>$part</strong> as the last part in syntax.";
}
break;
case "||":
case "&&":
if ($index == 0)
{
$errors[] = "Cannot have a logical operator <strong>$part</strong> as the first part in syntax.";
}
else if ($index != sizeof($parts) - 1)
{
$next_part = $parts[$index + 1];
if (!empty($next_part)
&& $next_part !== "("
&& $next_part !== "[")
{
$errors[] = "Invalid <strong>$next_part</strong> after <strong>$part</strong>.";
}
}
else
{
$errors[] = "Cannot have a logical operator <strong>$part</strong> as the last part in syntax.";
}
break;
case "[":
break;
case "]":
// Must have either a logical operator or ) or [ after, if not last item in syntax
if ($index != sizeof($parts) - 1)
{
$previous_2 = $parts[$index - 2];
$previous_5 = $parts[$index - 5];
$next_part = $parts[$index + 1];
if ($previous_2 !== "[" && $previous_5 !== "[") // Make sure it has an opening bracket. Proper syntax should be [, field_name, ], or [, field_name, (, code, ), ]
{
$errors[] = "Unclosed or empty <strong>]</strong> bracket.";
}
if ($next_part !== ")"
&& $next_part !== "["
&& !in_array($next_part, $logical_operators))
{
$errors[] = "Invalid <strong>'$next_part'</strong> after <strong>$part</strong>.";
}
}
break;
default:
// Check if it's a field or event
if ($part[0] != "'" &&
$part[0] != "\"" &&
$part[strlen($part) - 1] != "'" &&
$part[strlen($part) - 1] != "\"" &&
!is_numeric($part) &&
!empty($part) &&
($this->isValidField($part) == false && $this->isValidEvent($part) == false))
{
$errors[] = "<strong>$part</strong> is not a valid event/field in this project. If this is a checkbox field please use the following format: field_name<strong>(</strong>code<strong>)</strong>";
}
break;
}
}
return $errors;
}
/**
* Retrieve the following for all REDCap projects: ID, & title
*
* @return Array An array of rows pulled from the database, each containing a project's information.
*/
public function getProjects()
{
$query = $this->framework->createQuery();
$query->add("select project_id, app_title from redcap_projects", []);
if ($query_result = $query->execute())
{
while($row = $query_result->fetch_assoc())
{
$projects[] = $row;
}
}
return $projects;
}
/**
* Retrieves a project's fields
*
* @param String $pid A project's id in REDCap.
* @return String A JSON encoded string that contains all the event, instruments, and fields for a project.
*/
public function retrieveProjectMetadata($pid)
{
if (!empty($pid))
{
$metadata = REDCap::getDataDictionary($pid, "array");
$instruments = array_values(array_unique(array_column($metadata, "form_name")));
$RedcapProj = new Project($pid);
$events = array_values($RedcapProj->getUniqueEventNames());
$isLongitudinal = $this->escape($RedcapProj->longitudinal);
/**
* We can pipe over any data except descriptive, file, and signature fields.
*
* NOTE: For calculation fields only the raw data can be imported/exported.
*/
foreach($metadata as $field_name => $data)
{
if ($data["field_type"] == "checkbox")
{
$choices = explode("|", $data["select_choices_or_calculations"]);
foreach($choices as $choice)
{
$choice = trim($choice);
$code = trim(substr($choice, 0, strpos($choice, ",")));
$fields[] = "{$field_name}___{$code}";
}
}
if ($data["field_type"] != "descriptive" && $data["field_type"] != "signature" && $data["field_type"] != "file")
{
$fields[] = $field_name;
}
}
/**
* Add form completion status fields to push
*/
foreach($instruments as $instrument)
{
$fields[] = $instrument . "_complete";
}
// Add redcap_data_access_group to fields
$fields[] = "redcap_data_access_group";
return ["fields" => $fields, "events" => $events, "isLongitudinal" => $isLongitudinal, "instruments" => $instruments];
}
return FALSE;
}
/**
* Retrieves a project's data access groups
*
* @param String $pid A project's id in REDCap
* @return Array An array of unique Data Access Group names (based upon group name text) with group_id as array key and unique name as element
*/
public function retrieveProjectGroups($pid)
{
$RedcapProj = new Project($pid);
$dags = $RedcapProj->getUniqueGroupNames();
if ($dags) {
return $dags;
}
return FALSE;
}
public function get_det_errors($triggers)
{
$errors = [];
/**
* Process each trigger, and check if variables all exist in the data dictionary
*/
foreach($triggers as $index => $trigger_obj)
{
$dest_project_pid = $trigger_obj["dest-project"];
$err = $this->validateSyntax($trigger_obj["trigger"]);
if (!empty($err))
{
$errors[$index]["trigger_errors"] = $err;
}
if (!empty($trigger_obj["linkSourceEvent"]) && !$this->isValidEvent($trigger_obj["linkSourceEvent"]))
{
$errors[$index]["linkSourceEvent"] = "Invalid event!";
}
if (!$this->isValidField($trigger_obj["linkSource"]))
{
$errors[$index]["linkSource"] = "Invalid field!";
}
if (!empty($trigger_obj["linkDestEvent"]) && !$this->isValidEvent($trigger_obj["linkDestEvent"], $dest_project_pid))
{
$errors[$index]["linkDestEvent"] = "Invalid event!";
}
if (!$this->isValidField($trigger_obj["linkDest"], $dest_project_pid))
{
$errors[$index]["linkDest"] = "Invalid field!";
}
foreach($trigger_obj["pipingSourceEvents"] as $n => $field)
{
if(!$this->isValidEvent($field))
{
$errors[$index]["pipingSourceEvents"][$n] = "$field is an invalid event!";
}
}
foreach($trigger_obj["pipingSourceFields"] as $n => $field)
{
if(!$this->isValidField($field))
{
$errors[$index]["pipingSourceFields"][$n] = "$field is an invalid field!";
}
}
foreach($trigger_obj["pipingDestEvents"] as $n => $field)
{
if(!$this->isValidEvent($field, $dest_project_pid))
{
$errors[$index]["pipingDestEvents"][$n] = "$field is an invalid event!";
}
}
foreach($trigger_obj["pipingDestFields"] as $n => $field)
{
if(!$this->isValidField($field, $dest_project_pid))
{
$errors[$index]["pipingDestFields"][$n] = "$field is an invalid field!";
}
}
foreach($trigger_obj["setDestEvents"] as $n => $field)
{
if(!$this->isValidEvent($field, $dest_project_pid))
{
$errors[$index]["setDestEvents"][$n] = "$field is an invalid event!";
}
}
foreach($trigger_obj["setDestFields"] as $n => $field)
{
if(!$this->isValidField($field, $dest_project_pid))
{
$errors[$index]["setDestFields"][$n] = "$field is an invalid field!";
}
}
foreach($trigger_obj["sourceInstrEvents"] as $n => $field)
{
if(!$this->isValidEvent($field))
{
$errors[$index]["sourceInstrEvents"][$n] = "$field is an invalid event!";
}
}
foreach($trigger_obj["sourceInstr"] as $n => $field)
{
if(!$this->isValidInstrument($field))
{
$errors[$index]["sourceInstr"][$n] = "$field is an invalid instrument!";
}
}
foreach($trigger_obj["destInstrEvents"] as $n => $field)
{
if(!$this->isValidEvent($field, $dest_project_pid))
{
$errors[$index]["destInstrEvents"][$n] = "$field is an invalid event!";
}
}
if (!empty($trigger_obj["surveyUrlEvent"]) && !$this->isValidEvent($trigger_obj["surveyUrlEvent"], $dest_project_pid))
{
$errors[$index]["surveyUrlEvent"] = "Invalid event!";
}
if (!empty($trigger_obj["surveyUrl"]) && !$this->isValidInstrument($trigger_obj["surveyUrl"], $dest_project_pid))
{
$errors[$index]["surveyUrl"] = "Invalid instrument!";
}
if (!empty($trigger_obj["saveUrlEvent"]) && !$this->isValidEvent($trigger_obj["saveUrlEvent"]))
{
$errors[$index]["saveUrlEvent"] = "Invalid event!";
}
if (!empty($trigger_obj["saveUrlField"]) && !$this->isValidField($trigger_obj["saveUrlField"]))
{
$errors[$index]["saveUrlField"] = "Invalid field!";
}
}
return $errors;
}
/**
* REDCap hook is called immediately after a record is saved. Will retrieve the DET settings,
* & import data according to DET.
*/
public function redcap_save_record($project_id, $record, $instrument, $event_id, $group_id, $survey_hash, $response_id, $repeat_instance)
{
if ($project_id == $this->getProjectId())
{
// Get DET settings
$settings_json = $this->getProjectSetting("det_settings");
if (!$settings_json || $settings_json == "null") {
return;
}
$settings = json_decode($settings_json, true);
if ($settings)
{
if (array_key_exists("triggers", $settings)) {
$triggers = $settings["triggers"];
}
else {
$triggers = $settings;
}
if (array_filter($triggers, 'is_array') !== $triggers) {
$this->log("DET Builder: Existing settings not in expected json format for module");
return;
}
}
else {
$this->log("DET Builder: Invalid json detected in existing settings");
return;
}
// Send email if errors are present in DET
$errors = $this->get_det_errors($triggers);
if (!empty($errors))
{
$system_from_email = $this->getSystemSetting("system-from-email");
$system_contact_email = $this->getSystemSetting("system-contact-email");
$frequency = $this->getSystemSetting("det-error-check-frequency");
$subject = "Data Entry Trigger Builder Errors in Project $project_id";
$html_body = "<p>Errors have been detected in the Data Entry Trigger Builder external module for <b>PID $project_id</b>. Please fix this as soon as possible, otherwise the DET will not run properly.</p><p><a href='" . $this->getUrl("form.php") . "'>Click to Navigate to Project EM Page</a></p>";
$last_send_time = $this->get_last_send_time();
if ($system_from_email && $system_contact_email && intval($last_send_time) >= intval($frequency))
{
$email = new \Message();
$email->setFrom($system_from_email);
$email->setTo($system_contact_email);
$email->setSubject($subject);
$email->setBody($html_body, true);
$email->send();
$date_time = new DateTime();
$this->setSystemSetting("email_last_sent_timestamp", $date_time->format("Y-m-d H:i:s"));
}
}
// Get current record data
$record_data = json_decode(REDCap::getData("json", $record, null, null, null, false, true), true);
/**
* Process each trigger, and, if true, prepare associated data to move.
*/
foreach($triggers as $index => $trigger_obj)
{
$valid = REDCap::evaluateLogic($trigger_obj["trigger"], $project_id, $record); // REDCap class method to evaluate conditional logic.
if ($valid === null) // Null returned if logic is invalid. Else a boolean value.
{
$this->log("DET Builder: Trigger was either syntactically incorrect, or parameters were invalid (e.g., record or event does not exist). No data moved. Trigger #" . ($index + 1) . ": " . $trigger_obj["trigger"]);
}
else if ($valid)
{
$dest_record_data = [];
$dest_project = $trigger_obj["dest-project"];
$dest_dags = $this->retrieveProjectGroups($dest_project);
$overwrite_data = $trigger_obj["overwrite-data"];
$import_dags = $trigger_obj["import-dags"];
$link_source_event = $trigger_obj["linkSourceEvent"];
$link_source = $trigger_obj["linkSource"];
$link_dest_event = $trigger_obj["linkDestEvent"];
$link_dest_field = $trigger_obj["linkDest"];
$trigger_source_fields = $trigger_obj["pipingSourceFields"];
$trigger_source_events = $trigger_obj["pipingSourceEvents"];
$trigger_dest_fields = $trigger_obj["pipingDestFields"];
$trigger_dest_events = $trigger_obj["pipingDestEvents"];
/**
* Move field data from source to destination
*/
foreach($trigger_dest_fields as $i => $dest_field)
{
if (!empty($trigger_source_events[$i]))
{
$source_event = $trigger_source_events[$i];
$key = array_search($source_event, array_column($record_data, "redcap_event_name"));
$data = $record_data[$key];
}
else
{
$data = $record_data[0]; // Takes data from first event
}
if (!empty($trigger_dest_events[$i]))
{
$dest_event = $trigger_dest_events[$i];
}
else // Assume classic project
{
$dest_event = "classic";
}
if (empty($dest_record_data[$dest_event]))
{
$event_data = [];
}
else
{
$event_data = $dest_record_data[$dest_event];
}
$source_field = $trigger_source_fields[$i];
if ($dest_field == "redcap_data_access_group") {
$unique_group_name = $dest_dags[$data[$source_field]];
$value = $unique_group_name;
}
else {
$value = $data[$source_field];
}
$event_data[$dest_field] = $value;
$dest_record_data[$dest_event] = $event_data;
}
/**
* Set destination fields as custom value
*/
$trigger_dest_fields = $trigger_obj["setDestFields"];
$trigger_dest_values = $trigger_obj["setDestFieldsValues"];
$trigger_dest_events = $trigger_obj["setDestEvents"];
foreach($trigger_dest_fields as $i => $dest_field)
{
if (!empty($trigger_dest_events[$i]))
{
$dest_event = $trigger_dest_events[$i];
}
else // Assume classic project
{
$dest_event = "classic";
}
if (empty($dest_record_data[$dest_event]))
{
$event_data = [];
}
else
{
$event_data = $dest_record_data[$dest_event];
}
if ($dest_field == "redcap_data_access_group") {
$unique_group_name = $dest_dags[$trigger_dest_values[$i]];
$value = $unique_group_name;
}
else {
$value = $trigger_dest_values[$i];
}
$event_data[$dest_field] = $value;
$dest_record_data[$dest_event] = $event_data;
}
/**
* Move source instruments to destination instruments.
*/
$trigger_source_instruments = $trigger_obj["sourceInstr"];
$trigger_source_instruments_events = $trigger_obj["sourceInstrEvents"];
$trigger_dest_instruments_events = $trigger_obj["destInstrEvents"];
$dest_dd = REDCap::getDataDictionary($dest_project, "array");
$dest_fields = array_keys($dest_dd);
// Add form completion statuses as fields to consider in the destination project
$dest_form_completion_fields = array_map(function($value) {
return $value . "_complete";
},
array_unique(array_column(array_values($dest_dd), "form_name")));
$dest_fields = array_merge($dest_fields, $dest_form_completion_fields);
foreach($trigger_source_instruments as $i => $source_instrument)
{
if (!empty($trigger_dest_instruments_events[$i]))
{
$dest_event = $trigger_dest_instruments_events[$i];
}
else // Assume destination is classic project.
{
$dest_event = "classic";
}
if (empty($dest_record_data[$dest_event]))
{
$event_data = [];
}
else
{
$event_data = $dest_record_data[$dest_event];
}
// Fields are returned in the order they are in the REDCap project
$source_instrument_fields = REDCap::getFieldNames($source_instrument);
// Add completion status to move with instrument
$source_instrument_fields[] = $source_instrument . "_complete";
// Check for fields that don't exist in the destination project, and remove them
$source_instrument_fields = array_filter($source_instrument_fields, function($v, $k) use ($dest_fields) {
return in_array($v, $dest_fields);
}, ARRAY_FILTER_USE_BOTH);
if (!empty($source_instrument_fields)) {
$source_event = !empty($trigger_source_instruments_events[$i]) ? $trigger_source_instruments_events[$i] : null;
$source_instrument_data = json_decode(REDCap::getData("json", $record, $source_instrument_fields, $source_event), true);
}
if (sizeof($source_instrument_data) > 0)
{
// Remove any REDcap repeat instance fields, as module is currently incompatible
$source_instrument_data = $source_instrument_data[0];
unset($source_instrument_data["redcap_repeat_instrument"], $source_instrument_data["redcap_repeat_instance"]);
$event_data = $event_data + $source_instrument_data;
$dest_record_data[$dest_event] = $event_data;
}
}
if (!empty($dest_record_data) || $trigger_obj["create-empty-record"] == 1)
{
if (empty($dest_record_data))
{
if (empty($link_dest_event))
$dest_record_data["classic"] = [];
else
$dest_record_data[$link_dest_event] = [];
}
// Check if the linking id field is the same as the record id field.
$dest_record_id = $this->framework->getRecordIdField($dest_project);
if ($dest_record_id != $link_dest_field)
{
/**
* Check for existing record, otherwise create a new one. Assume linking ID is unique.
*/
// Search for the index of the linking id's event. If not found, then assume it's a classical project and that the index for the first event is 0.
if (!empty($link_source_event))
{
$key = array_search($link_source_event, array_column($record_data, "redcap_event_name"));
}
else
{
$key = 0;
}
$data = $record_data[$key];
$link_dest_value = $data[$link_source];
if (!empty($trigger_obj["prefixPostfixStr"]))
{
if ($trigger_obj["prefixOrPostfix"] == "post")
$link_dest_value .= $trigger_obj["prefixPostfixStr"];
else
$link_dest_value = $trigger_obj["prefixPostfixStr"] . $link_dest_value;
}
// Set linking id
if (!empty($link_dest_event))
{
$dest_record_data[$link_dest_event][$link_dest_field] = $link_dest_value;
}
else // Assume classic project
{
$dest_record_data["classic"][$link_dest_field] = $link_dest_value;
}
// Retrieve record id. Exit if there is no value for the linking field, as it should be filled and never change.
if (empty($link_dest_value))
{
$this->log("DET Builder: Linking field value is empty, so no data moved. Filter logic: [$link_dest_field] = ''");
return;
}
else
{
$filter_logic = "[$link_dest_field] = '$link_dest_value'";
$existing_record = REDCap::getData($dest_project, "json", null, $dest_record_id, $link_dest_event, null, false, false, false, $filter_logic);
$existing_record = json_decode($existing_record, true);
if (sizeof($existing_record) == 0)
{
$dest_record = REDCap::reserveNewRecordId($dest_project);
}
else
{
$dest_record = $existing_record[0][$dest_record_id];
}
}
}
else
{
$dest_record = $record_data[0][$link_source];
if (!empty($trigger_obj["prefixPostfixStr"]))
{
if ($trigger_obj["prefixOrPostfix"] == "post")
$dest_record .= $trigger_obj["prefixPostfixStr"];
else
$dest_record = $trigger_obj["prefixPostfixStr"] . $dest_record;
}
}
// Set redcap_event_name, record_id, and redcap_data_access_group if $import_dags is true
foreach ($dest_record_data as $redcap_event_name => $data)
{
$dest_record_data[$redcap_event_name][$dest_record_id] = $dest_record;
if ($redcap_event_name != "classic")
{
$dest_record_data[$redcap_event_name]["redcap_event_name"] = $redcap_event_name;
}
if ($import_dags)
{
$dest_record_data[$redcap_event_name]["redcap_data_access_group"] = $record_data[0]["redcap_data_access_group"];
}
}
$dest_record_data = array_values($dest_record_data); // Don't need the keys to push, only the values.
}
if (!empty($dest_record_data))
{
global $Proj;
$SourceProj = $Proj;
// Save DET data in destination project;
$save_response = REDCap::saveData($dest_project, "json", json_encode($dest_record_data), $overwrite_data);
// HOTFIX: For issue where after saveData the global $Proj variable references the destination project context
if ($Proj->project_id !== $project_id) {
$Proj = $SourceProj;
}
if (!empty($save_response["errors"]))
{
$this->log("DET Builder: Errors for Trigger #" . ($index + 1) . " Data not moved. Received the following: " . json_encode($save_response["errors"]));
}
else if (!empty($save_response["warnings"]))
{
$this->log("DET Builder: Moved Data with Warnings for Trigger #" . ($index + 1) . ". Received the following: " . json_encode($save_response["warnings"]));
}
else
{
$this->log("DET Builder: Moved Data for Trigger #" . ($index + 1) . ". Created/modified the following records in PID $dest_project: " . implode(", ", array_unique($save_response["ids"])));
}
/**
* If data was saved without errors then generate survey link and save it to the source project
**/
if (empty($save_response["errors"]))
{
$survey_url_event = $trigger_obj["surveyUrlEvent"];
$survey_url_instrument = $trigger_obj["surveyUrl"];
$save_url_event = $trigger_obj["saveUrlEvent"];
$save_url_field = $trigger_obj["saveUrlField"];