-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandapi.php
1018 lines (919 loc) · 43.9 KB
/
Randapi.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 redcapuzgent\Randapi;
require_once __DIR__.DIRECTORY_SEPARATOR."vendor/autoload.php";
use \ExternalModules\AbstractExternalModule;
use \Exception;
use \Randomization;
use \stdClass;
use redcapuzgent\Randapi\model\RandomizationAllocation;
use redcapuzgent\Randapi\model\RandomizationField;
use redcapuzgent\Randapi\model\RandapiException;
class Randapi extends AbstractExternalModule
{
private $contentType = "json";
public function __construct(){
parent::__construct();
}
/**
* Initializes global variables, used by Randomization::randomizeRecord
* @param string $recordId The record that we want to randomize
* @param int $projectId The projectId where the record belongs to
* @throws Exception
*/
private function initRandomizeRecord(string $recordId,int $projectId){
// set globals required for Randomization::getRandomizationFields;
global $redcap_version;
$classesPath = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR."redcap_v$redcap_version".DIRECTORY_SEPARATOR."Classes".DIRECTORY_SEPARATOR;
require_once($classesPath."Randomization.php");
if(!defined(PROJECT_ID)){
error_log("defining project id $projectId");
define(PROJECT_ID,$projectId);
}else{
error_log("project id was already defined");
}
global $longitudinal;
if(!isset($longitudinal)){
error_log("defining longitudinal");
//echo "requiring $classesPath"."Project.php";
require_once($classesPath."Project.php");
$proj = new \Project($projectId, true);
$longitudinal = $proj->longitudinal;
}else{
error_log("longitudinal was already defined");
}
// set globals required for Randomization::randomizeRecord()
global $status;
if(!isset($status)){
error_log("defining status");
Randomization::wasRecordRandomized($recordId);
}else{
error_log("status was already defined");
}
}
/**
* @param string $recordId The record that we want to randomize
* @param int $projectId The projectId where the record belongs to
* @param RandomizationField[] $fields An array of RandomizationFields
* @param string $resultFieldName The field where the randomization result can be stored.
* @param string $group_id (optional) The DAG identifier. default = '' (none)
* @param string $arm_name (optional) The name of the arm. default = 'Arm 1'
* @param string $event_name (optional) The name of the event. default = 'Event 1'
* @return string returns the field value result of the randomization
* @throws Exception
*/
function randomizeRecord(string $recordId,int $projectId,array $fields=array(),string $resultFieldName,string $group_id='',string $arm_name='Arm 1', string $event_name='Event 1'): string{
$this->initRandomizeRecord($recordId, $projectId);
$tfields = array();
foreach($fields as $field) {
$tfields[$field->getKey()] = $field->getValue();
}
error_log("randomizing using fields ".print_r($tfields,true));
// calls Randomization::getRandomizationFields
$aid = Randomization::randomizeRecord($recordId,$tfields,$group_id);
if($aid){
// retrieve randomization value (target_field)
// SQL Inject check
// ----------------
// $aid is a method result
$query = "select target_field from redcap_randomization_allocation rra where rra.aid = $aid";
$randomizationQueryResult = $this->query($query);
$randomizationResult = null;
if($row = $randomizationQueryResult->fetch_assoc()){
$randomizationResult = $row["target_field"];
}
$randomizationQueryResult->close();
if(!is_null($randomizationResult)){
// The randomization result cannot be changed so an insert should not fail because of an duplicate row exception.
// The API cannot be used to insert the randomization result
// SQL Injection check
// -------------------
// $projectId is int in method signature
// $recordId should be escaped
$recordId = db_real_escape_string($recordId);
// $resultFieldName should be escaped
$resultFieldName = db_real_escape_string($resultFieldName);
// $randomizationResult is not passed by a parameter
// $event_name should be escaped
$event_name = db_real_escape_string($event_name);
// $arm_name should be escaped
$arm_name = db_real_escape_string($arm_name);
$query = "
insert into redcap_data(project_id, event_id, record, field_name, `value`)
select $projectId as project_id, md.event_id, '$recordId' as record, '$resultFieldName' as field_name, '$randomizationResult' as `value`
from redcap_events_arms a
join redcap_events_metadata md on
a.arm_id = md.arm_id and
md.descrip = '$event_name'
where a.project_id = $projectId and
a.arm_name='$arm_name';";
error_log("Executing query $query");
if($this->query($query)){
error_log("Randomization result $randomizationResult for aid $aid successfully saved in record");
return $randomizationResult;
}else{
$msg = "Could not save randomization result $randomizationResult for aid $aid. ".mysqli_error($this->conn);
error_log($msg);
throw new Exception($msg);
}
}else {
$msg = "No result found for aid $aid";
error_log($msg);
throw new Exception($msg);
}
}else{
throw new Exception("Standard Randomization class could not randomize record");
}
}
/**
* @param $criteriaFields
* @param array $fields
* @param string $group_id
* @param $currentTargetField
* @return int 0 in case of no value.
*/
function getFreeAllocationRecordForTarget($criteriaFields,$fields=array(),$group_id='',$currentTargetField){
global $status;
$tfields = array();
foreach($fields as $field) {
$tfields[$field->getKey()] = $field->getValue();
}
// Create sql subquery for DAG
$sqlsub = "and a.group_id" . (is_numeric($group_id) ? " = $group_id " : " is null ");
// Create sql subquery for strata critera
foreach ($criteriaFields as $col=>$field) {
$sqlsub .= "and a.$col = '".db_escape($tfields[$field])."' ";
}
// extra criteria: target_field = $currentTargetField
$sqlsub .= "and a.target_field = '$currentTargetField' ";
// Query to get an aid key for these field value combinations
$sql = "select a.aid from redcap_randomization_allocation a, redcap_randomization r
where r.project_id = " . PROJECT_ID . " and r.rid = a.rid and a.project_status = $status
and a.is_used_by is null $sqlsub order by a.aid limit 1";
error_log("executing query $sql");
$q = db_query($sql);
if (db_num_rows($q) < 1) {
// Return as 0 to give error message about being already allocated
return 0;
} else {
// Get the NEXT aid matching our criteria
$aid = db_result($q, 0);
return $aid;
}
}
/**
* Due to wrong registration, it might be necessary to change the source fields that are used to randomize a record.
* This can be done using the following steps
* 1) Check if an allocation record is available for the given recorid
* 2) Collect the current target_field value.
* 3) Look for a new allocation record (aid) for the new source_field values but for the same target_field.
* 4) Select the first free allocation. If none available, add new ones as defined in $newAllocations and select first (aid)
* 5) Update is_used_by field for the current allocation to null, update the new allocation to the new found aid.
* 6) Update the source field values in the record
*
* @param string $recordId
* @param int $projectId
* @param RandomizationField[] $fields
* @param string $group_id
* @param RandomizationAllocation[] $allocations These allocations will be added if no allocations are available for the given combination of source fields and the target field.
* @param string $arm_name (optional) The name of the arm. default = 'Arm 1'
* @param string $event_name (optional) The name of the event. default = 'Event 1'
* @return int
* @throws Exception
*/
function changeSources(string $recordId,int $projectId,$fields=array(),array $allocations,$group_id='',string $arm_name='Arm 1', string $event_name='Event 1'){
error_log("init change sources");
$this->initRandomizeRecord($recordId, $projectId);
global $status;
$recordId = db_real_escape_string($recordId);
// What is the current target_field value?
$currentTargetFieldQuery = $this->query("SELECT ra.target_field, ra.aid
FROM redcap_randomization r
join redcap_randomization_allocation ra on
ra.rid = r.rid and
ra.is_used_by = '$recordId' and
ra.project_status = $status
where r.project_id = $projectId");
if($row = $currentTargetFieldQuery->fetch_assoc()){
$currentTargetField = $row["target_field"];
$currentAid = $row["aid"];
error_log("Received current target field $currentTargetField and current aid $currentAid");
// copy of Randomization::randomizeRecord
// Ensure that fields have all correct criteria fields. If not, return false to throw AJAX error msg.
$criteriaFieldsOk = true;
$criteriaFields = Randomization::getRandomizationFields(false,true);
if (count($fields) != count($criteriaFields)) $criteriaFieldsOk = false;
foreach (array_keys($fields) as $field) {
if (!in_array($field, $criteriaFields)) $criteriaFieldsOk = false;
}
if(!$criteriaFieldsOk){
throw new Exception("The given criteria fields are not valid");
}
error_log("criteria fields are oké.");
$newAid = $this->getFreeAllocationRecordForTarget($criteriaFields, $fields, $group_id, $currentTargetField);
if($newAid == 0) {
error_log("No allocations are present");
if (is_array($allocations) && sizeof($allocations) > 0) {
error_log("Adding new allocations");
$this->addRecordsToAllocationTable($projectId, $status, $allocations);
$newAid = $this->getFreeAllocationRecordForTarget($criteriaFields, $fields, $group_id, $currentTargetField);
} else {
throw new RandapiException('No free allocation was available and no allocations were passed through the $allocations argument');
}
}
if($newAid != 0){
error_log("Found a new aid $newAid");
// No need to change the target_field value in redcap_data. This remains the same.
if(!$this->query("update redcap_randomization_allocation set is_used_by = null where aid = '$currentAid' and is_used_by = '$recordId'")){
throw new RandapiException("Could not unset is_used_by for aid $currentAid");
}
error_log("updated is_used_by from old aid $currentAid to null");
if(!$this->query("update redcap_randomization_allocation set is_used_by = '$recordId' where aid = $newAid;")){
throw new RandapiException("Could not set is_used_by for aid $newAid");
}
error_log("updated is_used_by from new aid $newAid to $recordId");
// update the source fields in the record
$i = 0;
foreach($fields as $sourcefield){
$updateQuery = "
update redcap_data rd
join redcap_events_metadata md on
md.event_id = rd.event_id and
md.descrip = '$event_name'
join redcap_events_arms a on a.arm_id = md.arm_id and
a.arm_name = '$arm_name'
join redcap_randomization_allocation cura on
cura.aid = $currentAid and
cura.source_field".($i+1)." = rd.value
join redcap_randomization_allocation newa on newa.aid = $newAid
set rd.value = newa.source_field".($i+1)."
where rd.project_id = $projectId and
rd.record = '$recordId' and
rd.field_name = '".$sourcefield->getKey()."'
";
error_log("Executing query $updateQuery");
if(!$this->query($updateQuery)){
throw new RandapiException("Could not update field $i '".$sourcefield->getKey()."' to value '".$sourcefield->getValue()."' for project $projectId, record $recordId, event $event_name and arm $arm_name from aid $currentAid to aid $newAid");
}else{
error_log("updated field $i '".$sourcefield->getKey()."' to value '".$sourcefield->getValue()."' for project $projectId, record $recordId, event $event_name and arm $arm_name from aid $currentAid to aid $newAid");
}
$i++;
}
return $newAid;
}else{
throw new RandapiException("Could not find an empty allocation record for the given target and source fields");
}
}else{
throw new RandapiException("Record $recordId has not yet been randomized");
}
}
/**
* In limited cases it might be necessary to change the outcome of the randomization. E.g. in an automated process a record was assigned to a certain target group.
* Due to some manual changes, the record is unrandomized. Correcting the error and randomizing the record again, results in a different target value.
* This can be done using the following steps
* 1) Check if an allocation record is available for the given recorid
* 2) Collect the current source_field value.
* 3) Look for a new allocation record (aid) for the new source_field values but for the same target_field.
* 4) Select the first free allocation. If none available, add new ones as defined in $newAllocations and select first (aid)
* 5) Update is_used_by field for the current allocation to null, update the new allocation to the new found aid.
* 6) Update the source field values in the record
*
* @param string $recordId
* @param int $projectId
* @param string $new_target The new target value
* @param string $group_id
* @param RandomizationAllocation[] $allocations These allocations will be added if no allocations are available for the given combination of source fields and the target field.
* @param string $arm_name (optional) The name of the arm. default = 'Arm 1'
* @param string $event_name (optional) The name of the event. default = 'Event 1'
* @return int
* @throws Exception
*/
function changeTarget(string $recordId,int $projectId,string $new_target,array $allocations,$group_id='',string $arm_name='Arm 1', string $event_name='Event 1'){
error_log("init change target");
$this->initRandomizeRecord($recordId, $projectId);
global $status;
$recordId = db_real_escape_string($recordId);
/**
* @var $source_fields array key value array with key source_fieldx and value the source_field's name
*/
$source_fields = Randomization::getRandomizationFields(false,true);
$source_field_columns = array_keys($source_fields);
for($i = 0; $i < sizeof($source_field_columns); $i++){
$source_field_columns[$i]="ra.".$source_field_columns[$i];
}
// What is the current target_field value?
$currentTargetFieldQuery = $this->query("SELECT ra.aid, ".implode(',',$source_field_columns)."
FROM redcap_randomization r
join redcap_randomization_allocation ra on
ra.rid = r.rid and
ra.is_used_by = '$recordId' and
ra.project_status = $status
where r.project_id = $projectId");
if($row = $currentTargetFieldQuery->fetch_assoc()){
// copy of Randomization::randomizeRecord
// Ensure that fields have all correct criteria fields. If not, return false to throw AJAX error msg.
$criteriaFieldsOk = true;
$criteriaFields = Randomization::getRandomizationFields(false,true);
//create RandomizationField objects
/**
* @var $source_fields_rf RandomizationField[]
*/
$source_fields_rf = array();
foreach(array_keys($source_fields) as $source_field){
$source_fields_rf[] = new RandomizationField($criteriaFields[$source_field], strval($row[$source_field]));
}
$currentAid = $row["aid"];
$source_fields_str = array();
foreach($source_fields_rf as $rf){
$source_fields_str[] = $rf->getKey()." => ".$rf->getValue();
}
error_log("Received current source fields ".implode(",",$source_fields_str)." and current aid $currentAid");
if (count($source_fields_rf) != count($criteriaFields)) $criteriaFieldsOk = false;
foreach (array_keys($source_fields_rf) as $field) {
if (!in_array($field, $criteriaFields)) $criteriaFieldsOk = false;
}
if(!$criteriaFieldsOk){
throw new Exception("The given criteria fields are not valid");
}
error_log("criteria fields are oké.");
$newAid = $this->getFreeAllocationRecordForTarget($criteriaFields, $source_fields_rf, $group_id, $new_target);
if($newAid == 0) {
error_log("No allocations are present");
if (is_array($allocations) && sizeof($allocations) > 0) {
error_log("Adding new allocations");
$this->addRecordsToAllocationTable($projectId, $status, $allocations);
$newAid = $this->getFreeAllocationRecordForTarget($criteriaFields, $source_fields_rf, $group_id, $new_target);
} else {
throw new RandapiException('No free allocation was available and no allocations were passed through the $allocations argument');
}
}
if($newAid != 0){
error_log("Found a new aid $newAid");
// No need to change the target_field value in redcap_data. This remains the same.
if(!$this->query("update redcap_randomization_allocation set is_used_by = null where aid = '$currentAid' and is_used_by = '$recordId'")){
throw new RandapiException("Could not unset is_used_by for aid $currentAid");
}
error_log("updated is_used_by from old aid $currentAid to null");
if(!$this->query("update redcap_randomization_allocation set is_used_by = '$recordId' where aid = $newAid;")){
throw new RandapiException("Could not set is_used_by for aid $newAid");
}
error_log("updated is_used_by from new aid $newAid to $recordId");
// update the target field in the record
$randomization_fields = Randomization::getRandomizationFields(false,false);
$updateQuery = "
update redcap_data rd
join redcap_events_metadata md on
md.event_id = rd.event_id and
md.descrip = '$event_name'
join redcap_events_arms a on
a.arm_id = md.arm_id and
a.arm_name = '$arm_name'
join redcap_randomization_allocation newa on newa.aid = $newAid
set rd.value = newa.target_field
where rd.project_id = $projectId and
rd.record = '$recordId' and
rd.field_name = '".$randomization_fields["target_field"]."'
";
error_log("Executing query $updateQuery");
if(!$this->query($updateQuery)){
throw new RandapiException("Could not update target_field to value '".$new_target."' for project $projectId, record $recordId, event $event_name and arm $arm_name from aid $currentAid to aid $newAid");
}else{
error_log("updated target_field to value '".$new_target."' for project $projectId, record $recordId, event $event_name and arm $arm_name from aid $currentAid to aid $newAid");
}
return $newAid;
}else{
throw new RandapiException("Could not find an empty allocation record for the given target and source fields");
}
}else{
throw new RandapiException("Record $recordId has not yet been randomized");
}
}
/**
* @param int $projectId The project id
* @param int $project_status (0 = development, 1 = production)
* @param RandomizationAllocation[] $allocations
* @throws Exception
*/
public function addRecordsToAllocationTable(int $projectId,int $project_status,array $allocations): void{
// SQL injection check
// -------------------
// $projectId is typed in method signature
$ridQuery = "select rid from redcap_randomization where project_id = $projectId";
$rid = false;
try{
if($ridQueryResult = $this->query($ridQuery)){
if($row = $ridQueryResult->fetch_assoc()){
$rid = $row["rid"];
}
$ridQueryResult->close();
}else{
$msg = "Could not execute ridQuery $ridQuery. ";
error_log($msg);
}
}catch(\Exception $e){
$msg = "Could not execute ridQuery $ridQuery. ".$e->getMessage()." ".$e->getTraceAsString();
error_log($msg);
}
if($rid) {
foreach ($allocations as $allocation) {
$sourceFieldNames = $allocation->getSourceFieldNames();
// SQL Injection check
// -------------------
// $sourceFieldNames is generated here
// $rid is a database result
// $project_status is typed (int) in the method signature
// $allocation->getTargetField() should be escaped
$target_field = db_real_escape_string($allocation->getTargetField());
// $allocation->getSourceFields() should be escaped
$sourceFieldValues = $allocation->getSourceFieldValues();
$query = "
insert into redcap_randomization_allocation(rid,project_status,target_field," . implode(',', $sourceFieldNames) . ")
values($rid,$project_status,'$target_field','" . implode("','", $sourceFieldValues) . "');";
error_log("Executing query: $query");
if (!$this->query($query)) {
throw new Exception("Could not add allocation values to table for query: $query. Exception: " . mysqli_error($this->conn));
}
}
}else{
throw new Exception("Could not find rid");
}
}
/**
* @param $jsonObject
* @throws RandapiException | Exception
*/
private function handleAddAllocation($jsonObject): void{
if(!property_exists($jsonObject,"parameters")){
throw new RandapiException("parameters property not found.");
}
if(!property_exists($jsonObject->parameters, "project_status")){
throw new RandapiException("parameters->project_status property not found.");
}
if(!is_numeric($jsonObject->parameters->project_status)){
throw new RandapiException("parameters->project_status is not numeric.");
}
if(!in_array($jsonObject->parameters->project_status, array(0,1))){
throw new RandapiException("parameters->project_status does not have values 0 or 1.");
}
if(!property_exists($jsonObject->parameters, "allocations")){
throw new RandapiException("parameters->project_status property not found.");
}
if(!is_array($jsonObject->parameters->allocations)){
throw new RandapiException("parameters->project_status is not an array.");
}
$allocations = array();
foreach($jsonObject->parameters->allocations as $allocation){
array_push($allocations,RandomizationAllocation::fromstdClass($allocation));
}
$this->addRecordsToAllocationTable($this->getProjectId(),
$jsonObject->parameters->project_status,
$allocations);
}
/**
* @param $jsonObject
* @return string
* @throws RandapiException
*/
private function handleRandomization($jsonObject): string{
if(!property_exists($jsonObject,"parameters")){
throw new RandapiException("parameters property not found.");
}
if(!property_exists($jsonObject->parameters, "recordId")){
throw new RandapiException("parameters->recordId property not found.");
}
if(!property_exists($jsonObject->parameters, "fields")){
throw new RandapiException("parameters->fields property not found.");
}
if(!property_exists($jsonObject->parameters, "resultFieldName")){
throw new RandapiException("parameters->resultFieldName property not found.");
}
// optional
$groupId = "";
if(property_exists($jsonObject->parameters, "groupId")){
$groupId = $jsonObject->parameters->groupId;
}
$armName = "Arm 1";
if(property_exists($jsonObject->parameters, "armName")){
$groupId = $jsonObject->parameters->armName;
}
$eventName = "Event 1";
if(property_exists($jsonObject->parameters, "eventName")){
$eventName = $jsonObject->parameters->eventName;
}
$fields = array();
foreach($jsonObject->parameters->fields as $field){
array_push($fields,RandomizationField::fromStdClass($field));
}
//randomizeRecord($recordId,$projectId,$fields=array(),$resultFieldName,$group_id='',$arm_name='Arm 1', $event_name='Event 1'){
return $this->randomizeRecord($jsonObject->parameters->recordId,
$this->getProjectId(),
$fields,
$jsonObject->parameters->resultFieldName,
$groupId,$armName,$eventName);
}
/**
* @param stdClass $jsonObject
* @return int
* @throws RandapiException
*/
private function handleAvailableSlots(stdClass $jsonObject): int {
if(!property_exists($jsonObject,"parameters")){
throw new RandapiException("parameters property not found.");
}
if(!property_exists($jsonObject->parameters, "source_fields")){
throw new RandapiException("parameters->source_fields property not found.");
}
/**
* @var $source_fields string[]
*/
$source_fields = $jsonObject->parameters->source_fields;
$sourceWhere = array();
for($i = 0; $i < sizeof($source_fields); $i++){
array_push($sourceWhere,"rra.source_field".($i+1)." = '".$source_fields[$i]."'");
}
$asQuery = "select count(*) as nrOfAvailableSlots
from redcap_randomization_allocation rra
join redcap_randomization rr on
rr.project_id = ".$this->getProjectId()." and
rr.rid = rra.rid
where rra.is_used_by is null and
".implode(" and ",$sourceWhere);
if($ridQueryResult = $this->query($asQuery)) {
if ($row = $ridQueryResult->fetch_assoc()) {
$ridQueryResult->close();
return intval($row["nrOfAvailableSlots"]);
}else{
$ridQueryResult->close();
throw new RandapiException("query did not return a result: $asQuery");
}
}else{
throw new RandapiException("Could not execute query: $asQuery");
}
}
/**
* @param stdClass $jsonObject
* @param string $jsonText
* @throws RandapiException
*/
public function handleRequest(stdClass $jsonObject, string $jsonText):void{
if($this->checkToken($jsonObject)){
if(property_exists($jsonObject,"action")){
switch($jsonObject->action){
case "addRecordsToAllocationTable":
$this->handleAddAllocation($jsonObject);
echo json_encode("success");
break;
case "randomizeRecord":
$foundAid =$this->handleRandomization($jsonObject);
echo json_encode("$foundAid");
break;
case "availableSlots":
$nrOfAvaibaleSlots = $this->handleAvailableSlots($jsonObject);
echo json_encode($nrOfAvaibaleSlots);
break;
case "findAID":
$aid = $this->handleFindAID($jsonObject);
echo json_encode($aid);
break;
case "undoRandomization":
$this->handleUndoRandomization($jsonObject);
echo json_encode("success");
break;
case "changeSources":
$newAid = $this->handleChangeSources($jsonObject);
echo json_encode($newAid);
break;
case "changeTarget":
$newAid = $this->handleChangeTarget($jsonObject);
echo json_encode($newAid);
break;
case "readConfiguration": $this->readConfiguration($jsonObject);
break;
case "readAllocations": $this->readAllocations($jsonObject);
break;
default:
throw new RandapiException("Invalid Action was specified");
}
}else{
http_response_code(500);
$exception = new RandapiException("Invalid jsonObject was posted: $jsonText");
echo json_encode($exception);
}
}else{
error_log("incorrect token");
throw new RandapiException("You don't have sufficient privileges to access this api.",500);
}
}
public function handleGetRequest(){
$params = new stdClass();
$params->token = $_GET["token"];
if($this->checkToken($params)){
if(isset($_GET["action"]) && isset($_GET["pid"])){
switch($_GET["action"]){
case "readConfiguration": $this->readConfiguration();
break;
case "readAllocations": $this->readAllocations();
break;
default:
throw new RandapiException("Invalid Action was specified");
}
}else{
http_response_code(500);
$exception = new RandapiException("No action or pid was set");
echo json_encode($exception);
}
}else{
error_log("incorrect token");
throw new RandapiException("You don't have sufficient privileges to access this api.",500);
}
}
/**
* @param stdClass $jsonObject
* @return bool
* @throws RandapiException
*/
private function checkToken(stdClass $jsonObject):bool {
if(!$this->getProjectId()){
throw new RandapiException("projectid was not set");
}
if(property_exists($jsonObject,"token")){
try {
$token = db_real_escape_string($jsonObject->token);
// check for project specific token and for super user token
$tokenQuery = "SELECT 1 as ok
FROM redcap_user_information i
JOIN redcap_user_rights u on i.username = u.username
WHERE u.api_token = '" . db_escape($token) . "'
AND u.project_id = ".$this->getProjectId()."
AND i.user_suspended_time is null
UNION
SELECT 1 as ok
FROM redcap_user_information
WHERE api_token = '" . db_escape($token) . "'
AND user_suspended_time IS NULL
AND super_user = 1";
error_log($tokenQuery);
$tokenQueryResult = $this->query($tokenQuery);
return !is_null($tokenQueryResult->fetch_assoc());
}catch(\Exception $e){
throw new RandapiException("Could not check token status",500,$e);
}
}else{
throw new RandapiException("Token property was not set");
}
}
/**
* @param stdClass $jsonObject
* @return int
* @throws RandapiException
*/
private function handleFindAID(stdClass $jsonObject): int {
if(!property_exists($jsonObject,"parameters")){
throw new RandapiException("parameters property not found.");
}
try {
$recordid = db_real_escape_string($jsonObject->parameters);
$aidQuery = "
select rra.aid
from redcap_projects rp
join redcap_randomization rr on rr.project_id = rp.project_id
join redcap_randomization_allocation rra on
rr.rid = rra.rid and
rra.project_status = rp.status and
rra.is_used_by = '$recordid'
where rp.project_id = ".$this->getProjectId();
error_log("executing aidQuery $aidQuery");
$aidQueryResult = $this->query($aidQuery);
$res = $aidQueryResult->fetch_object();
if (!is_null($res)) {
return $res->aid;
} else {
throw new RandapiException("recordid $$recordid is not found",400);
}
}catch(\Exception $e){
throw new RandapiException("Could not execute handleFindAID",500,$e);
}
}
/**
* @param stdClass $jsonObject
* @throws RandapiException
*/
private function handleUndoRandomization(stdClass $jsonObject){
if(!property_exists($jsonObject,"parameters")){
throw new RandapiException("parameters property not found.");
}
$recordid = $jsonObject->parameters;
$aid = $this->handleFindAID($jsonObject);
if($aid){
$ok = $this->query("
delete d
from redcap_randomization_allocation ra
join redcap_randomization r on r.rid = ra.rid
join redcap_data d on
d.project_id = r.project_id and
d.field_name = r.target_field and
(r.target_event is null or d.event_id = r.target_event) and
d.record = ra.is_used_by
where ra.aid = $aid
");
if($ok){
$ok = $this->query("
update redcap_randomization_allocation
set is_used_by = null
where aid = $aid
");
if(!$ok){
throw new RandapiException("Could not unset allocation record for record $recordid and aid $aid");
}
}else{
throw new RandapiException("Could not delete data record for record $recordid and aid $aid");
}
}else{
throw new RandapiException("Could not find aid for record $recordid");
}
}
/**
* @param stdClass $jsonObject
* @return int
* @throws RandapiException
*/
private function handleChangeSources(stdClass $jsonObject){
error_log("Received parameters in changeSources: ".print_r($jsonObject,true));
if(!property_exists($jsonObject,"parameters")){
error_log("parameters property not found.");
throw new RandapiException("parameters property not found.");
}
if(!property_exists($jsonObject->parameters, "recordId")){
error_log("parameters->recordId property not found.");
throw new RandapiException("parameters->recordId property not found.");
}
if(!property_exists($jsonObject->parameters, "fields")){
error_log("parameters->fields property not found.");
throw new RandapiException("parameters->fields property not found.");
}
if(!is_array($jsonObject->parameters->fields)){
error_log("parameters->fields is not an array.");
throw new RandapiException("parameters->fields is not an array.");
}
if(!property_exists($jsonObject->parameters, "allocations")){
error_log("parameters->allocations property not found.");
throw new RandapiException("parameters->allocations property not found.");
}
if(!is_array($jsonObject->parameters->allocations)){
error_log("parameters->allocations is not an array.");
throw new RandapiException("parameters->allocations is not an array.");
}
// optional
$groupId = "";
if(property_exists($jsonObject->parameters, "groupId")){
$groupId = $jsonObject->parameters->groupId;
}
$armName = "Arm 1";
if(property_exists($jsonObject->parameters, "armName")){
$groupId = $jsonObject->parameters->armName;
}
$eventName = "Event 1";
if(property_exists($jsonObject->parameters, "eventName")){
$eventName = $jsonObject->parameters->eventName;
}
$fields = array();
foreach($jsonObject->parameters->fields as $field){
array_push($fields,RandomizationField::fromStdClass($field));
}
$allocations = array();
foreach($jsonObject->parameters->allocations as $allocation){
array_push($allocations,RandomizationAllocation::fromstdClass($allocation));
}
error_log("executing changeSources");
return $this->changeSources($jsonObject->parameters->recordId,
$this->getProjectId(),
$fields,
$allocations,
$groupId,
$armName,
$eventName);
}
/**
* @param stdClass $jsonObject
* @return int
* @throws RandapiException
*/
private function handleChangeTarget(stdClass $jsonObject){
error_log("Received parameters in changeTarget: ".print_r($jsonObject,true));
if(!property_exists($jsonObject,"parameters")){
error_log("parameters property not found.");
throw new RandapiException("parameters property not found.");
}
if(!property_exists($jsonObject->parameters, "recordId")){
error_log("parameters->recordId property not found.");
throw new RandapiException("parameters->recordId property not found.");
}
if(!property_exists($jsonObject->parameters, "target")){
error_log("parameters->fields property not found.");
throw new RandapiException("parameters->fields property not found.");
}
if(!property_exists($jsonObject->parameters, "allocations")){
error_log("parameters->allocations property not found.");
throw new RandapiException("parameters->allocations property not found.");
}
if(!is_array($jsonObject->parameters->allocations)){
error_log("parameters->allocations is not an array.");
throw new RandapiException("parameters->allocations is not an array.");
}
// optional
$groupId = "";
if(property_exists($jsonObject->parameters, "groupId")){
$groupId = $jsonObject->parameters->groupId;
}
$armName = "Arm 1";
if(property_exists($jsonObject->parameters, "armName")){
$groupId = $jsonObject->parameters->armName;
}
$eventName = "Event 1";
if(property_exists($jsonObject->parameters, "eventName")){
$eventName = $jsonObject->parameters->eventName;
}
$allocations = array();
foreach($jsonObject->parameters->allocations as $allocation){
array_push($allocations,RandomizationAllocation::fromstdClass($allocation));
}
error_log("executing changeTarget");
return $this->changeTarget($jsonObject->parameters->recordId,
$this->getProjectId(),
$jsonObject->parameters->target,
$allocations,
$groupId,
$armName,
$eventName);
}
/**
*
*/
private function readConfiguration(){
$configQuery = $this->query("select r.*
from redcap_randomization r
where r.project_id = ".$this->getProjectId().";");
$ret = array();
while($row = $configQuery->fetch_assoc()){
foreach($row as $key=>$value){
if(!key_exists($key,$ret)){
$ret[$key]=array();
}
array_push($ret[$key],$value);
}
}
$this->printCsv($ret);
}
/**
* @throws RandapiException
*/
private function readAllocations(){
if(!isset($_GET["status"])){
error_log("parameter status not found.");
throw new RandapiException("parameter status not found.");
}
$allocationsQuery = $this->query("select a.*
from redcap_randomization r
join redcap_randomization_allocation a on
a.rid = r.rid and
a.project_status = ".$_GET["status"]."
where r.project_id = ".$this->getProjectId().";");
$ret = array();
while($row = $allocationsQuery->fetch_assoc()){
foreach($row as $key=>$value){
if(!key_exists($key,$ret)){
$ret[$key]=array();
}
array_push($ret[$key],$value);
}
}
$this->printCsv($ret);
}
/**
* @param array $ret a map with key, the column name and value an array with values for each line.
*/
private function printCsv(array $ret){
$this->setHeaderCSV();
// assume each array has an equal nr of rows
$nrOfRow = sizeof($ret[array_keys($ret)[0]]);
$keys = array_keys($ret);
echo implode(";",$keys)."\r\n";
for($i = 0; $i<$nrOfRow;$i++){
$line = array();
foreach($keys as $key){
array_push($line, $ret[$key][$i]);
}