-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepeatingSurveyPortal.php
1275 lines (985 loc) · 47.7 KB
/
RepeatingSurveyPortal.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 Stanford\RepeatingSurveyPortal;
use ExternalModules\ExternalModules;
use \REDCap;
use \DateTime;
use \Message;
use Exception;
use Piping;
use GuzzleHttp;
require_once("src/ConfigInstance.php");
require_once 'emLoggerTrait.php';
require_once 'src/Participant.php';
require_once 'src/PortalConfig.php';
require_once 'src/InsertInstrumentHelper.php';
/**
* Class RepeatingSurveyPortal
* @package Stanford\RepeatingSurveyPortal
*
*
* WEB
*
* Portal Landing Page
* src/landing.php NOAUTH
* src/forecast.php (tries to show what will happen based on certain dates)
* src/cron.php NOAUTH (landing page to instantiate cron)
* - load the project config, for each config, it will execute check to see if each record needs notification...
* -
*
*
*
*/
class RepeatingSurveyPortal extends \ExternalModules\AbstractExternalModule
{
use emLoggerTrait;
const PARTICIPANT_INFO_FORM = "rsp_participant_info";
const SURVEY_METADATA_FORM = "rsp_survey_metadata";
public $iih;
public $project_id;
/*******************************************************************************************************************/
/* HOOK METHODS */
/***************************************************************************************************************** */
function redcap_data_entry_form_top($project_id, $record, $instrument, $event_id, $group_id, $repeat_instance)
{
//$this->emDebug($instrument, current($this->getProjectSetting('main-config-form-name')));
if ($instrument == current($this->getProjectSetting('main-config-form-name'))) {
$config_id_field_name = $this->getProjectSetting('participant-config-id-field');
//if there is a value for this field, display it here
$params = array(
'return_format' => 'json',
'records' => array($record),
'events' => $event_id,
'repeat_instance' => $repeat_instance,
'fields' => array(REDCap::getRecordIdField(), $config_id_field_name)
);
$q = REDCap::getData($params);
$records = json_decode($q, true);
$key = array_search($repeat_instance, array_column($records, 'redcap_repeat_instance'));
if (trim($key) !== '') {
$selected = $records[$key][$config_id_field_name];
}
//if the are settings for the the config id, convert from a text field to a dropdown
$config_fields = $this->getProjectSetting('config-id');
$option_str = '<option value></option>';
foreach ($config_fields as $option) {
$option_str .= '<option value="'.$option.'">'.$option.'</option>';
}
?>
<script type="text/javascript">
$(document).ready(function () {
var field_name = <?php echo "'".$config_id_field_name."'"; ?>;
var options = <?php echo "'".$option_str."'";?>;
var selected = <?php echo "'".$selected."'";?>;
$('input[name="rsp_prt_config_id"]')
.replaceWith('<span><select role="listbox" aria-labelledby="label-rsp_prt_config_id" class="x-form-text x-form-field " id="rsp_prt_config_id" name="rsp_prt_config_id" tabindex="0">' + options + '</select></span>');
$('#rsp_prt_config_id').val(selected);
});
</script>
<?php
}
}
public function redcap_module_system_enable() {
// SET THE
// Do Nothing
//create instrument participant info. upload zip for instrument
REDCap::getInstrumentNames(); //to get instrument name
//upload instrument zip
//verify that default fields aren't already existing. if exists, then abort
//if pi_ already exists, notify admin that the field already exists
\ExternalModules\ExternalModules::sendAdminEmail('subject', 'message');
//make sure its in dev mode
//status > 0
//$current_forms = ($status > 0) ? $Proj->forms_temp : $Proj->forms;
//make sure form name doesn't already exist.
//insert the form
}
/**
* 18Sep20 : occasion when this is called without a pid.
* so disabling for now
*
* @param $project_id
* @param $link
* @return mixed
*/
public function disable_redcap_module_link_check_display($project_id, $link) {
// TODO: Loop through each portal config that is enabled and see if they are all valid.
//TODO: ask andy123; i'm not sure what KEY_VALID_CONFIGURATION is for...
//if ($this->getSystemSetting(self::KEY_VALID_CONFIGURATION) == 1) {
list($result, $message) = $this->getConfigStatus();
if ($result === true) {
// Do nothing - no need to show the link
} else {
$link['icon'] = "exclamation";
}
return $link;
}
// SAVE CONFIG HOOK
// if config-id is null, then generate a config id for that the configs...
//todo: HOLD ON THIS. saving works, but delete ignores this setting we add. punt for now.
/**
* Save config hook:
* 1. validate configuratio on save
* @param $project_id
*/
public function redcap_module_save_configuration($project_id) {
list($result, $message) = $this->getConfigStatus();
}
/**
* Need to handle case where after the survey completes, it redirects back to the portal for the user.
* There is a cooke stored at creation of the portal. Lookup key and reconstitute hash for the participant
*
*
* @param $project_id
* @param $record
* @param $instrument
* @param $event_id
* @param $group_id
* @param $survey_hash
* @param $response_id
* @param $repeat_instance
*/
public function redcap_survey_complete($project_id, $record, $instrument, $event_id, $group_id, $survey_hash, $response_id, $repeat_instance) {
//retrieve the config (ex: parent or child config) from the cookie that was stored when started from the landing page
//TODO: Ask Andy: If there multiple protocols (ex: parent and child) on machine at same time, we cannot distinguish which survey this is related to
$cookie_key = $this->PREFIX."_".$project_id."_".$record; //this won't work if mother/child are on same machine at same time.
$cookie_config = $_COOKIE[$cookie_key];
$this->emDebug("COOKIE KEY ". $cookie_key);
//if redirect has been turned on redirect to the landing page
$sub = $this->getSubIDFromConfigID($cookie_config);
$this->emDebug("COOKIE CONFIG <". $cookie_config . "> found SUB: ".$sub);
$redirect = $this->getProjectSetting('survey-complete-redirect', $project_id)[$sub];
$survey_event = $this->getProjectSetting('survey-event-name', $project_id)[$sub];
if (isset($redirect) && ($redirect == $instrument) && ($event_id == $survey_event)) {
$this->emDebug("Redirecting to landing page after this survey completed in target event ($event_id): " . $redirect);
if (empty($cookie_config) || $cookie_config == '') {
$this->emError("Unable to redirect to landing page since unable to retrieve config info from cookie: " . $cookie_key);
$this->exitAfterHook(); //this doesn't really exit! it continues on to attempt redirect so will put redirect in else block
//die("Unable to return to portal page. Please use the link from your email.");
} else {
$config_event_id = $this->getProjectSetting('main-config-event-name')[$sub];
$config_event_name = REDCap::getEventNames(true, false, $config_event_id);
$config_field = $this->getProjectSetting('participant-config-id-field');
$hash_field = $this->getProjectSetting('personal-hash-field')[$sub];
$hash = $this->retrieveParticipantFieldWithFilter($record, $config_event_name, $config_field, $cookie_config, $hash_field);
//$this->emDebug("HASH: ". $hash);
$portal_url = $this->getUrl("src/landing.php", true, true);
$return_hash_url = $portal_url . "&h=" . $hash . "&c=" . $cookie_config;
//$this->emDebug("this is new hash url: " . $return_hash_url);
//now redirect back to the landing page
header("Location: " . $return_hash_url);
}
}
}
// SAVE_RECORD HOOK
// make portal objects and verify that current record has hash and personal url saved
/**
* @param $project_id
* @param null $record
* @param $instrument
*/
public function redcap_save_record($project_id, $record, $instrument, $event_id, $group_id = NULL, $survey_hash = NULL, $response_id = NULL, $repeat_instance = NULL) {
//If instrument is the right one, create the portal url and save it to the designated field
$this->project_id = $project_id;
//iterate through all of the sub_settings
$target_forms = $this->getProjectSetting('main-config-form-name', $project_id);
foreach ($target_forms as $sub => $target_form) {
/**
* In default install, $target_form should be rsp_participant_info
*
*/
if ($instrument == $target_form) {
$config_field = $this->getProjectSetting('participant-config-id-field', $project_id);
$config_event = $this->getProjectSetting('main-config-event-name', $project_id)[$sub];
$start_date_field = $this->getProjectSetting('start-date-field', $project_id)[$sub];
//CHECK that the config event set for rsp_participant_event is the same as this current event
if ($config_event != $event_id) {
$this->emError("Event id $event_id is not not what is designated in the config: $config_event.");
return;
//$this->exitAfterHook();
}
//check that the start date for the portal is set, if not set then return
$start_date = $this->getFieldValue($project_id, $record, $event_id, $start_date_field, $instrument, $repeat_instance);
if ($start_date == null) {
$this->emError("Start Date for record $record is not set. Will not create portal url for this record.");
return;
//$this->exitAfterHook();
}
//get the config_id for this participant
$config_id = $this->getFieldValue($project_id,$record, $event_id, $config_field, $instrument, $repeat_instance);
//CHECK that the config ID for this record is set, if not set then return
if ($config_id == null) {
$this->emError("Config ID for record $record is not set. Will not create portal url for this record.");
return;
//$this->exitAfterHook();
}
//$sub = $this->getSubIDFromConfigID($config_id);
$config_ids = $this->getProjectSetting('config-id', $project_id);
$sub = array_search($config_id, $config_ids);
//if sub is empty, then the participant is using a config_id that doesn't exist.
if ($sub === false) {
$this->emError("This $config_id entered in participant $record is not found the EM config settings.");
return;
//$this->exitAfterHook();
}
/***********************************/
$personal_hash_field = $this->getProjectSetting('personal-hash-field',$project_id)[$sub];
$personal_url_field = $this->getProjectSetting('personal-url-field', $project_id)[$sub];
$portal_invite_checkbox = $this->getProjectSetting('send-portal-invite',$project_id)[$sub];
/***********************************/
// First check if hashed portal already has been created
$f_value = $this->getFieldValue($project_id, $record, $config_event, $personal_hash_field, $instrument, $repeat_instance);
if ($f_value == null) {
//generate a new URL
$new_hash = $this->generateUniquePersonalHash($project_id, $personal_hash_field, $config_event);
$portal_url = $this->getUrl("src/landing.php", true, true);
//sometimes coming from differnt project context
if ($_GET['pid'] != $project_id) {
//the pid needs to be replaced
$portal_url = preg_replace( '/&pid=\d+/', "&pid={$project_id}", $portal_url);
}
$new_hash_url = $portal_url . "&h=" . $new_hash . "&c=" . $config_id;
// Save it to the record (both as hash and hash_url for piping)
//this doesn't work out of context
$event_name = REDCap::getEventNames(true, false, $config_event);
//because we will hit this code from different project context we need to get the correct event name to save.
$proj = new \Project($project_id);
$event_name = $proj->getUniqueEventNames($config_event);
$data = array(
REDCap::getRecordIdField() => $record,
'redcap_event_name' => $event_name,
'redcap_repeat_instrument' => $instrument,
'redcap_repeat_instance' => $repeat_instance,
$personal_url_field => $new_hash_url,
$personal_hash_field => $new_hash
);
$response = REDCap::saveData($project_id, 'json', json_encode(array($data)));
//$this->emDebug($sub, data, $response, "Save Response for count"); exit;
if (!empty($response['errors'])) {
$msg = "Error creating record - ask administrator to review logs: " . json_encode($response);
$this->emError($msg, $response['errors']);
}
//checkbox to send portal invite has been checked so send invite
if ($portal_invite_checkbox) {
//$this->emDebug("PORTAL CHECKBOX: ". $portal_invite_checkbox,$this->getProjectSetting('send-portal-invite'));//exit;
$this->handlePortalInvite($project_id,$sub, $record, $instrument, $repeat_instance,$new_hash_url);
}
//$this->emDebug($record . ": Set unique Hash Url to $new_hash_url with result " . json_encode($response));
}
}
}
}
/*******************************************************************************************************************/
/* CRON METHODS */
/***************************************************************************************************************** */
/**
* Current settings to run every hour
*
* TODO: Add cron to config.json
*
* 1) Determine projects that are using this EM
* 2) Instantiate instance of EM for each project
* 3)
*/
public function inviteCron() {
$this->emDebug("Starting invite cron for ".$this->PREFIX);
//* 1) Determine projects that are using this EM
//get all projects that are enabled for this module
$enabled = ExternalModules::getEnabledProjects($this->PREFIX);
//get the noAuth api endpoint for Cron job.
$url = $this->getUrl('src/InviteCron.php', true, true);
//while ($proj = db_fetch_assoc($enabled)) {
while($proj = $enabled->fetch_assoc()){
$pid = $proj['project_id'];
$this->emDebug("STARTING INVITE CRON for pid ". $pid);
//check scheduled hour of send
$scheduled_hour = $this->getProjectSetting('invitation-time', $pid);
$current_hour = date('H');
//iterate through all the sub settings
foreach ($scheduled_hour as $sub => $invite_time) {
//TODO: check that the 'enable-invitations' is not set. test this
$enabled_invite = $this->getProjectSetting('enable-invitations', $pid)[$sub];
if ($enabled_invite == '1') {
//$this->emDebug("PROJECT $pid : SUB $sub scheduled at this hour $invite_time vs current hour: $current_hour");
//if not hour, continue
if ($invite_time != $current_hour) continue;
$this_url = $url . '&pid=' . $pid . "&s=" . $sub;
$this->emDebug("INVITE CRON URL IS " . $this_url);
// $timeout = 3600;
// // Without a timeout, it appears that after 10 minutes the curl request was 'restarting'
// $resp = http_get($this_url, $timeout);
try{
$client = new GuzzleHttp\Client();
$resp = $client->request('GET', $this_url, [
GuzzleHttp\RequestOptions::SYNCHRONOUS => true
]);
$this->emDebug("Guzzle done", $resp->getBody()->getContents());
} catch (GuzzleHttp\Exception\ConnectException $e) {
$this->emDebug("Guzzle exception: " . $e->getMessage());
}
//$this->cronAttendanceReport($pid);
// $this->emDebug("Invite Cron Response:",$resp->getBody());
// TODO: How to inspect guzzle response for errors?
}
}
}
}
/**
* Cron method to initiate reminder emails/texts
*
* Cron job for project is only initiated for a project's subsetting in the config if
* the checkbox to Enable Reminders have been checked.
*
* The Cron job is started by triggeringg the ReminderCron.php page PLUS the additional parameters:
* project id
* subsetting
*/
public function reminderCron() {
//* 1) Determine projects that are using this EM
//get all projects that are enabled for this module
$enabled = ExternalModules::getEnabledProjects($this->PREFIX);
//get the noAuth api endpoint for Cron job.
$url = $this->getUrl('src/ReminderCron.php', true, true);
//while ($proj = db_fetch_assoc($enabled)) {
while($proj = $enabled->fetch_assoc()){
$pid = $proj['project_id'];
$this->emDebug("STARTING REMINDER CRON for pid ". $pid);
//check scheduled hour of send
$scheduled_hour = $this->getProjectSetting('reminder-time', $pid);
$current_hour = date('H');
//iterate through all the sub settings
foreach ($scheduled_hour as $sub => $reminder_time) {
//TODO: check that the 'enable-reminders' is not set. test this
$enabled_reminder = $this->getProjectSetting('enable-reminders', $pid)[$sub];
if ($enabled_reminder == '1') {
//$this->emDebug("project $pid - $sub scheduled at this hour $reminder_time vs current hour: $current_hour");
//if not hour, continue
if ($reminder_time != $current_hour) continue;
$this_url = $url . '&pid=' . $pid . "&s=" . $sub;
$this->emDebug("REMINDER CRON URL IS " . $this_url);
// $resp = http_get($this_url);
// //$this->cronAttendanceReport($pid);
// $this->emDebug("cron for reminder: " . $resp);
try{
$client = new GuzzleHttp\Client();
$resp = $client->request('GET', $this_url, [
GuzzleHttp\RequestOptions::SYNCHRONOUS => true
]);
$this->emDebug("Guzzle done", $resp->getBody()->getContents());
} catch (GuzzleHttp\Exception\ConnectException $e) {
$this->emDebug("Guzzle exception: " . $e->getMessage());
}
}
}
}
}
/*******************************************************************************************************************/
/* METHODS */
/***************************************************************************************************************** */
/**
* @param $sub
* @param $record
* @param $instrument
* @param $repeat_instance
* @param $new_hash_url
*/
function handlePortalInvite($project_id, $sub, $record,$instrument, $repeat_instance, $new_hash_url) {
//prep for the initial invite email
$config_event = $this->getProjectSetting('main-config-event-name', $project_id)[$sub];
$email_to_field = $this->getProjectSetting('email-field', $project_id)[$sub];
$portal_url_label = $this->getProjectSetting('portal-url-label', $project_id)[$sub];
$initial_invite_msg = nl2br($this->getProjectSetting('portal-invite-email', $project_id)[$sub]);
$initial_invite_subject = $this->getProjectSetting('portal-invite-subject', $project_id)[$sub];
$email_from = $this->getProjectSetting('portal-invite-from', $project_id)[$sub];
//the URL has been updated so send out an email
//get the email field. if email is set, then send out invite
$email_to = $this->getFieldValue($project_id, $record, $config_event, $email_to_field, $instrument, $repeat_instance);
if (!empty($email_to)) {
//convert all to piped values
//$this->emDebug("RECORD:".$record. " / SUB: ".$sub. " / EVENTID: ".$event_id. " /REP INSTANCE: ".$repeat_instance);
$piped_email_subject = Piping::replaceVariablesInLabel($initial_invite_subject, $record, $config_event,$repeat_instance, array(), false, $project_id, false);
$piped_email_msg = Piping::replaceVariablesInLabel($initial_invite_msg, $record, $config_event,$repeat_instance, array(), false, $project_id, false);
//$this->emDebug($record. "piped subject: ". $piped_email_subject);
//$this->emDebug($record. "piped msg: ". $piped_email_msg);
$this->sendInitialPortalUrl($project_id, $record, $new_hash_url, $portal_url_label, $piped_email_msg, $email_to, $email_from, $piped_email_subject);
} else {
//if both the text and email fields are empty, log so that admin know that record never got the initial invite
$this->emLog("Portal invite was not sent for record $record because the email field is empty.");
REDCap::logEvent(
"Unable to send portal invite by Survey Portal EM", //action
"Portal invite was not sent because the email field is empty.",
NULL, //sql optional
$record, //record optional
null,
$project_id//$project_id //project ID optional
);
}
}
/**
* Method to send out the initial portal invitation by email
*
* @param $record
* @param $portal_url
* @param $portal_url_label
* @param $msg
* @param $email_to
* @param $from
* @param $subject
*/
public function sendInitialPortalUrl($project_id,$record, $portal_url,$portal_url_label, $msg, $email_to, $from, $subject) {
//replace $portal_url the tag [portal-url]
$target_str = "[portal-url]";
if (empty($portal_url_label)) {
$portal_url_label = $portal_url;
}
$tagged_link = "<a href='{$portal_url}'>$portal_url_label</a>";
//$this->emDebug($portal_url, $portal_url_label, $tagged_link);
//if there is a portal-url tag included, switch it out for the actual url. if not, then add it to the end.
if (strpos($msg, $target_str) !== false) {
$msg = str_replace($target_str, $tagged_link, $msg);
} else {
$msg = $msg . "<br>Use this link to take the survey: ".$tagged_link;
}
//$this->emDebug( $email_to, $from, $subject, $msg);
if (!isset($from)) $from = '[email protected]';
//send email
$email = new Message();
$email->setTo($email_to);
$email->setFrom($from);
$email->setSubject($subject);
$email->setBody($msg); //format message??
$result = $email->send();
if ($result == false) {
$action_status = "Error sending invite form Survey Portal EM";
$send_status = 'Error sending mail to '.$email_to .
" with status: " . $email->getSendError() . ' with ' . json_encode($email);
} else {
$action_status = "Portal Link Sent from Survey Portal EM";
$send_status = 'Email with portal url was sent to '. $email_to;
}
REDCap::logEvent(
$action_status, //action
$send_status,
NULL, //sql optional
$record, //record optional
null,
$project_id //project ID optional
);
}
/**
* Method to send out initial portal invitation by text
* Design change: no longer sending out portal url by text
* Method unused - delete?
*
* @param $project_id
* @param $record
* @param $portal_url
* @param $msg
* @param $text_to
*/
public function textInitialPortalUrl($project_id, $record, $portal_url, $msg, $text_to) {
//replace $portal_url the tag [portal-url]
$target_str = "[portal-url]";
//no taggged link for texts
//$tagged_link = "<a href='{$portal_url}'>$portal_url_label</a>";
//if there is a portal-url tag included, switch it out for the actual url. if not, then add it to the end.
if (strpos($msg, $target_str) !== false) {
$msg = str_replace($target_str, $portal_url, $msg);
} else {
$msg = $msg . "<br>Here is the link to your portal".$portal_url;
}
$twilio_status = $this->emText($text_to, $msg);
if ($twilio_status !== true) {
$this->emError("TWILIO Failed to send to ". $text_to. " with status ". $twilio_status);
$action_status = "Initial Text Invite Failed to send from Survey Portal EM";
$send_status = "Text for portal invite failed to send to " .$text_to . " with status " . $twilio_status;
} else {
$this->emDebug($twilio_status);
$action_status = "Text Portal Invitation Sent from Survey Portal EM";
$send_status = "Portal Invitation texted to " .$text_to;
}
REDCap::logEvent(
$action_status, //action
$send_status,
NULL, //sql optional
$record, //record optional
null,
$project_id //project ID optional
);
}
/**
* This function takes the settings for each configuration and rearranges them into arrays of subsettings
* instead of arrays of key/value pairs. This is called from javascript so each configuration
* can be verified in real-time.
*
* @param $key - JSON key where the subsettings are stored
* @param $settings - retrieved list of subsettings from the html modal
* @return array - the array of subsettings for each configuration
*/
public function parseSubsettingsFromSettings($key, $settings) {
$config = $this->getSettingConfig($key);
if ($config['type'] !== "sub_settings") return false;
// Get the keys that are part of this subsetting
$keys = [];
foreach ($config['sub_settings'] as $subSetting) {
$keys[] = $subSetting['key'];
}
// Loop through the keys to pull values from $settings
$subSettings = [];
foreach ($keys as $key) {
$values = $settings[$key];
foreach ($values as $i => $value) {
$subSettings[$i][$key] = $value;
}
}
return $subSettings;
}
/*******************************************************************************************************************/
/* PORTAL CONFIGURATION METHODS */
/*******************************************************************************************************************/
/**
* Check the EM configuration for validity
* 1. Make sure form, rsp_participant_info, exist
* 2. rsp_participant_info designated in main event
* 3. rsp_participant_info is repeating form
* 4. Form, rsp_survey_metadata, exists
* 5. rsp_survey_metadata designated in survey event
* 6. Survey event is repeating event
* 7. If exists, invitation-days are a subset of valid-day-number
* 8. If exists, reminder-days are a subset of valid-day-number
*
*
* @return array
*/
public function getConfigStatus($configs = null, $fix = true) {
$iih = new InsertInstrumentHelper($this);
$alerts = array();
$result = false;
//check that default forms exist in project
// * 1. Make sure form, rsp_participant_info, exist
if (!$iih->formExists(self::PARTICIPANT_INFO_FORM)) {
$p = "<b>Participant Info form has not yet been created. </b>
<div class='btn btn-xs btn-primary float-right' data-action='insert_form' data-form='" . self::PARTICIPANT_INFO_FORM ."'>Create Form</div>";
$alerts[] = $p;
}
//make sure that metadata form exists
if (!$iih->formExists(self::SURVEY_METADATA_FORM)) {
$s= "<b>Survey Info form has not yet been created. </b>
<div class='btn btn-xs btn-primary float-right' data-action='insert_form' data-form='" . self::SURVEY_METADATA_FORM . "'>Create Form</div>";
$alerts[] = $s;
}
//This is the event that holds the main config form: rsp_participant_info
//Check that rsp_participant_info is a repeating form
//TODO: should this EM just create the event and set it?
//check that the forms exist
if (empty($configs)) {
//create config_instance
$configs = $this->getSubSettings('survey-portals');
}
foreach ($configs as $i => $config) {
$c_instance = new ConfigInstance($this, $config, $i);
list($c_result, $c_alerts) = $c_instance->validateConfig();
if ($c_result == false) {
$alerts = array_merge($alerts, $c_alerts);
$alerts2[] = $c_alerts;
}
}
//$this->emDebug('!CONFIG STATUS', $alerts);
if (empty($alerts) && !empty($configs)) {
$result = true;
$alerts[] = "Your configuration appears valid!";
}
return array( $result, $alerts );
}
public function insertForm($form) {
$this->emDebug("!INSERT FORM: ". $form );
$iih = new InsertInstrumentHelper($this);
$result = $iih->insertForm($form);
$message = $iih->getErrors();
// $this->emDebug("INSERT FORM". $form);
// switch ($form) {
// case "pi" :
// $status = $iih->insertParticipantInfoForm();
// break;
// case "md" :
// $status = $iih->insertSurveyMetadataForm();
// break;
// default:
// $status = false;
// }
//
//
// $errors = $status ? null :$iih->getErrors();
//
// //$status = $this->getConfigStatus();
return array($result, $message);
}
public function designateEvent($form, $event) {
$iih = new InsertInstrumentHelper($this);
$this->emDebug("DESIGNATING EVENT: ". $form . $event);
$result = $iih->designateFormInEvent($form, $event);
if ($result) {
$event_name = REDCap::getEventNames(true, false, $event);
$message = "Form ($form) has been designated in the event $event_name.";
} else {
$message = $iih->getErrors();
}
$this->emDebug("RETURN STATUS", $result, $message);
return array($result, $message);
}
public function makeFormRepeat($form, $event) {
$iih = new InsertInstrumentHelper($this);
$this->emDebug("MAKE FORM REPEATING: ". $form . $event);
$result = $iih->makeFormRepeating($form, $event);
if ($result) {
$event_name = REDCap::getEventNames(true, false, $event);
$message = "Form ($form) has been made repeating in event $event_name.";
} else {
$message = $iih->getErrors();
}
//$this->emDebug("RETURN STATUS", $result, $message);
return array($result, $message);
}
public function makeEventRepeat($event) {
$iih = new InsertInstrumentHelper($this);
$this->emDebug("!MAKE EVENT REPEATING: ". $event );
$result = $iih->makeEventRepeating($event);
if ($result) {
$event_name = REDCap::getEventNames(true, false, $event);
$message = "Event ($event_name) has been made repeating";
} else {
$message = $iih->getErrors();
}
//$this->emDebug("RETURN STATUS", $result, $message);
return array($result, $message);
}
/*******************************************************************************************************************/
/* HELPER METHODS */
/***************************************************************************************************************** */
/**
*
* @param $record
* @param $filter_event : event NAME not id
* @param $filter_field
* @param $filter_value
* @param null $retrieve_array
*/
public function retrieveParticipantFieldWithFilter($record, $filter_event, $filter_field, $filter_value, $hash_field) {
$filter = "[" . $filter_event . "][" . $filter_field . "] = '$filter_value'";
$params = array(
'return_format' => 'json',
'records' => $record,
'events' => $filter_event,
'fields' => array($hash_field),
'filterLogic' => $filter
);
$q = REDCap::getData($params);
$records = json_decode($q, true);
//since 9.1, repeating instance return an empty array plus filtered array.
foreach ($records as $k => $v) {
//$this->emDebug($v);
if (!empty($v[$hash_field])) {
return $v[$hash_field];
}
}
$this->emDebug("COULD NOT FIND HASH FIELD", $filter, $records);
return null;
}
/**
* Given the config_id (text entered to name the configuration subsetting, return the subsetting number (subid)
*
* @param $config_id
* @return false|int|string
*/
public function getSubIDFromConfigID($config_id) {
$config_ids = $this->getProjectSetting('config-id');
return array_search($config_id, $config_ids);
}
/**
* Given the subId (subsetting number 0,1,...) returned the text field used to 'name' configuration subsetting.
*
* @param $sub
* @return mixed
*/
public function getConfigIDFromSubID($sub) {
$config_ids = $this->getProjectSetting('config-id');
return $config_ids[$sub];
}
/**
* @param $project_id
* @param $url_field
* @param $event
* @return string
*/
public function generateUniqueConfigID($hash_field) {
$config_ids = $this->getProjectSetting($hash_field);
$max = max($config_ids);
if ($max == null) {
return 1;
}
return $max + 1;
}
/**
*
*
* @param $project_id
* @param $url_field
* @param $event
* @return string
*/
public function generateUniquePersonalHash($project_id, $hash_field, $event) {
//$url_field = $this->getProjectSetting('personal-url-fields'); // won't work with sub_settings
$i = 0;
do {
$new_hash = generateRandomHash(8, false, TRUE, false);
$this->emDebug("NEW HASH ($i):" .$new_hash);
$params = array(
'return_format' => 'array',
'fields' => array($hash_field),
'events' => $event,
'filterLogic' => "[".$hash_field."] = '$new_hash'"
);
$q = REDCap::getData($params);
// 'array', NULL, array($cfg['MAIN_SURVEY_HASH_FIELD']), $config_event[$sub],
// NULL,FALSE,FALSE,FALSE,$filter);
//$this->emDebug($params, "COUNT IS ".count($q));
$i++;
} while ( count($q) > 0 AND $i < 10 ); //keep generating until nothing returns from get
//$new_hash_url = $portal_url. "&h=" . $new_hash . "&sp=" . $project_id;
return $new_hash;
}
/**
* Convenience method to see if the REDCap field passed for this event and record is already set
* Return value or null if not set
*
* @param $record
* @param $event
* @param $target_field
* @return |null
*/
public function getFieldValue($project_id, $record, $event, $target_field, $instrument, $repeat_instance = 1) {
//$this->emDebug("project_id $project_id, record = $record, event = $event, repeat_instance = $repeat_instance");
//Right instrument, carry on
// First check if hashed portal already has been created
$params = array(
'project_id' => $project_id,
'return_format' => 'json',
'records' => $record,
//'fields' => array($target_field, 'redcap_repeat_instance'), //include this doesn't return repeat_instance, repeat_instrument
'events' => $event,
'redcap_repeat_instrument' => $instrument, //this doesn't restrict
'redcap_repeat_instance' => $repeat_instance //this doesn't seem to do anything!
);
$q = REDCap::getData($params);
$results = json_decode($q, true);