-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpdfInjector.php
1516 lines (1268 loc) · 51.7 KB
/
pdfInjector.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 STPH\pdfInjector;
/**
* REDCap External Module: PDF Injector
* PDF Injector is a REDCap module that enables you to populate fillable PDFs with record data from variables.
*
* @author Ekin Tertemiz, Swiss Tropical and Public Health Institute
*
*/
require 'vendor/autoload.php';
use Exception;
use Files;
use Piping;
use REDCap;
class pdfInjector extends \ExternalModules\AbstractExternalModule {
protected $isSurvey=false;
protected $taggedFields= [];
protected $lang;
private $injections;
private $report_id;
private $ui;
private $version;
private $old_version;
private $enum;
private $validation_type;
const SUPPORTED_ACTIONTAGS = ['@TODAY'];
const ACTION_TAG = '@PDFI';
/**
* Allows custom actions to be performed at the top of every page in REDCap
* (including plugins that render the REDCap page header)
*
* @return void
* @since 1.0.0
*
*/
function redcap_every_page_top($project_id = null) {
try {
// Check if user is logged in
if($this->getUser()) {
// Include Javascript and Styles on module page
if( $this->isModulePage("Injections")) {
$this->initBase();
$this->initModule();
}
// Include Button on Record Home
if ($this->isREDCapPage("DataEntry/record_home.php") && isset($_GET["id"]) && isset($_GET["pid"])) {
$this->initBase();
$this->initPageRecord();
}
// Include Button on Data Export (Reports) page
if ( $this->isREDCapPage("DataExport/index.php") && isset($_GET["report_id"]) && isset($_GET["pid"])) {
$this->initBase();
$str = $this->getProjectSetting("reports-enabled");
$reportsEnabled = array_map('trim', explode(',', $str));
$isReportEnabled = in_array($_GET["report_id"], $reportsEnabled);
if($isReportEnabled) {
$this->initPageDataExport();
}
}
}
} catch(Exception $e) {
// Do nothing...
}
}
/**
* Allows custom actions to be performed on a data entry form (excludes survey pages)
*
* @return void
* @since 3.0.0
*/
function redcap_data_entry_form($project_id, $record, $instrument, $event_id, $group_id, $repeat_instance) {
$this->initPageDataEntry($project_id, $record);
}
// ==== H A N D L E R S ====
/**
*
* Scans an uploaded PDF file and returns field data
* -> Called via RequestHandler.php over AJAX
*
* @return string
* @since 1.0.0
*/
public function scanFile(){
if(isset($_FILES['file']['name'])){
if(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) != "pdf") {
$this->errorResponse("Invalid file type.");
}
$filename = $_FILES['file']['name'];
$ext = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
$tmp_file = $_FILES['file']['tmp_name'];
// Process PDF with FPDM - Helper Class (FPDMH)
if (!class_exists("FPDMH")) include_once("classes/FPDMH.php");
$pdf = new FPDMH($tmp_file);
$fieldNames = $pdf->getFieldNames();
// Bring array in correct form so it works also with Updates
$fieldData = [];
foreach ($fieldNames as $key => $fieldName) {
$fieldData[] = [
"fieldName" => $fieldName,
"fieldValue" => ""
];
}
if($pdf->hasError) {
// Check for errors
$this->errorResponse("Invalid PDF.");
} else {
// Return as json response
$data = file_get_contents( $tmp_file );
$response = array(
'file' => $filename,
'title' => $this->generateTitle($filename),
'fieldData' => $fieldData,
'pdf64' => base64_encode($data)
);
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($response);
exit();
}
}
else {
$this->errorResponse("Unknown Error");
}
}
/**
* Scans field entered to modal to check if it is valid and returns meta data.
* -> Called via RequestHandler.php over AJAX
*
* @return array
* @since 1.0.0
*
*/
public function scanField($fieldName) {
$fieldMetaData = $this->getFieldMetaData($fieldName);
if($fieldMetaData != "") {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array($fieldMetaData));
} else $this->errorResponse("Field is invalid");
}
/**
* Gets all enum data
* @param string $project_id
* @param array $fields
* @return array
* @since 1.3.0
*
*/
private function getEnumData($project_id, $fields){
$field_names_array = [];
foreach ($fields as $key => $field) {
if( !empty($field["field_name"])){
$field_names_array[] = '"'.$field["field_name"] . '"';
}
}
$enum_data = [];
if (!empty($field_names_array)) {
$field_names = implode(",", $field_names_array);
// Get all enums (affects types: radio, checkbox and select)
$sql = "SELECT element_enum,field_name FROM redcap_metadata WHERE project_id = ? AND field_name IN('.$field_names.') AND element_enum IS NOT NULL";
$result = $this->query($sql, [ $project_id]);
while($row = $result->fetch_object()) {
// use parseEnum
$enum_data[$row->field_name] = parseEnum($row->element_enum);
}
}
return $enum_data;
}
/**
* Gets all validation type data
* @param string $project_id
* @param array $fields
* @return array
* @since 1.3.1
*
*/
private function getValidationTypeData($project_id, $fields) {
$field_names_array = [];
foreach ($fields as $key => $field) {
if( !empty($field["field_name"])){
$field_names_array[] = '"'.$field["field_name"] . '"';
}
}
$validation_type_data = [];
if(!empty($field_names_array)) {
$field_names = implode(",", $field_names_array);
// Gets all element validation types (Mainly to support date formats)
$sql = 'SELECT element_validation_type, field_name FROM redcap_metadata WHERE project_id = ? AND field_name IN('.$field_names.') AND element_validation_type IS NOT NULL';
$result = $this->query($sql, [ $project_id]);
while($row = $result->fetch_object()) {
$vDFormat = $this->getDateFormatDisplay($row->element_validation_type);
if($vDFormat) {
$validation_type_data[$row->field_name] = $vDFormat;
}
}
}
return $validation_type_data;
}
/**
* Renders Injection by filling field data into file
* -> Called via RequestHandler.php over AJAX
* @param string $document_id
* @param string $record_id
* @param string $project_id
* @param string $outputFormat
* @return string
* @since 1.0.0
*
*/
public function renderInjection($document_id, $record_id = null, $project_id = null, $outputFormat = null) {
// Check if document id is given
if( empty($document_id) ){
$this->errorResponse("Document ID missing.");
}
// Check if Injection data is available
$injections = self::getProjectSetting("pdf-injections");
if( empty($injections)) {
$this->errorResponse("No injection data available.");
}
// Check if doc_id exists
$injection = $injections[$document_id];
if(!$injection) {
$this->errorResponse("Injection does not exist.");
}
// Copy Edoc To Temp
$path = \Files::copyEdocToTemp( $document_id );
// Get Fields and check if has more than 0
$fields = $injection["fields"];
if(count( (array) $fields) == 0) {
$this->errorResponse("PDF has no fields.");
}
if($record_id != null){
# Do the actual render for a given record_id
if( !\Records::recordExists($project_id, $record_id) ) {
$this->errorResponse("Record does not exist.");
}
// Get Enum Data if not already set during batch processing
if( empty($this->enum[$project_id]) ) {
$this->enum[$project_id] = $this->getEnumData($project_id, $fields);
}
// Get Validation Type Data if not already set during batch processing
if( empty($this->validation_type[$project_id]) ) {
$this->validation_type[$project_id] = $this->getValidationTypeData($project_id, $fields);
}
// Prepare data access check arrays
$user_id = USERID;
$user_rights = \REDCap::getUserRights($user_id);
$no_access_forms = array_keys(array_filter($user_rights[$user_id]["forms"], function($value){
return $value == 0;
}));
$no_access_fields = [];
foreach ($no_access_forms as $key => $form) {
$no_access_fields = array_merge($no_access_fields, $this->getFieldNames($form));
}
foreach ($fields as $key => &$value) {
// Skip Injection if field is not mapped
if($value == "") {
continue;
}
// fetch variable value for each variable inside field
$field_name = $value["field_name"];
// If user has no data access rights return *NO ACCESS* as value and skip rest
if(in_array($field_name, $no_access_fields)) {
$value = "*NO ACCESS*";
continue;
}
$element_type = $value["element_type"];
// support multiple redcap_data tables
$data_table = method_exists('\REDCap', 'getDataTable') ? \REDCap::getDataTable($project_id) : "redcap_data";
$sql = "SELECT value FROM ".$data_table." WHERE record = ? AND project_id = ? AND field_name = ? ORDER BY instance DESC LIMIT 1";
$result = $this->query($sql,
[
$record_id,
$project_id,
$field_name,
]
);
$field_value = $result->fetch_object()->value;
// Detect empty record values and set their field value to empty string
if (empty($field_value)) {
$value= "";
continue;
}
// Check if element type has enum
if( !empty($this->enum[$project_id][$field_name]) ) {
$value = $this->enum[$project_id][$field_name][$field_value];
} else {
// Check if field value has variables or action tags
$hasVariables = preg_match('/([\[\]])\w+/', $field_value);
$hasActiontags = preg_match('/([\@])\w+/', $field_value);
if($hasVariables) {
$data = \REDCap::getData($project_id, 'array', $record_id);
$value = Piping::replaceVariablesInLabel($field_value, $record_id, null, 1, $data, false, $project_id, false,
"", 1, false, false, "", null, true, false, false);
}
else if($hasActiontags){
foreach (self::SUPPORTED_ACTIONTAGS as $key => $actiontag) {
if(\Form::hasActionTag($actiontag, $field_value)) {
$value = $this->replaceActionTag($field_value, $actiontag);
}
else {
// Fix rendering of '@' without action tags!
$value = $field_value;
}
}
}
else {
$value = $field_value;
}
}
// Check if element has validation type (support date formats)
if( !empty($this->validation_type[$project_id][$field_name]) ) {
$value = $this->renderDateFormat($value, $this->validation_type[$project_id][$field_name]);
}
}
} else {
// For Preview
foreach ($fields as $key => &$value) {
if(!empty($value)) {
$value = "[" . $value["field_name"] . "]";
} else {
$value = "(undefined)";
}
}
}
if (!class_exists("FPDMH")) include_once("classes/FPDMH.php");
$pdf = new FPDMH($path);
// Add checkbox support
$pdf->useCheckboxParser = true;
// Fill fields into PDF
$pdf->Load($fields,true);
$pdf->Merge(); // Does not support $pdf->Merge(true) yet (which would trigger PDF Flatten to "close" form fields via pdftk)
# Future support of PDF flattening would be implemented as optional module setting ensuring pdftk is installed on server
$string = $pdf->Output( "S" );
if( $outputFormat == "json" ) {
header('Content-Type: application/json; charset=UTF-8');
header("HTTP/1.1 200 ");
//$base64_string = base64_encode($string);
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = 'data:application/' . $type . ';base64,' . base64_encode($string);
echo json_encode(array("data" => $data));
}
if ($outputFormat == "pdf") {
header('Content-type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
$filename = uniqid($record_id) . "_" . $injection["fileName"];
header('Content-Disposition: inline; filename="' . basename($filename) . '"');
echo $string;
} else {
return $string;
}
}
private function validateFileUpload() {
if(!$_FILES) {
// Throw exception if no file has been set.
throw new Exception("The file upload is not set.");
}
if( pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) != "pdf") {
// Throw exception if file extension is not PDF
throw new Exception("The file type is invalid.");
}
if( $this->PDFhasError($_FILES['file']['tmp_name']) ) {
// Throw exception if PDF is not valid.
throw new Exception("The PDF file is invalid.");
}
}
/**
* Handles $_POST for modes Create, Update, Delete
* @return mixed
* @since 1.0.0
*
*/
private function handlePost() {
if($_POST) {
// if Create:
// New Injection
if($_POST["mode"] == "CREATE") {
$this->validateFileUpload();
// Upload PDF to REDCap edoc storage
$document_id = Files::uploadFile($_FILES['file']);
if($document_id == 0 ) {
throw new Exception("The PDF upload to REDCap storage failed.");
}
// Upload Thumbnail to REDCap edoc storage
$thumbnail_id = $this->saveThumbnail($document_id, $_POST['thumbnail_base64']);
if($thumbnail_id == 0) {
throw new Exception("The Thumbnail upload to REDCap storage failed.");
}
// Create new Injection entry in database if upload successful
// Validate fields before save
$validFields = $this->filterForValidVariables($_POST["fields"]);
if (!class_exists("Injection")) include_once("classes/Injection.php");
$injection = new Injection;
$injection->setValues(
$_POST["title"],
$_POST["description"],
$validFields,
$_FILES['file']['name'],
$document_id,
$thumbnail_id
);
// Save Injection to Storage
$this->saveInjection( $injection );
} if($_POST["mode"] == "UPDATE") {
//$this->validateFileUpload();
if (!class_exists("Injection")) include_once("classes/Injection.php");
// Create old injection instance by id
$oldInjection = new Injection;
$oldInjection->setInjectionById($this->injections, $_POST["document_id"] );
$document_id = $_POST["document_id"];
$thumbnail_id = $_POST["thumbnail_id"];
$filename = $oldInjection->get("fileName");
// If file has changed overwrite document and thumbnail ids
if( $_POST["hasFileChanged"] ) {
// Upload PDF and Thumbnail to REDCap edoc storage
$document_id = Files::uploadFile($_FILES['file']);
$thumbnail_id = $this->saveThumbnail($document_id, $_POST['thumbnail_base64']);
$filename = $_FILES['file']['name'];
if( $document_id != 0 && $thumbnail_id != 0 ) {
// Remove old injection with old id
$this->deleteInjection( $oldInjection );
} else throw new Exception($this->tt("injector_15"));
}
$validFields = $this->filterForValidVariables($_POST["fields"]);
// Create new injection instance
$newInjection = new Injection;
$newInjection->setValues(
$_POST["title"],
$_POST["description"],
$validFields,
$filename,
intval($document_id),
intval($thumbnail_id),
$oldInjection->get("created")
);
$hasUpdate = $this->hasUpdate( $oldInjection, $newInjection );
if( $hasUpdate ) {
// Save Injection to Storage
$this->saveInjection( $newInjection );
}
} if($_POST["mode"] == "DELETE") {
if(!$_POST["document_id"]) {
throw new Exception("The document id not set.");
}
if (!class_exists("Injection")) include_once("classes/Injection.php");
$injection = new Injection;
$injection->setInjectionById( $this->injections, $_POST["document_id"]);
// Delete Injection from Storage
$this->deleteInjection( $injection );
}
$this->forceRedirect();
}
}
// Parse fields for @PDFI Action Tag
// https://github.com/lsgs/redcap-instance-table/blob/54f46e874d91c9faed907562df520f41b071ee7b/InstanceTable.php#L126
private function setTaggedFields() {
$this->taggedFields = array();
$instrumentFields = REDCap::getDataDictionary('array', false, true, $this->instrument);
if(count($this->injections) === 0) return;
foreach ($instrumentFields as $fieldName => $fieldDetails) {
$matches = array();
// check field_type and form_name
if ($fieldDetails['field_type']==='descriptive' && $fieldDetails['form_name'] == $_GET["page"]){
if( preg_match(
"/".self::ACTION_TAG."\s*=\s*'?((\d+(,\d+)*))'?\s?/",
$fieldDetails['field_annotation'],
$matches
)) {
$injection_ids = explode(',', $matches[1]);
$valid_injections = [];
// validate injection ids
foreach ($injection_ids as $key => $injection_id) {
$injection = $this->injections[$injection_id];
// skip if injection does not exist
if(!$injection) continue;
$valid_injections[] = $injection;
}
// skip if no valid injections
if(empty($valid_injections)) {
continue;
}
$this->taggedFields[] = [
"form_name"=> $fieldDetails["form_name"],
"field_name" => $fieldDetails["field_name"],
"injections" => $valid_injections
];
}
}
}
}
private function includeButtonJavaScript($project_id, $record) {
// Prepare parameter array to be passed to Javascript
$js_params = array (
"debug" => $this->getProjectSetting("javascript-debug") == true,
"project_id" => $project_id,
"record_id" => $record,
"tagged_fields" => $this->taggedFields
);
?>
<link rel="stylesheet" href="<?= $this->getUrl('css/styles.css'); ?>">
<template id="pdfi-download-button">
<tr style="display:flex;">
<td class="col-7">
<i class="fa-solid fa-cube text-info me-2"></i>
<small style="font-weight:normal;">This field is modified by an external module: <b>PDF Injector</b></small>
</td>
<td class="data col-5">
<div class="btn-group">
<button style="font-size:13px;padding:6px 8px;" class="pdfi-download-button btn btn-defaultrc btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-syringe"></i> PDF Injection
</button>
<ul class="dropdown-menu">
</ul>
</div>
</td>
</tr>
</template>
<script src="<?php print $this->getUrl('js/Button.js'); ?>"></script>
<script>
STPH_pdfInjector.params = <?= json_encode($js_params) ?>;
STPH_pdfInjector.previewUrl = "<?= $this->getUrl("preview.php") ?>";
$(function() {
$(document).ready(function(){
STPH_pdfInjector.initButtons();
})
});
</script>
<?php
}
// ==== I N I T I A L I Z E R S ====
/**
* Initializes module base
* @return void
* @since 1.0.0
*
*/
private function initBase() {
$this->setInjections();
$this->report_id = $this->sanitize($_GET["report_id"]);
$this->ui = self::getProjectSetting("ui-mode");
$this->includePageJavascript();
$this->includePageCSS();
}
/**
* Initializes module handler
* @return void
* @since 1.0.0
*
*/
private function initModule() {
$this->handlePost();
}
/**
* Initializes module on record page
* @return void
* @since 1.0.0
*
*/
private function initPageRecord(){
if(count((array)$this->injections) > 0) {
$this->includePreviewModal();
if($this->ui == 1 || $this->ui == 3) {
$this->includeModuleTip();
}
if($this->ui == 2 || $this->ui == 3) {
$this->includeModuleContainer();
}
}
}
/**
* Initializes module on Data Export page
* @return void
* @since 1.0.0
*
*/
public function initPageDataExport() {
$this->includeModalDataExport();
$this->includePageJavascriptDataExport();
}
/**
* Initializes module on Data Entry page
*
* @return void
* @since 3.0.0
*/
private function initPageDataEntry($project_id, $record) {
$this->setInjections();
$this->ui = self::getProjectSetting("ui-mode");
// Check if any field of type descriptive contains PDFI action tags
$this->setTaggedFields();
if(count($this->taggedFields)) {
$this->includeButtonJavaScript($project_id, $record);
}
}
// ==== I N J E C T I O N S ====
/**
* Gets injections
* @return array
* @since 1.0.0
*
*/
public function getInjections() {
return $this->injections;
}
/**
* Sets Injections
* @return void
* @since 1.3.8
*
*/
private function setInjections() {
$this->injections = self::getProjectSetting("pdf-injections") ?? [];
}
/**
* Saves Injection to database
* @param Injection $injection
* @return void
* @since 1.0.0
*/
private function saveInjection( $injection ) {
$injections = $this->injections;
// Insert new injection to injections array
$injections[ $injection->get("document_id") ] = $injection->getValuesAsArray();
// Save injections data into module data base
$this->setProjectSetting("pdf-injections", $injections);
// Set Injections variable to latest state
$this->setInjections();
}
/**
* Deletes Injection from database
* @param Injection $injection
* @return boolean
* @since 1.0.0
*/
private function deleteInjection( $injection ) {
$injections = $this->injections;
// Remove injection from Injections Array
unset( $injections [$injection->get("document_id") ] );
// Flag files for deletion
// Actual deletion through (Cron) Jobs::RemoveTempAndDeletedFiles()
$deletedPDF = Files::deleteFileByDocId( $injection->get("document_id") , PROJECT_ID);
$deletedThumbnail = Files::deleteFileByDocId( $injection->get("thumbnail_id") , PROJECT_ID);
// Save updated injections data into module data base
if($deletedPDF && $deletedThumbnail) {
$this->setProjectSetting("pdf-injections", $injections);
//$this->injections = self::getProjectSetting("pdf-injections"); //replaced by setInjections()
$this->setInjections();
return true;
} else throw new Exception($this->tt("injector_15"));
}
/**
* Checks if Injection has update by comparing old and new Injections
* @param Injection $oldInjection
* @param Injection $newInjection
* @return boolean
* @since 1.0.0
*/
private function hasUpdate(Injection $oldInjection, Injection $newInjection ) {
$o_arr = $oldInjection->getValuesAsArray();
$n_arr = $newInjection->getValuesAsArray();
unset($o_arr["created"]);
unset($n_arr["created"]);
unset($o_arr["updated"]);
unset($n_arr["updated"]);
$diff_level_1 = !empty(array_diff_assoc($o_arr, $n_arr));
if($diff_level_1) {
return true;
}
$o_arr_f = $o_arr["fields"];
$n_arr_f = $n_arr["fields"];
$diff_level_2 = !empty(array_diff_assoc($o_arr_f, $n_arr_f));
if($diff_level_2) {
return true;
}
foreach ($o_arr_f as $field => $meta) {
// Typecast to array if is not array, otherwise array_diff_assoc will throw an exception
$o_arr_f_n = is_array($meta) ? $meta : (array) $meta;
$n_arr_f_n = is_array($n_arr_f[$field]) ? $n_arr_f[$field] : (array) $n_arr_f[$field];
$diff_level_3 = !empty(array_diff_assoc($o_arr_f_n, $n_arr_f_n));
if( $diff_level_3 ){
break;
// exit loop if difference found
}
}
return ( $diff_level_1 || $diff_level_2 || $diff_level_3);
}
// ==== H E L P E R S ====
/**
* Gets Field Meta Data
* @param string $fieldName
* @return array|string
* @since 1.3.0
*
*/
private function getFieldMetaData($fieldName, $pid=null) {
if($pid == null) {
$pid = PROJECT_ID;
}
$sql = 'SELECT * FROM redcap_metadata WHERE project_id = ? AND field_name = ?';
$result = $this->query($sql, [$pid, $fieldName]);
if($result->num_rows == 1) {
$fieldMetaData = $result->fetch_object();
$result->close();
return array(
"field_name" => $fieldMetaData->field_name,
"element_type" => $fieldMetaData->element_type
);
}
else return "";
}
/**
* Filters fields, checks if valid and returns their meta data
* @param array $fields
* @return array
* @since 1.0.0
*
*/
private function filterForValidVariables($fields = null) {
if($fields != null) {
foreach ($fields as $fieldName => &$fieldValue) {
$fieldValue = $this->getFieldMetaData($fieldValue);
}
} else {
$fields = [];
}
return $fields;
}
/**
* Saves thumbnail from BASE64 string source as PNG into edoc storage
* @param string $d_id
* @param string $b64
* @return string
* @since 1.0.0
*
*/
private function saveThumbnail($d_id, $b64) {
if ( isset( $b64 ) && $b64 != '' ) {
// Retrieve Thumbnail as Base64 String and save to docs
$_FILES['thumbnailFile']['type'] = "image/png";
$_FILES['thumbnailFile']['name'] = "thumbnail_injection_" . $d_id . ".png";
$_FILES['thumbnailFile']['tmp_name'] = APP_PATH_TEMP . "thumbnail_injection_" . $d_id . "_" . substr(sha1(mt_rand()), 0, 12) . ".png";
file_put_contents($_FILES['thumbnailFile']['tmp_name'], base64_decode(str_replace(' ', '+', $b64)));
$_FILES['thumbnailFile']['size'] = filesize($_FILES['thumbnailFile']['tmp_name']);
// Upload File to REDCap, returns edoc id
return Files::uploadFile($_FILES['thumbnailFile']);
} else return 0;
}
/**
* Converts PNG from edoc storage to BASE64
* @param string $doc_id
* @return string
* @since 1.0.0
*
*/
public function base64FromId($doc_id) {
//$path = EDOC_PATH . Files::getEdocName( $doc_id, true );
$path = \Files::copyEdocToTemp( $doc_id );
if($path) {
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
}
/**
* Generates injection default title from file name
* @param string $fileName
* @return string
* @since 1.0.0
*
*/
public function generateTitle($fileName) {
$s = substr($fileName, 0, -4);
$s = str_replace("_", " ", $s);
$s = str_replace("-", " ", $s);
return $s;
}
/**
* Replaces Action Tag within Injection
* @param string $label
* @param string $actiontag
* @return string
* @since 1.0.0
*/
private function replaceActionTag($label, $actiontag) {
switch ($actiontag) {
case '@TODAY':
$str = date("d.m.Y");
break;
default:
$str = "";
break;
}
return str_replace($actiontag, $str, $label);
}
/**
* Forces redirect to same page to clear $_POST data
* @return void
* @since 1.0.0
*/
private function forceRedirect() {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
|| $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
header('Location: '.$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}