-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCustomTemplateEngine.php
More file actions
3933 lines (3584 loc) · 201 KB
/
CustomTemplateEngine.php
File metadata and controls
3933 lines (3584 loc) · 201 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\CustomTemplateEngine;
/**
* Require Template Engine Template class,
* and autoload.php from Composer.
*/
require_once "Template.php";
use REDCap;
use Project;
use Dompdf\Dompdf;
use Dompdf\Options;
use DOMDocument;
use HtmlPage;
use phpDocumentor\Reflection\Types\Array_;
use ZipArchive;
class CustomTemplateEngine extends \ExternalModules\AbstractExternalModule
{
/**
* Class variables.
*
* @var String $templates_dir Directory to store templates.
* @var String $compiled_dir Directory to store templates compiled by Smarty template engine.
* @var String $img_dir Directory to store images.
* @var String $pid Project id of current REDCap project.
* @var String $userid ID of current user.
*/
private $templates_dir;
private $compiled_dir;
private $temp_dir;
private $img_dir;
private $pid;
private $userid;
private $Proj;
private $redcap_data_table;
/**
* Initialize class variables.
*/
// here you are. Remove constructor and implement lazy loading, per ~/public_html/redcap/bin/scan . output
/**
*
*
* @since 4.2.1
*/
private function getProjectImageDir(): string
{
$dir = rtrim($this->img_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . "pid_" . $this->pid . DIRECTORY_SEPARATOR;
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
return $dir;
}
/**
*
*
* @since 4.2.1
*/
private function getProjectImageUrl(string $filename): string
{
$realpath = realpath($this->getProjectImageDir());
$publicly_accessible_start_pos = strpos($realpath, "redcap");
$path = substr($realpath, $publicly_accessible_start_pos);
return "https://" . $_SERVER["SERVER_NAME"] . "/" . str_replace(DIRECTORY_SEPARATOR, "/", $path) . "/" . rawurlencode($filename);
}
/**
*
*
* @since 4.2.1
*/
private function getLegacyImageUrl(string $filename): string
{
$realpath = realpath($this->img_dir);
$publicly_accessible_start_pos = strpos($realpath, "redcap");
$path = substr($realpath, $publicly_accessible_start_pos);
return "https://" . $_SERVER["SERVER_NAME"] . "/" . str_replace(DIRECTORY_SEPARATOR, "/", $path) . "/" . rawurlencode($filename);
}
/**
* CTE Trigger retrieves the trigger configuration for the project
*
* @since 4.2.0
*/
private function getTriggerConfig(int $projectId): array
{
$raw = $this->getProjectSetting('cte_trigger_config', $projectId);
if (!is_string($raw) || trim($raw) === '') {
return ['schema' => 1, 'templates' => []];
}
$cfg = json_decode($raw, true);
if (!is_array($cfg)) {
return ['schema' => 1, 'templates' => []];
}
// current: schema 1 - array of templates with logic, template filename, target field, and target event unique name
if ((int)($cfg['schema'] ?? 0) !== 1) {
return ['schema' => 1, 'templates' => []];
}
if (!isset($cfg['templates']) || !is_array($cfg['templates'])) {
return ['schema' => 1, 'templates' => []];
}
return [
'schema' => 1,
'templates' => $cfg['templates'],
];
}
/**
* CTE Trigger saves the generated PDF bytes to the specified file upload field
*
* @since 4.2.0
*/
private function savePdfBytesToUploadField(
string $filename,
string $pdfBytes,
string $fieldName,
string $record,
int $eventId,
?int $repeatInstance = null
): bool {
return $this->saveFileToFieldForContext($filename, $pdfBytes, $fieldName, $record, $eventId, $repeatInstance);
}
/**
* CTE Trigger resolves the appropriate event ID to save the generated PDF to
*
* @since 4.2.0
*/
private function resolveEventIdForSaving(int $projectId, int $currentEventId, string $eventUniqueName = ''): int
{
if ($eventUniqueName !== '') {
$eid = \REDCap::getEventIdFromUniqueEvent($eventUniqueName);
if (!empty($eid)) return (int)$eid;
}
if (\REDCap::isLongitudinal()) {
return $currentEventId;
}
// If no event specified, use the FIRST event (same as SaveFileToField.php)
$sql = "SELECT m.event_id
FROM redcap_events_metadata m
JOIN redcap_events_arms a ON m.arm_id = a.arm_id
WHERE a.project_id = ?
ORDER BY m.event_id ASC
LIMIT 1";
$result = $this->query($sql, [$projectId]);
if ($result && ($row = $result->fetch_assoc()) && !empty($row['event_id'])) {
return (int)$row['event_id'];
}
// Should not happen; fallback
return 0;
}
/**
* CTE Trigger generates a PDF from a specified template for a given record
*
* @since 4.2.0
*/
private function generatePdfFromTemplateForRecord(string $template_filename, string $record): string
{
$template = new \BCCHR\CustomTemplateEngine\Template();
$template->setPaths($this->templates_dir, $this->compiled_dir);
$filled_template = $template->fillTemplate($template_filename, $record);
$doc = new \DOMDocument();
$doc->loadHTML($filled_template);
$header = $doc->getElementsByTagName("header")->item(0);
$footer = $doc->getElementsByTagName("footer")->item(0);
$main = $doc->getElementsByTagName("main")->item(0);
$filled_main = $doc->saveHTML($main);
$fm_entities = htmlentities($filled_main);
$filled_header = empty($header) ? "" : $doc->saveHTML($header);
$filled_footer = empty($footer)? "" : $doc->saveHTML($footer);
$header = \REDCap::filterHtml(preg_replace("/ /", " ", $filled_header));
$footer = \REDCap::filterHtml(preg_replace("/ /", " ", $filled_footer));
$main = \REDCap::filterHtml(preg_replace("/ /", " ", $filled_main));
$dompdf = new \Dompdf\Dompdf();
return $this->createPDF($dompdf, $filled_header, $filled_footer, $filled_main);
}
/**
* CTE Trigger makes a filename for the generated PDF based on the template filename and record ID
*
* @since 4.2.0
*/
private function makeFilename(string $templateFilename, string $record): string
{
$base = pathinfo($templateFilename, PATHINFO_FILENAME);
$base = preg_replace('/_\d+$/', '', $base);
return "{$base}_{$record}";
}
/**
* CTE Trigger get the latest instance for a given instrument on event, to properly evaluate logic
*
* @since 4.2.0
*/
private function getLatestInstanceForInstrument($record, $event_id, $instrument)
{
$record_data = REDCap::getData(
"json",
$record,
null,
$event_id,
null,
true,
false,
true,
null,
true
);
$json = json_decode($record_data, true);
if (!is_array($json)) {
return null;
}
$instance = null;
foreach ($json as $row) {
$rowInstrument = $row['redcap_repeat_instrument'] ?? null;
$rowInstance = $row['redcap_repeat_instance'] ?? null;
if (
$rowInstrument !== null &&
strtolower($rowInstrument) === strtolower($instrument) &&
!empty($rowInstance)
) {
$instance = max((int)($instance ?? 0), (int)$rowInstance);
}
}
return $instance;
}
public function setPaths() {
/*
** lazy loading equivalent of what was done by the __construct() call in previoius versions
*/
$this->userid = defined('USERID') ? strtolower(USERID) : null;
/**
* External Module functions to get module settings.
*/
$this->templates_dir = $this->getSystemSetting("templates-folder");
$this->compiled_dir = $this->getSystemSetting("compiled-templates-folder");
$this->temp_dir = $this->getSystemSetting("temp-folder");
$this->img_dir = $this->getSystemSetting("img-folder");
$this->pid = $this->getProjectId();
/*
** check REDCap version of the server; versions before v14 only have a single data table and no
** getDataTable() function, which returns -1 if first < second, 0 if equal, 1 otherwise
*/
if ( \REDCap::versionCompare(REDCAP_VERSION, '14.0.0') == -1) { // pre v14, so only a single table an no function to call
$this->redcap_data_table = 'redcap_data';
} else { // use REDCap::getDataTable() function to check if there may be other redcap_data tables
$this->redcap_data_table = \REDCap::getDataTable($this->pid);
// REDCap::logEvent('version is ' . REDCAP_VERSION . ' compare check is ' . \REDCap::versionCompare(REDCAP_VERSION, '14.0.0'));
} // end if
if (!empty($this->pid)) {
$this->Proj = new Project($this->pid);
} // end if
/**
* Checks and adds trailing directory separator
*/
if (substr($this->templates_dir, -1) != DIRECTORY_SEPARATOR) {
$this->templates_dir = $this->templates_dir . DIRECTORY_SEPARATOR;
} // end if
if (substr($this->compiled_dir, -1) != DIRECTORY_SEPARATOR) {
$this->compiled_dir = $this->compiled_dir . DIRECTORY_SEPARATOR;
} // end if
if (substr($this->temp_dir, -1) != DIRECTORY_SEPARATOR) {
$this->temp_dir = $this->temp_dir . DIRECTORY_SEPARATOR;
} // end if
if (substr($this->img_dir, -1) != DIRECTORY_SEPARATOR) {
$this->img_dir = $this->img_dir . DIRECTORY_SEPARATOR;
} // end if
} // end setPaths()
/**
* Allows custom actions to be performed immediately after a record has been saved on a data entry form or survey page
* CTE Trigger Uploads a generated PDF to a specified file upload field when the trigger conditions are met.
* @since 4.2.0
*/
public function redcap_save_record($project_id, $record, $instrument, $event_id, $group_id, $survey_hash, $response_id, $repeat_instance) {
$this->setPaths();
if ((int)$project_id !== (int)$this->getProjectId()) {
return;
}
$cfg = $this->getTriggerConfig((int)$project_id);
$templates = $cfg['templates'] ?? [];
if (empty($templates) || !is_array($templates)) {
return;
}
foreach ($templates as $templateFile => $tCfg) {
if (!is_array($tCfg)) continue;
if (empty($tCfg['enabled'])) continue;
$logic = trim((string)($tCfg['logic'] ?? ''));
$targetField = trim((string)($tCfg['target_field'] ?? ''));
$targetEventUnique = trim((string)($tCfg['target_event_unique'] ?? ''));
if ($templateFile === '' || $logic === '' || $targetField === '') {
continue;
}
$valid = false;
$saveEventId = $this->resolveEventIdForSaving($project_id, $event_id, $targetEventUnique);
if ($saveEventId <= 0) {
continue;
}
if (\REDCap::isLongitudinal() && ($this->checkFieldInEvent($targetField, $saveEventId) == false)) {
\REDCap::logEvent('CTE Trigger - Invalid field for event', "template={$templateFile} field={$targetField} event_id={$saveEventId}", '', (string)$record);
continue;
}
if (\REDCap::isLongitudinal() && !empty($targetEventUnique)) {
$valid = \REDCap::evaluateLogic(
$logic,
$project_id,
(string)$record,
$targetEventUnique, // pass unique event name
(int)$repeat_instance
);
} else {
$project = $this->getProject();
$repeatingForms = is_object($project) ? $project->getRepeatingForms((int)$event_id) : [];
$targetFieldForm = (!empty($targetField) && is_object($project)) ? $project->getFormForField($targetField) : null;
$isTargetFieldFormRepeating = $targetFieldForm !== null && is_array($repeatingForms) && in_array($targetFieldForm, $repeatingForms, true);
$resRepeatInstrument = null;
$resRepeatInstance = null;
if ($isTargetFieldFormRepeating) {
if ((string)$instrument === $targetFieldForm) {
$resRepeatInstrument = (string)$instrument;
$resRepeatInstance = ((int)$repeat_instance > 0) ? (int)$repeat_instance : 1;
} else {
// If the trigger field's form is repeating, but the current instrument isn't that form, we need to find the latest instance for the trigger form to evaluate the logic correctly
$resRepeatInstrument = $targetFieldForm;
$resRepeatInstance = $this->getLatestInstanceForInstrument((string)$record, (int)$event_id, $targetFieldForm);
}
}
if ($resRepeatInstrument !== null && $resRepeatInstance !== null) {
$valid = \REDCap::evaluateLogic(
$logic,
(int)$project_id,
(string)$record,
null,
(int)$resRepeatInstance,
(string)$resRepeatInstrument,
);
} else {
$valid = \REDCap::evaluateLogic(
$logic,
(int)$project_id,
(string)$record,
null,
);
}
}
if ($valid !== true) continue;
try {
$pdf_content = $this->generatePdfFromTemplateForRecord($templateFile, (string)$record);
} catch (\Throwable $e) {
\REDCap::logEvent('CTE Trigger - PDF generation failed', $e->getMessage(), '', (string)$record);
continue;
}
$filename = $this->makeFilename($templateFile, (string)$record);
if (\REDCap::isLongitudinal()) {
if ($repeat_instance === 1) {
$saveRepeatInstance = null;
} else {
$saveRepeatInstance = (int)$repeat_instance;
}
} else {
$saveRepeatInstance = null;
}
$project = $this->getProject();
$targetFieldForm = (!empty($targetField) && is_object($project))
? $project->getFormForField($targetField)
: null;
$repeatingForms = is_object($project) ? $project->getRepeatingForms((int)$saveEventId) : [];
$isClassicRepeatingTarget = !\REDCap::isLongitudinal()
&& $targetFieldForm !== null
&& is_array($repeatingForms)
&& in_array($targetFieldForm, $repeatingForms, true);
if ($isClassicRepeatingTarget) {
if ((string)$instrument === $targetFieldForm && (int)$repeat_instance > 0) {
// Saving on the repeating target form itself: use the current instance.
if ($repeat_instance === 1) {
$saveRepeatInstance = null;
} else {
$saveRepeatInstance = (int)$repeat_instance;
}
// \REDCap::logEvent(
// 'CTE Trigger - Classic Repeating Target: Using current repeat instance',
// "template={$templateFile} field={$targetField} event_id={$saveEventId} current_repeat_instance={$repeat_instance}",
// '',
// (string)$record,
// (int)$saveEventId
// );
} else {
// Saving from another form: use the latest instance of the target form.
$latest = $this->getLatestInstanceForInstrument((string)$record, (int)$saveEventId, $targetFieldForm);
$saveRepeatInstance = $latest !== null ? (int)$latest : null;
// \REDCap::logEvent(
// 'CTE Trigger - Classic Repeating Target: Using latest repeat instance for target form',
// "template={$templateFile} field={$targetField} event_id={$saveEventId} target_form={$targetFieldForm} latest_repeat_instance={$latest}",
// '',
// (string)$record,
// (int)$saveEventId
// );
}
}
$saved = $this->savePdfBytesToUploadField(
$filename,
$pdf_content,
$targetField,
(string)$record,
(int)$saveEventId,
$saveRepeatInstance
);
if (!$saved) {
\REDCap::logEvent(
'CTE Trigger - Failed to Save Report to field',
"Template: {$templateFile}, Field name: {$targetField}, event_id={$saveEventId}, repeat_instance=" . ($saveRepeatInstance ?? 'NULL'),
"",
(string)$record
);
continue;
}
\REDCap::logEvent(
'CTE Trigger - Generated PDF to field',
"template={$templateFile} field={$targetField} event_id={$saveEventId} repeat_instance=" . ($saveRepeatInstance ?? 'NULL'),
'',
(string)$record
);
}
}
/**
* Creates the templates, compiled templates, and images folders for the module, if they don't exist.
*
* Creates the templates, compiled templates, and images folders for the module, if they don't exist. Exits on an error if any of the
* module folders haven't been configured, or if any of the locations aren't writable.
*
* @since 1.0
* @access private
*/
private function createModuleFolders()
{
if (empty($this->templates_dir))
{
exit("<div class='red'><b>ERROR</b> Templates directory has not been set. Please contact your REDCap administrator.</div>");
}
else
{
if (!file_exists($this->templates_dir))
{
if (!mkdir($this->templates_dir, 0777, true))
{
exit("<div class='red'><b>ERROR</b> Unable to create directory $this->templates_dir to store templates. Please contact your systems administrator to make sure the location is writable.</div>");
}
}
}
if (empty($this->compiled_dir))
{
exit("<div class='red'><b>ERROR</b> Compiled templates directory has not been set. Please contact your REDCap administrator.</div>");
}
else
{
if (!file_exists($this->compiled_dir))
{
if (!mkdir($this->compiled_dir, 0777, true))
{
exit("<div class='red'><b>ERROR</b> Unable to create directory $this->compiled_dir to store compiled templates. Please contact your systems administrator to make sure the location is writable.</div>");
}
}
}
if (empty($this->temp_dir))
{
exit("<div class='red'><b>ERROR</b> Compiled templates directory has not been set. Please contact your REDCap administrator.</div>");
}
else
{
if (!file_exists($this->temp_dir))
{
if (!mkdir($this->temp_dir, 0777, true))
{
exit("<div class='red'><b>ERROR</b> Unable to create directory $this->temp_dir to store temporary files. Please contact your systems administrator to make sure the location is writable.</div>");
}
}
}
if (empty($this->img_dir))
{
exit("<div class='red'><b>ERROR</b> Images directory has not been set. Please contact your REDCap administrator.</div>");
}
else
{
if (!file_exists($this->img_dir))
{
if (!mkdir($this->img_dir, 0777, true))
{
exit("<div class='red'><b>ERROR</b> Unable to create directory $this->img_dir to store template. Please contact your systems administrator to make sure the location is writable.</div>");
}
}
}
}
/**
* Initializes a CKeditor with all the appropriate plugins.
*
* Injects Javascript to initialize the CKEditor in the given textarea element, alongside all its plugins,
* adjusting its height according to the argument passed.
*
* @param String $id The id of the textarea element to replace with the editor.
* @param Integer $height The height of the editor in pixels.
* @since 1.0
* @access private
*/
private function initializeEditor($id, $height)
{
?>
<script>
// CKEDITOR.plugins.addExternal('codemirror', '<?php print $this->getUrl("vendor/egorlaw/ckeditor_codemirror/plugin.js"); ?>');
CKEDITOR.replace('<?php print $id;?>', {
// extraPlugins: 'codemirror',
toolbar: [
{ name: 'clipboard', items: [ 'Undo', 'Redo' ] },
{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat'] },
{ name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-'] },
{ name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule' ] },
{ name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
{ name: 'colors', items: [ 'TextColor', 'BGColor', 'CopyFormatting' ] },
{ name: 'align', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
{ name: 'source', items: ['Source', 'searchCode', 'Find', 'SelectAll'] },
],
height: <?php print $height; ?>,
bodyClass: 'document-editor',
contentsCss: [ 'https://cdn.ckeditor.com/4.21.0/full-all/contents.css', '<?php print $this->getUrl("app.css"); ?>' ],
filebrowserBrowseUrl: '<?php print $this->getUrl("BrowseImages.php"); ?>&type=Images',
filebrowserUploadUrl: '<?php print $this->getUrl("UploadImages.php"); ?>&type=Images',
filebrowserUploadMethod: 'form',
clipboard_handleImages: false,
fillEmptyBlocks: false,
extraAllowedContent: '*{*}',
font_names: 'Arial/Arial, Helvetica, sans-serif; Times New Roman/Times New Roman, Times, serif; Courier; DejaVu; DejaVu Sans, sans-serif'
});
</script>
<?php
}
/**
* Checks the module permissions.
*
* Checks if the necessary directorys have been created, and whether the user has data export and report rights,
* which are needed to access the module's functionality.
*
* @since 1.0
* @access private
*/
private function checkPermissions()
{
if (empty($this->templates_dir) || !file_exists($this->templates_dir))
{
exit("<div class='red'><b>ERROR</b> Templates directory has not been set, or doesn't exist. Please contact your REDCap administrator.</div>");
}
if (empty($this->compiled_dir) || !file_exists($this->compiled_dir))
{
exit("<div class='red'><b>ERROR</b> Compiled templates directory has not been set, or doesn't exist. Please contact your REDCap administrator.</div>");
}
if (empty($this->img_dir) || !file_exists($this->img_dir))
{
exit("<div class='red'><b>ERROR</b> Images directory has not been set, or doesn't exist. Please contact your REDCap administrator.</div>");
}
$rights = REDCap::getUserRights($this->userid);
if ($rights[$this->userid]["data_export_tool"] === "0" || !$rights[$this->userid]["reports"])
{
exit("<div class='red'>You don't have permission to view this page</div><a href='" . $this->getUrl("index.php") . "'>Back to Front</a>");
}
}
/**
* Retrieves the latest repeatable instance for a record on a specified event.
*
* @since 3.1
*/
private function getLatestRecordInstance($record, $event_id = null)
{
$record_data = REDCap::getData("json", $record, null, $event_id, null, TRUE, FALSE, TRUE, null, TRUE);
$json = json_decode($record_data, true);
foreach($json as $index => $event_data)
{
$redcap_repeat_instance = $event_data["redcap_repeat_instance"];
if (isset($redcap_repeat_instance) && !empty($redcap_repeat_instance))
{
$instance = $redcap_repeat_instance == 1 ? null : $redcap_repeat_instance; // First instance is represented by null in db
}
}
return $instance;
}
/**
* Retrieves the latest repeatable instance for a record, if [event_id][field_name] is on a repeatable instrument/event, else return null.
*
* @since 3.1
*/
private function getLatestRepeatableInstance($record, $event_id, $field_name)
{
/**
* Check if field is on a repeatable form. If yes, then return latest instance, else return null.
*/
if($this->Proj->hasRepeatingFormsEvents())
{
$repeating_events = $this->Proj->getRepeatingFormsEvents();
$instruments = $repeating_events[$event_id];
if ($instruments === "WHOLE") // repeat whole event
{
$query = $this->framework->createQuery();
$query->add("select form_name from redcap_events_repeat where event_id = ?", [$event_id]);
$result = $query->execute();
if($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$instrument = $row["form_name"];
$fields = REDCap::getFieldNames($instrument); // Get fields in repeatable instrument
if (in_array($field_name, $fields)) // Check if field is part of repeatable instrument
{
return $this->getLatestRecordInstance($record, $event_id);
}
}
}
}
else if (is_array($instruments)) // repeate instruments on event
{
foreach($instruments as $instrument => $custom_repeat_label) // iterate through instruments on repeatable event
{
$fields = REDCap::getFieldNames($instrument); // Get fields in repeatable instrument
if (in_array($field_name, $fields)) // Check if field is part of repeatable instrument
{
return $this->getLatestRecordInstance($record, $event_id);
}
}
}
}
return null;
}
/**
* Checks that the field exists on the given event
*
* @since 3.1
*/
public function checkFieldInEvent($field_name, $event_id)
{
$query = $this->framework->createQuery();
$query->add("SELECT 1 from redcap_metadata
join redcap_events_forms
on redcap_metadata.form_name = redcap_events_forms.form_name
where redcap_events_forms.event_id = ? and redcap_metadata.field_name = ?", [$event_id, $field_name]);
$result = $query->execute();
if ($result)
{
return $result->num_rows > 0;
}
return false;
}
/**
* Saves a file to a REDCap field in the project. Assumes the field is a file upload field. Returns false on failure, and true otherwise.
* Currently no compatible with repeating events.
*/
public function saveFileToField($filename, $file_contents, $field_name, $record, $event_id)
{
// Save file to edocs tables in the REDCap database
$database_success = FALSE;
$upload_success = FALSE;
$dummy_file_name = $filename . ".pdf";
$dummy_file_name = preg_replace("/[^a-zA-Z-._0-9]/","_",$dummy_file_name);
$dummy_file_name = str_replace("__","_",$dummy_file_name);
$dummy_file_name = str_replace("__","_",$dummy_file_name);
$stored_name = date('YmdHis') . "_pid" . $this->pid . "_" . generateRandomHash(6) . ".pdf";
$upload_success = file_put_contents(EDOC_PATH . $stored_name, $file_contents);
if ($upload_success !== FALSE)
{
$dummy_file_size = $upload_success;
$query = $this->framework->createQuery();
$query->add("INSERT INTO redcap_edocs_metadata (stored_name,mime_type,doc_name,doc_size,file_extension,project_id,stored_date)
VALUES ('$stored_name','application/pdf',?,?,'pdf',?,?)", [$dummy_file_name, $dummy_file_size, $this->pid, date('Y-m-d H:i:s')]);
if ($query->execute())
{
$docs_id = db_insert_id();
// Always save report to the latest repeatable instance, otherwise null
$instance = $this->getLatestRepeatableInstance($record, $event_id, $field_name);
// See if field has had a previous value. If so, update; if not, insert.
$query = $this->framework->createQuery();
/*
$query->add("SELECT value FROM redcap_data
WHERE project_id = ? AND record = ? AND event_id = ? AND field_name = ?", [$this->pid, $record, $event_id, $field_name]);
*/
$query->add("SELECT value FROM " . $this->redcap_data_table . "
WHERE project_id = ? AND record = ? AND event_id = ? AND field_name = ?", [$this->pid, $record, $event_id, $field_name]);
if (!isset($instance))
{
$query->add("AND instance is NULL");
}
else
{
$query->add("AND instance = ?", [$instance]);
}
$result = $query->execute();
if ($result && $result->num_rows > 0) // row exists
{
// Set the file as "deleted" in redcap_edocs_metadata table, but don't really delete the file or the table entry (unless the File Version History is enabled for the project)
if ($GLOBALS['file_upload_versioning_global_enabled'] == '' && $this->Proj->project['file_upload_versioning_enabled'] != '1')
{
while ($row = $result->fetch_assoc()) {
$id = $row["value"];
}
$query = $this->framework->createQuery();
$query->add("UPDATE redcap_edocs_metadata SET delete_date = ? WHERE doc_id = ?", [NOW, $id]);
$query->execute();
}
$query = $this->framework->createQuery();
// $query->add("UPDATE redcap_data SET value = ? WHERE project_id = ? AND record = ? AND event_id = ? AND field_name = ?", [$docs_id, $this->pid, $record, $event_id, $field_name]);
$query->add("UPDATE " . $this->redcap_data_table . " SET value = ? WHERE project_id = ? AND record = ? AND event_id = ? AND field_name = ?", [$docs_id, $this->pid, $record, $event_id, $field_name]);
if (!isset($instance))
{
$query->add("AND instance is NULL");
}
else
{
$query->add("AND instance = ?", [$instance]);
}
}
else // row did not exist
{
// If this is a longitudinal project and this file is being added to an event without data,
// then add a row for the record ID field too (so it doesn't get orphaned).
if ($this->Proj->longitudinal)
{
$query = $this->framework->createQuery();
// $query->add("SELECT 1 FROM redcap_data WHERE project_id = ? AND record = ? AND event_id = ?", [$this->pid, $record, $event_id]);
$query->add("SELECT 1 FROM " . $this->redcap_data_table . " WHERE project_id = ? AND record = ? AND event_id = ?", [$this->pid, $record, $event_id]);
if ($instance > 1)
{
$query->add("AND instance = ?", [$instance]);
}
else
{
$query->add("AND instance is NULL");
}
$query->add("LIMIT 1");
$result = $query->execute();
if ($result && $result->num_rows == 0)
{
$instance = $instance > 1 ? $instance : "NULL";
$query = $this->framework->createQuery();
/*
$query->add("INSERT INTO redcap_data (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $this->Proj->table_pk, $record, $instance]);
*/
$query->add("INSERT INTO " . $this->redcap_data_table . " (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $this->Proj->table_pk, $record, $instance]);
$query->execute();
}
}
// Add an entry in redcap_data that contains the edoc ID
$query = $this->framework->createQuery();
if (!isset($instance))
{
/*
$query->add("INSERT INTO redcap_data (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $field_name, $docs_id, null]);
*/
$query->add("INSERT INTO " . $this->redcap_data_table . " (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $field_name, $docs_id, null]);
}
else
{
/*
$query->add("INSERT INTO redcap_data (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $field_name, $docs_id, $instance]);
*/
$query->add("INSERT INTO " . $this->redcap_data_table . " (project_id, event_id, record, field_name, value, instance) VALUES (?, ?, ?, ?, ?, ?)",
[$this->pid, $event_id, $record, $field_name, $docs_id, $instance]);
}
}
if ($query->execute())
{
// Logging event as DOC_UPLOAD allows file history to be built.
$redcap_log_event_table = method_exists('\REDCap', 'getLogEventTable') ? REDCap::getLogEventTable($this->pid) : "redcap_log_event";
$current_timestamp = date("YmdHis");
$ip = $_SERVER["REMOTE_ADDR"];
$description = isset($instance) ? "[instance = $instance],\n$field_name = '$docs_id'" : "$field_name = '$docs_id'";
$sql = str_replace("'", "''", $sql);
$query = $this->framework->createQuery();
$query->add("INSERT INTO $redcap_log_event_table (ts, user, ip, page, project_id, event, object_type, sql_log, pk, event_id, data_values, description) VALUES (?, ?, ?, 'ExternalModules/index.php', ?, 'DOC_UPLOAD', 'redcap_data', ?, ?, ?, ?, 'Upload Document')",
[$current_timestamp, $this->userid, $ip, $this->pid, $sql, $record, $event_id, $description]);
$query->execute();
return true;
}
}
}
return false;
}
/**
* CTE Trigger saves a file to a upload field considering save instance and event context
*
* @since 4.2.0
*/
public function saveFileToFieldForContext($filename, $file_contents, $field_name, $record, $event_id, $repeat_instance = null)
{
$database_success = FALSE;
$upload_success = FALSE;
$dummy_file_name = $filename . ".pdf";
$dummy_file_name = preg_replace("/[^a-zA-Z-._0-9]/", "_", $dummy_file_name);
$dummy_file_name = str_replace("__", "_", $dummy_file_name);
$dummy_file_name = str_replace("__", "_", $dummy_file_name);
$stored_name = date('YmdHis') . "_pid" . $this->pid . "_" . generateRandomHash(6) . ".pdf";
$upload_success = file_put_contents(EDOC_PATH . $stored_name, $file_contents);
if ($upload_success === false) {
return false;
}
$dummy_file_size = $upload_success;
$query = $this->framework->createQuery();
$query->add(
"INSERT INTO redcap_edocs_metadata
(stored_name, mime_type, doc_name, doc_size, file_extension, project_id, stored_date)
VALUES (?, 'application/pdf', ?, ?, 'pdf', ?, ?)",
[$stored_name, $dummy_file_name, $dummy_file_size, $this->pid, date('Y-m-d H:i:s')]
);
if (!$query->execute()) {
return false;
}
$docs_id = db_insert_id();
$instance = $repeat_instance !== null ? (int)$repeat_instance : null;
$sql = '';
$query = $this->framework->createQuery();
$query->add(
"SELECT value
FROM " . $this->redcap_data_table . "
WHERE project_id = ?
AND record = ?
AND event_id = ?
AND field_name = ?",
[$this->pid, $record, $event_id, $field_name]
);
if ($instance !== null) {
$query->add("AND instance = ?", [$instance]);
} else {
$query->add("AND instance IS NULL");
}
$result = $query->execute();
if ($result && $result->num_rows > 0) {
if ($GLOBALS['file_upload_versioning_global_enabled'] == '' && $this->Proj->project['file_upload_versioning_enabled'] != '1') {
while ($row = $result->fetch_assoc()) {
$old_doc_id = $row["value"];
}
$query = $this->framework->createQuery();
$query->add(
"UPDATE redcap_edocs_metadata
SET delete_date = ?
WHERE doc_id = ?",
[NOW, $old_doc_id]
);
$query->execute();
}
$query = $this->framework->createQuery();
$query->add(
"UPDATE " . $this->redcap_data_table . "
SET value = ?
WHERE project_id = ?
AND record = ?
AND event_id = ?
AND field_name = ?",
[$docs_id, $this->pid, $record, $event_id, $field_name]
);
if ($instance !== null) {
$query->add("AND instance = ?", [$instance]);
} else {
$query->add("AND instance IS NULL");
}