-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDETBuilder.php
More file actions
1736 lines (1492 loc) · 79.4 KB
/
DETBuilder.php
File metadata and controls
1736 lines (1492 loc) · 79.4 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\DETBuilder;
require_once "vendor/autoload.php";
use Dompdf\Dompdf;
use REDCap;
use Project;
class DETBuilder extends \ExternalModules\AbstractExternalModule {
/*
** A class to assist with the DET Builder code.
*/
public $source_project = 0; // a pid
public $source_record = ''; // a record ID in the source project to be parsed by the DETBuilder
public $dest_project = 0; // a pid
public $source_data = array(); // the raw data pulled from the source project
public $source_field_types = array(); // array of field types in source project, key is field name valie is type
public $source_instrument_names = array(); // array keyed by instrument name, with array of fields for that instrument as values
public $dest_field_types = array(); // array of field types in dest project, key is field name value is type
public $dest_instrument_names = array(); // array keyed by instrument name, with array of fields for that instrument as values
public $create_record_trigger = ''; // the trigger to check for record creation
public $link_source_field = ''; // linking field name in source project
public $link_source_event = ''; // linking event in source project
public $link_dest_field = ''; // linking field name in dest project
public $link_dest_event = ''; // linking event in dest project
public $triggers = array(); // array of triggers to check
public $piping_source_events = array(); // events in source project
public $piping_dest_events = array(); // events in dest project
public $piping_source_fields = array(); // fields in source project
public $piping_dest_fields = array(); // fields in dest project
public $set_dest_events = array();
public $set_dest_fields = array();
public $set_dest_fields_values = array();
public $source_to_dest_field_map = array(); // an assoc array of source field name with dest field name as value
public $data_for_transfer = array(); // the data to be written
public $source_instruments_events = array();
public $source_instruments = array();
public $instr_dest_events = array(); // classic -> longitudinal destination event mapping for instruments
public $overwrite_data = '';
public $import_dags = '';
public $source_rows_by_event = []; // ['event_name' => assoc row]
public function loadDETSettings() {
/*
** loads the DET settings from the provided source
*/
// Get DET settings
//$settings = json_decode($this->getProjectSetting("det_settings", $this->source_project), true);
$settings = json_decode($this->getProjectSetting("det_settings"), true);
// REDCap::logEvent("DET Builder: [debug] det_settings read from getProjectSetting", print_r($settings, true), null, $record, null, $project_id);
$this->dest_project = $settings["dest-project"];
$this->create_record_trigger = $settings["create-record-cond"]; // this is never used.
$this->link_source_event = $settings["linkSourceEvent"];
$this->link_source_field = $settings["linkSource"];
$this->link_dest_event = $settings["linkDestEvent"];
$this->link_dest_field = $settings["linkDest"];
$this->triggers = $settings["triggers"];
$this->piping_source_events = $settings["pipingSourceEvents"];
// REDCap::logEvent("DET Builder: [debug] source events", print_r($this->piping_source_events, true), null, $record, null, $project_id);
$this->piping_dest_events = $settings["pipingDestEvents"];
$this->piping_source_fields = $settings["pipingSourceFields"];
//REDCap::logEvent("DET Builder: [debug] source fields", print_r($this->piping_source_fields, true), null, $record, null, $project_id);
$this->piping_dest_fields = $settings["pipingDestFields"];
$this->set_dest_events = $settings["setDestEvents"];
$this->set_dest_fields = $settings["setDestFields"];
$this->set_dest_fields_values = $settings["setDestFieldsValues"];
$this->source_instruments_events = $settings["sourceInstrEvents"];
$this->source_instruments = $settings["sourceInstr"];
// per-instrument dest events mapping
$this->instr_dest_events = isset($settings["instrDestEvents"])
? $settings["instrDestEvents"]
: [];
$this->overwrite_data = $settings["overwrite-data"];
$this->import_dags = $settings["import-dags"];
} // end loadDETSettings()
public function loadFieldTypes() {
/*
** parses the data dictionaries for the two projects and stores them. Stores field name, field_type
*/
$sdd = REDCap::getDataDictionary($this->source_project, 'json'); // source data dict
$source_dd = json_decode($sdd, true);
foreach ($source_dd as $one_source_dd_field) { // load source project field types
$this->source_field_types[$one_source_dd_field['field_name']] = $one_source_dd_field['field_type'];
if (empty($this->source_instrument_names[$one_source_dd_field['form_name']])) { // create form-to-fields mapping
$this->source_instrument_names[$one_source_dd_field['form_name']] = array();
} // end if
array_push($this->source_instrument_names[$one_source_dd_field['form_name']], $one_source_dd_field['field_name']);
} // end foreach
// REDCap::logEvent("DET Builder: [debug] source_instrument_names is now: ", print_r($this->source_instrument_names, true), null, $record, null, $project_id);
$ddd = REDCap::getDataDictionary($this->dest_project, 'json'); // dest data dict
$dest_dd = json_decode($ddd, true);
foreach ($dest_dd as $one_dest_dd_field) { // load dest project field types
$this->dest_field_types[$one_dest_dd_field['field_name']] = $one_dest_dd_field['field_type'];
if (empty($this->dest_instrument_names[$one_dest_dd_field['form_name']])) { // create form-to-fields-mapping
$this->dest_instrument_names[$one_dest_dd_field['form_name']] = array();
} // end if
array_push($this->dest_instrument_names[$one_dest_dd_field['form_name']], $one_dest_dd_field['field_name']);
} // end foreach
// REDCap::logEvent("DET Builder: [debug] in loadFieldTypes() source field types", print_r($this->source_field_types, true), null, $record, null, $project_id);
// REDCap::logEvent("DET Builder: [debug] in loadFieldTypes() dest field types", print_r($this->dest_field_types, true), null, $record, null, $project_id);
} // end loadFieldTypes()
public function mapFieldsAndData() {
/*
** maps the tuples of source field data, destination fields, events into associative
** arrays, and populates the data_for_transfer array with keys named properly for the
** destination project.
*/
/*
** load the source record data from the project
*/
$source_fields_to_read = array_keys($this->source_field_types); // build list of fields to read
// REDCap::logEvent("DET Builder: [debug] source instrument names value: ", print_r($this->source_instrument_names, true), null, $record, null, $project_id);
// just read all the form completion fields - check values later
foreach (array_keys($this->source_instrument_names) as $instr_name) {
$comp_field_name = $instr_name . "_complete";
array_push($source_fields_to_read, $comp_field_name);
}
// Create a map of trigger index -> completion requirements
$trigger_completion_requirements = array();
foreach ($this->triggers as $index => $trigger) {
$checks = $this->extractFormCompletionChecks($trigger);
if (!empty($checks)) {
$trigger_completion_requirements[$index] = $checks;
}
}
// REDCap::logEvent("DET Builder: [debug] in mapFieldsAndData() requesting fields for record " . $this->source_record , print_r($source_fields_to_read, true), null, $record, null, $project_id);
//$raw_source_data = json_decode(REDCap::getData($this->source_project, 'json', $this->source_record, $source_fields_to_read, $this->piping_source_events), true);
$raw_source_data = json_decode(REDCap::getData($this->source_project, 'json', $this->source_record, $source_fields_to_read), true);
// $this->source_data = $raw_source_data[0]; // there can only be a single element of this array
$this->source_rows_by_event = [];
foreach ($raw_source_data as $row) {
$ev = isset($row['redcap_event_name']) ? (string)$row['redcap_event_name'] : '';
$this->source_rows_by_event[$ev] = $row;
}
// Keep a default (first row) for legacy use where event is unspecified
$this->source_data = reset($raw_source_data) ?: [];
// REDCap::logEvent("DET Builder: [debug] in mapFieldsAndData() read source data", print_r($this->source_data, true), null, $record, null, $project_id);
/*
** Build the source to destination field mapping but don't transfer data yet
*/
foreach ($this->piping_source_fields as $i => $source_field_arr) {
foreach ($source_field_arr as $j => $sf_name) {
$this->source_to_dest_field_map[$sf_name] = $this->piping_dest_fields[$i][$j];
}
}
// If full instruments were selected in the settings, include their fields in the transfer.
// $this->source_instruments is an array indexed by trigger containing arrays of instrument names.
// Process each trigger independently - no data is transferred until a trigger's conditions are fully met
foreach ($this->triggers as $triggerIndex => $triggerLogic) {
// Initialize data array specific to this trigger
$trigger_data = array();
// evaluate this trigger's condition
$valid = REDCap::evaluateLogic($triggerLogic, $this->source_project, $this->source_record);
if (!$valid) {
continue; // Skip this entire trigger if its condition isn't met
}
// Check completion requirements for this trigger before processing any data
$trigger_requirements = isset($trigger_completion_requirements[$triggerIndex]) ?
$trigger_completion_requirements[$triggerIndex] : array();
// Verify ALL completion requirements are met
$all_requirements_met = true;
foreach ($trigger_requirements as $reqInstrument => $reqStatus) {
$comp_field = $reqInstrument . '_complete';
if (!isset($this->source_data[$comp_field]) ||
$this->source_data[$comp_field] != $reqStatus) {
$all_requirements_met = false;
break;
}
}
if (!$all_requirements_met) {
continue; // Skip to next trigger if any completion requirement not met
}
// REDCap::logEvent("DET Builder: [debug] Processing trigger $triggerIndex",
// "All conditions met - collecting fields", null, $this->source_record, null, $this->source_project);
// Only now start collecting fields for this trigger
if (isset($this->piping_source_fields[$triggerIndex])) {
// Track which forms we've processed to avoid duplicate _complete fields
$processed_forms = array();
foreach ($this->piping_source_fields[$triggerIndex] as $j => $sf_name) {
$df_name = $this->piping_dest_fields[$triggerIndex][$j];
// Find which form this field belongs to
$field_form = null;
foreach ($this->source_instrument_names as $form_name => $fields) {
if (in_array($sf_name, $fields)) {
$field_form = $form_name;
break;
}
}
if ($this->source_field_types[$sf_name] == 'checkbox') {
// Handle checkbox fields
foreach ($this->source_data as $field_key => $field_value) {
if (str_contains($field_key, $sf_name)) {
$dest_field_name = str_replace($sf_name, $df_name, $field_key);
$trigger_data[$dest_field_name] = $field_value;
}
}
} else {
// Handle regular fields
if (array_key_exists($sf_name, $this->source_data)) {
$trigger_data[$df_name] = $this->source_data[$sf_name];
}
}
// Include the form completion status if we haven't already for this form
if ($field_form && !in_array($field_form, $processed_forms)) {
$comp_field = $field_form . '_complete';
if (array_key_exists($comp_field, $this->source_data)) {
$trigger_data[$comp_field] = $this->source_data[$comp_field];
$processed_forms[] = $field_form;
}
}
}
}
// Extract and verify completion requirements for this trigger
$trigger_requirements = isset($trigger_completion_requirements[$triggerIndex]) ?
$trigger_completion_requirements[$triggerIndex] : array();
// Check all completion requirements before processing any data
foreach ($trigger_requirements as $reqInstrument => $reqStatus) {
$comp_field = $reqInstrument . '_complete';
if (!isset($this->source_data[$comp_field]) ||
$this->source_data[$comp_field] != $reqStatus) {
continue 2; // Skip to next trigger
}
}
// Process instrument fields if this trigger has any
if (!empty($this->source_instruments[$triggerIndex])) {
foreach ($this->source_instruments[$triggerIndex] as $instrumentName) {
if (empty($this->source_instrument_names[$instrumentName])) continue;
// Process each field in the instrument
foreach ($this->source_instrument_names[$instrumentName] as $fieldName) {
// Skip if already handled by explicit field mapping
if (array_key_exists($fieldName, $trigger_data)) continue;
$fieldType = isset($this->source_field_types[$fieldName]) ? $this->source_field_types[$fieldName] : '';
if ($fieldType === 'checkbox') {
foreach ($this->source_data as $sourceKey => $sourceValue) {
if (strpos($sourceKey, $fieldName) === 0) {
$trigger_data[$sourceKey] = $sourceValue;
}
}
} else if (array_key_exists($fieldName, $this->source_data)) {
$trigger_data[$fieldName] = $this->source_data[$fieldName];
}
}
// Include the form completion status field for this instrument
$comp_field = $instrumentName . '_complete';
if (array_key_exists($comp_field, $this->source_data)) {
$trigger_data[$comp_field] = $this->source_data[$comp_field];
}
}
}
// If we collected any data for this trigger, transfer it
if (!empty($trigger_data)) {
foreach ($trigger_data as $field => $value) {
$this->data_for_transfer[$field] = $value;
}
REDCap::logEvent("DET Builder: [debug] Trigger $triggerIndex succeeded",
"Trigger condition: $triggerLogic\nTransferred fields: " . implode(", ", array_keys($trigger_data)),
null, $this->source_record, null, $this->source_project);
} else {
REDCap::logEvent("DET Builder: [debug] Trigger $triggerIndex - no fields to transfer",
"Trigger condition met but no fields collected",
null, $this->source_record, null, $this->source_project);
}
} // end foreach ($this->triggers as $triggerIndex => $triggerLogic)
// print "<pre>source->dest field mapping: " . print_r($this->source_to_dest_field_map, true) . "</pre>\n";
} // end mapFieldsAndData()
public function initializeObject($source_pid, $record) { // external module code is unhappy with constructors, so this is an actively-called function.
$this->source_project = $source_pid; // set the source project id
$this->source_record = $record; // set record in the DETBuilder object
$this->loadDETSettings(); // get the DET settings from project metadata
$this->loadFieldTypes(); // load the types of fields for the source and dest projects, keyed by field name
$this->mapFieldsAndData(); // load the data for this record, and map it into its proper name for the destination project
} // end init()
/**
* 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) {
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;
} // end replaceStrings()
/**
* 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;
} // end getSyntaxParts()
/**
* Extract form completion checks from a trigger condition.
* Returns an array of form names and their expected completion values.
*
* @access private
* @param String $trigger The trigger condition to analyze
* @return Array Array of form names mapped to their expected completion values
*/
private function extractFormCompletionChecks($trigger) {
$parts = $this->getSyntaxParts($trigger);
$checks = array();
for($i = 0; $i < count($parts); $i++) {
$part = $parts[$i];
// Look for patterns like [form_complete] = 2
if($part === '[' && isset($parts[$i + 1]) && isset($parts[$i + 2]) &&
substr($parts[$i + 1], -9) === '_complete') {
$form = substr($parts[$i + 1], 0, -9);
if(isset($parts[$i + 3]) && isset($parts[$i + 4])) {
if(in_array($parts[$i + 3], array('=', '=='))) {
// Remove any quotes from the value
$value = trim($parts[$i + 4], "'\"");
$checks[$form] = $value;
}
}
}
}
return $checks;
}
/**
* 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;
} // end validateSyntax()
/**
* 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;
} // end getProjects()
/**
* Retrieves a project's fields
*
* @param String $pid A project's id in REDCap.
* @return String A JSON encoded string that contains all the instruments and fields for a project.
*/
public function retrieveProjectMetadata($pid) {
if (!empty($pid))
{
$metadata = REDCap::getDataDictionary($pid, "array");
$instruments = array_unique(array_column($metadata, "form_name"));
$Proj = new Project($pid);
$events = array_values($Proj->getUniqueEventNames());
$isLongitudinal = $Proj->longitudinal;
/**
* We can pipe over any data except descriptive fields.
*
* NOTE: For calculation fields only the raw data can be imported/exported.
*/
foreach($metadata as $field_name => $data)
{
if ($data["field_type"] != "descriptive" && $data["field_type"] != "calc")
{
$fields[] = $field_name;
}
}
/**
* Add form completion status fields to push
*/
foreach($instruments as $instrument)
{
$fields[] = $instrument . "_complete";
}
$return_value = array("fields" => $fields, "events" => $events, "isLongitudinal" => $isLongitudinal);
// $json_return_value = json_encode($return_value);
// print ("<!-- in retrieveProjectMetadata value to be returned as json is: " . print_r($json_return_value, true) . "-->\n");
// return $json_return_value;
// PATCHED 2025-06-02 by Dan Evans. Trying to make a json error go away.
//*/
return ["fields" => $fields, "events" => $events, "isLongitudinal" => $isLongitudinal];
}
return FALSE;
} // end retrieveProjectMetadata()
/**
* 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();
$instruments = array_unique(array_column($data_dictionary, "form_name"));
foreach ($instruments as $unique_name)
{
$external_fields[] = "{$unique_name}_complete";
}
return in_array($var, $external_fields) || in_array($var, $fields);
}
/**
* 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, "'");
$Proj = new Project($pid);
$events = array_values($Proj->getUniqueEventNames());
/*
** PATCHED 2025-06-04 by Dan Evans. Newer redcap versions will use event_1_arm_1 as a value even if there are no defined events
*/
if (sizeof($events) == 0) { // no defined events, need to add a dummy event_1_arm_1 value
$events[] = 'event_1_arm_1';
} // end if
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);
}
private function debugToFile($message, $data = null)
{
$logDir = __DIR__ . '/logs';
if (!is_dir($logDir)) {
mkdir($logDir, 0775, true);
}
$logFile = $logDir . '/det_debug.log';
$timestamp = date('Y-m-d H:i:s');
$output = "[$timestamp] $message\n";
if ($data !== null) {
if (is_array($data) || is_object($data)) {
$output .= print_r($data, true);
} else {
$output .= $data . "\n";
}
}
$output .= str_repeat('-', 80) . "\n";
file_put_contents($logFile, $output, FILE_APPEND);
}
// Return the array key for an event row ('' for classic)
private function eventKey($isLongitudinal, $event) {
return $isLongitudinal ? (string)$event : '';
}
//
private function resolveDestinationRecordId(\Project $projDest, $linkValue): ?string {
$destPkField = (string) $projDest->table_pk;
$isLongitudinal = (bool) $projDest->longitudinal;
if ($linkValue === null || $linkValue === '') {
return null;
}
// if link field is the destination pk, linkage is direct
if ($this->link_dest_field === $destPkField) {
return (string) $linkValue;
}
$safe = str_replace("'", "\\'", (string) $linkValue);
$filterLogic = sprintf("[%s] = '%s'", $this->link_dest_field, $safe);
$eventsToRead = null;
if ($isLongitudinal && !empty($this->link_dest_event)) {
$eventsToRead = [$this->link_dest_event];
}
$raw = json_decode(
REDCap::getData(
$this->dest_project,
'json',
null,
[$destPkField, $this->link_dest_field],
$eventsToRead,
null,
false,
false,
false,
$filterLogic
),
true
) ?: [];
if (!empty($raw[0][$destPkField])) {
return (string) $raw[0][$destPkField];
}
return null;
}
// Ensure a row exists in $rowsByEvent and has link id (+ event for longitudinal)
private function ensureRow(
array &$rowsByEvent,
$key,
string $destPkField,
?string $destRecordId,
string $linkDestField,
$linkValue,
bool $isLongitudinal,
string $event
) {
if (!isset($rowsByEvent[$key])) {
$rowsByEvent[$key] = [];
// Only set destination PK now if already known.
if ($destRecordId !== null && $destRecordId !== '') {
$rowsByEvent[$key][$destPkField] = $destRecordId;
}
$shouldWriteLinkField =
$linkDestField !== $destPkField &&
$linkValue !== null &&
$linkValue !== '' &&
(
!$isLongitudinal ||
$event === (string) $this->link_dest_event
);
if ($shouldWriteLinkField) {
$rowsByEvent[$key][$linkDestField] = $linkValue;
}
if ($isLongitudinal && $event !== '') {
$rowsByEvent[$key]['redcap_event_name'] = $event;
}
}
}
// Add field checkbox
private function addFieldToRow(array &$row, $srcField, $destField, string $destPkField, array $sourceData, array $sourceFieldTypes, array $sourceInstrumentNames) {
// Never overwrite destination PK with copied data
if ($destField === $destPkField) {
return;
}
if (($sourceFieldTypes[$srcField] ?? '') === 'checkbox') {
foreach ($sourceData as $k => $v) {
if (strpos($k, $srcField . '___') === 0) {
$row[$destField . substr($k, strlen($srcField))] = $v;
}
}
} else {
if (array_key_exists($srcField, $sourceData)) {
$row[$destField] = $sourceData[$srcField];
}
}
}
// Add an entire instrument (+ its _complete) to the row, except for the destination PK field
private function addInstrumentToRow(array &$row, $instrument, string $destPkField, array $sourceData, array $sourceFieldTypes, array $sourceInstrumentNames) {
$fields = $sourceInstrumentNames[$instrument] ?? [];
foreach ($fields as $f) {
if ($f === $destPkField) {
continue;
}
$type = $sourceFieldTypes[$f] ?? '';
if ($type === 'checkbox') {
foreach ($sourceData as $k => $v) {
if (strpos($k, $f . '___') === 0) {
$row[$k] = $v;
}
}
} else {
if (array_key_exists($f, $sourceData)) {
$row[$f] = $sourceData[$f];
}
}
}
$cf = $instrument . '_complete';
if (isset($sourceData[$cf])) {
$row[$cf] = $sourceData[$cf];
}
}
public function redcap_save_record($project_id, $record, $instrument, $event_id, $group_id, $survey_hash, $response_id, $repeat_instance) {
$this->debugToFile('HOOK redcap_save_record() called', [
'project_id' => $project_id,
'record' => $record,
'instrument' => $instrument,
'event_id' => $event_id,
'group_id' => $group_id,
'repeat_instance' => $repeat_instance
]);
$det = new DETBuilder(); // make a new DETBuilder object and load the relevant data
$det->initializeObject($project_id, $record);
$this->debugToFile('DET snapshot', [
'dest_project' => $det->dest_project,
'link_source_event' => $det->link_source_event,
'link_source_field' => $det->link_source_field,
'link_dest_event' => $det->link_dest_event,
'link_dest_field' => $det->link_dest_field,
'overwrite' => $det->overwrite_data,
'import_dags' => $det->import_dags,
'triggers_count' => is_array($det->triggers) ? count($det->triggers) : 0
]);
// $this->debugToFile('Source data keys', array_keys($det->source_data ?? []));
if ($project_id == $this->getProjectId()) {
// $this->debugToFile("Comparing project_id to getProjectID", [
// 'project_id' => $project_id,
// 'getProjectId' => $this->getProjectId()
// ]);
$ProjDest = new \Project($det->dest_project);
$isLongitudinal = (bool) $ProjDest->longitudinal;
$destPkField = (string) $ProjDest->table_pk;
// Resolve source link value once per save.
$srcLinkEvent = (string) ($det->link_source_event ?? '');
$srcRowForLink = $det->source_rows_by_event[$srcLinkEvent]
?? $det->source_rows_by_event['']
?? $det->source_data;
$linkValue = $srcRowForLink[$det->link_source_field] ?? null;
// Resolve destination record once per save.
$destRecordId = $det->resolveDestinationRecordId($ProjDest, $linkValue);
foreach($det->triggers as $index => $trigger) {
// $this->debugToFile("Trigger[$index] evaluate", $trigger);
$valid = REDCap::evaluateLogic($trigger, $project_id, $record); // REDCap class method to evaluate conditional logic.
// $this->debugToFile("Trigger[$index] evaluateLogic result", var_export($valid, true));
if ($valid === null) {
REDCap::logEvent("DET: Trigger was either syntactically incorrect, or parameters were invalid (e.g., record or event does not exist). No data moved.", "Trigger: $trigger", null, $record, $event_id, $project_id);
continue;
}
if ($valid === false) {
continue;