/
C_Document.class.php
1428 lines (1298 loc) · 69.8 KB
/
C_Document.class.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
/**
* C_Document.class.php
*
* @package OpenEMR
* @link https://www.open-emr.org
* @author Brady Miller <brady.g.miller@gmail.com>
* @author Jerry Padgett <sjpadgett@gmail.com>
* @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
* @copyright Copyright (c) 2019-2024 Jerry Padgett <sjpadgett@gmail.com>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
require_once(__DIR__ . "/../library/forms.inc.php");
require_once(__DIR__ . "/../library/patient.inc.php");
use OpenEMR\Common\Acl\AclMain;
use OpenEMR\Common\Crypto\CryptoGen;
use OpenEMR\Common\Csrf\CsrfUtils;
use OpenEMR\Common\Logging\SystemLogger;
use OpenEMR\Common\Twig\TwigContainer;
use OpenEMR\Services\DocumentTemplates\DocumentTemplateService;
use OpenEMR\Services\FacilityService;
use OpenEMR\Services\PatientService;
use OpenEMR\Events\PatientDocuments\PatientDocumentTreeViewFilterEvent;
use OpenEMR\Events\PatientDocuments\PatientRetrieveOffsiteDocument;
class C_Document extends Controller
{
public $documents;
public $document_categories;
public $tree;
public $_config;
public $manual_set_owner = false; // allows manual setting of a document owner/service
public $facilityService;
public $patientService;
public $_last_node;
private $Document;
private $cryptoGen;
private bool $skip_acl_check = false;
private DocumentTemplateService $templateService;
public function __construct($template_mod = "general")
{
parent::__construct();
$this->facilityService = new FacilityService();
$this->patientService = new PatientService();
$this->documents = array();
$this->template_mod = $template_mod;
$this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING'] ?? ''));
$this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
if (php_sapi_name() !== 'cli') {
// skip when this is being called via command line for the ccda importing
$this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
}
$this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
//get global config options for this namespace
$this->_config = $GLOBALS['oer_config']['documents'];
$this->_args = array("patient_id" => ($_GET['patient_id'] ?? null));
$this->assign("STYLE", $GLOBALS['style']);
$t = new CategoryTree(1);
//print_r($t->tree);
$this->tree = $t;
$this->Document = new Document();
// Create a crypto object that will be used for for encryption/decryption
$this->cryptoGen = new CryptoGen();
$this->templateService = new DocumentTemplateService();
}
public function upload_action($patient_id, $category_id)
{
$category_name = $this->tree->get_node_name($category_id);
$this->assign("category_id", $category_id);
$this->assign("category_name", $category_name);
$this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
$this->assign("patient_id", $patient_id);
// Added by Rod to support document template download from general_upload.html.
// Cloned from similar stuff in manage_document_templates.php.
$templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
$templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
if (file_exists($templatedir)) {
$dh = opendir($templatedir);
}
if (!empty($dh)) {
$templateslist = array();
while (false !== ($sfname = readdir($dh))) {
if (substr($sfname, 0, 1) == '.') {
continue;
}
$templateslist[$sfname] = $sfname;
}
closedir($dh);
ksort($templateslist);
foreach ($templateslist as $sfname) {
$templates_options .= "<option value='" . attr($sfname) .
"'>" . text($sfname) . "</option>";
}
}
$this->assign("TEMPLATES_LIST", $templates_options);
// will call as module or individual template.
$templates_list = $this->templateService->renderPortalTemplateMenu($patient_id, '-patient-', false) ?? [];
$this->assign("TEMPLATES_LIST_PATIENT", $templates_list);
$activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
$this->assign("activity", $activity);
return $this->list_action($patient_id);
}
public function zip_dicom_folder($study_name = null)
{
$zip = new ZipArchive();
$zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {
foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
$zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
$fparts = pathinfo($name);
if (empty($fparts['extension'])) {
// viewer requires lowercase.
$fparts['extension'] = "dcm";
$name = $fparts['filename'] . ".dcm";
}
if ($fparts['extension'] == "DCM") {
// viewer requires lowercase.
$fparts['extension'] = "dcm";
$name = $fparts['filename'] . ".dcm";
}
// required extension for viewer
if ($fparts['extension'] != "dcm") {
continue;
}
move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
$zip->addFile($zfn, $name);
}
$zip->close();
} else {
return false;
}
$file_array['name'][] = $study_name;
$file_array['type'][] = 'zip';
$file_array['tmp_name'][] = $zip_name;
$file_array['error'][] = '';
$file_array['size'][] = filesize($zip_name);
return $file_array;
}
//Upload multiple files on single click
public function upload_action_process()
{
// Collect a manually set owner if this has been set
// Used when want to manually assign the owning user/service such as the Direct mechanism
$non_HTTP_owner = false;
if ($this->manual_set_owner) {
$non_HTTP_owner = $this->manual_set_owner;
}
$couchDB = false;
$harddisk = false;
if ($GLOBALS['document_storage_method'] == 0) {
$harddisk = true;
}
if ($GLOBALS['document_storage_method'] == 1) {
$couchDB = true;
}
if ($_POST['process'] != "true") {
return;
}
$doDecryption = false;
$encrypted = $_POST['encrypted'] ?? false;
$passphrase = $_POST['passphrase'] ?? '';
if (
!$GLOBALS['hide_document_encryption'] &&
$encrypted && $passphrase
) {
$doDecryption = true;
}
if (is_numeric($_POST['category_id'])) {
$category_id = $_POST['category_id'];
} else {
$category_id = 1;
}
$patient_id = 0;
if (isset($_GET['patient_id']) && !$couchDB) {
$patient_id = $_GET['patient_id'];
} elseif (is_numeric($_POST['patient_id'])) {
$patient_id = $_POST['patient_id'];
}
// ensure user has access to the category that is being uploaded to
$skipUpload = false;
if (!$this->isSkipAclCheck()) {
$acoSpec = sqlQuery("SELECT `aco_spec` from `categories` WHERE `id` = ?", [$category_id])['aco_spec'];
if (AclMain::aclCheckAcoSpec($acoSpec) === false) {
$error = xl("Not authorized to upload to the selected category.\n");
$skipUpload = true;
(new SystemLogger())->debug("An attempt was made to upload a document to an unauthorized category", ['user-id' => $_SESSION['authUserID'], 'patient-id' => $patient_id, 'category-id' => $category_id]);
}
}
if (!$skipUpload && !empty($_FILES['dicom_folder']['name'][0])) {
// let's zip um up then pass along new zip
$study_name = $_POST['destination'] ? (trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
$study_name = preg_replace('/\s+/', '_', $study_name);
$_POST['destination'] = "";
$zipped = $this->zip_dicom_folder($study_name);
if ($zipped) {
$_FILES['file'] = $zipped;
}
// and off we go! just fall through and let routine
// do its normal file processing..
}
$sentUploadStatus = array();
if (!$skipUpload && count($_FILES['file']['name']) > 0) {
$upl_inc = 0;
foreach ($_FILES['file']['name'] as $key => $value) {
$fname = $value;
$error = "";
if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
$fname = $value;
if (empty($fname)) {
$fname = htmlentities("<empty>");
}
$error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
if ($_FILES['file']['size'][$key] == 0) {
$error .= xl("The system does not permit uploading files of with size 0.") . "\n";
}
} elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
$error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
} else {
// Test for a zip of DICOM images
if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
$za = new ZipArchive();
$handler = $za->open($_FILES['file']['tmp_name'][$key]);
if ($handler) {
$mimetype = "application/dicom+zip";
for ($i = 0; $i < $za->numFiles; $i++) {
$stat = $za->statIndex($i);
$fp = $za->getStream($stat['name']);
if ($fp) {
$head = fread($fp, 256);
fclose($fp);
if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
$mimetype = "application/zip";
break;
}
unset($head);
// if here -then a DICOM
$parts = pathinfo($stat['name']);
if ($parts['extension'] != "dcm" || empty($parts['extension'])) { // required extension for viewer
$new_name = $parts['filename'] . ".dcm";
$za->renameIndex($i, $new_name);
$za->renameName($parts['filename'], $new_name);
}
} else { // Rarely here
$mimetype = "application/zip";
break;
}
}
$za->close();
if ($mimetype == "application/dicom+zip") {
sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
$_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
}
}
}
$tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
$filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
fclose($tmpfile);
if ($doDecryption) {
$filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
if ($filetext === false) {
error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
$filetext = "";
}
}
if ($_POST['destination'] != '') {
$fname = $_POST['destination'];
}
// test for single DICOM and assign extension if missing.
if (strpos($filetext, 'DICM') !== false) {
$mimetype = 'application/dicom';
$parts = pathinfo($fname);
if (!$parts['extension']) {
$fname .= '.dcm';
}
}
// set mimetype (if not already set above)
if (empty($mimetype)) {
$mimetype = mime_content_type($_FILES['file']['tmp_name'][$key]);
}
// if mimetype still empty, then do not upload the file
if (empty($mimetype)) {
$error = xl("Unable to discover mimetype, so did not upload " . $_FILES['file']['tmp_name'][$key]) . ".\n";
continue;
}
$d = new Document();
$rc = $d->createDocument(
$patient_id,
$category_id,
$fname,
$mimetype,
$filetext,
empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
$non_HTTP_owner,
$_FILES['file']['tmp_name'][$key]
);
if ($rc) {
$error .= $rc . "\n";
} else {
$this->assign("upload_success", "true");
}
$sentUploadStatus[] = $d;
$this->assign("file", $sentUploadStatus);
}
// Option to run a custom plugin for each file upload.
// This was initially created to delete the original source file in a custom setting.
$upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
if (file_exists($upload_plugin)) {
include_once($upload_plugin);
}
$upload_plugin_pp = 'documentUploadPostProcess';
if (function_exists($upload_plugin_pp)) {
$tmp = call_user_func($upload_plugin_pp, $value, $d);
if ($tmp) {
$error = $tmp;
}
}
// Following is just an example of code in such a plugin file.
/*****************************************************
public function documentUploadPostProcess($filename, &$d) {
$userid = $_SESSION['authUserID'];
$row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
$owner = strtolower($row['username']);
$dn = '1_' . ucfirst($owner);
$filepath = "/shared_network_directory/$dn/$filename";
if (@unlink($filepath)) return '';
return "Failed to delete '$filepath'.";
}
*****************************************************/
}
}
$this->assign("error", $error);
//$this->_state = false;
$_POST['process'] = "";
//return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
}
public function note_action_process($patient_id)
{
// this public function is a dual public function that will set up a note associated with a document or send a document via email.
if ($_POST['process'] != "true") {
return;
}
$n = new Note();
$n->set_owner($_SESSION['authUserID']);
parent::populate_object($n);
if ($_POST['identifier'] == "no") {
// associate a note with a document
$n->persist();
} elseif ($_POST['identifier'] == "yes") {
// send the document via email
$d = new Document($_POST['foreign_id']);
$url = $d->get_url();
$storagemethod = $d->get_storagemethod();
$couch_docid = $d->get_couch_docid();
$couch_revid = $d->get_couch_revid();
if ($couch_docid && $couch_revid) {
$couch = new CouchDB();
$resp = $couch->retrieve_doc($couch_docid);
$content = $resp->data;
if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
$log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
$log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
//$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
$this->document_upload_download_log($d->get_foreign_id(), $log_content);
die(xlt("File retrieval from CouchDB failed"));
}
// place it in a temporary file and will remove the file below after emailed
$temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
$fh = fopen($temp_couchdb_url, "w");
fwrite($fh, base64_decode($content));
fclose($fh);
$temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
} else {
$url = preg_replace("|^(.*)://|", "", $url);
// Collect filename and path
$from_all = explode("/", $url);
$from_filename = array_pop($from_all);
$from_pathname_array = array();
for ($i = 0; $i < $d->get_path_depth(); $i++) {
$from_pathname_array[] = array_pop($from_all);
}
$from_pathname_array = array_reverse($from_pathname_array);
$from_pathname = implode("/", $from_pathname_array);
$temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
}
if (!file_exists($temp_url)) {
echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $temp_url;
}
$url = $temp_url;
$pdetails = getPatientData($patient_id);
$pname = $pdetails['fname'] . " " . $pdetails['lname'];
$this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
if ($couch_docid && $couch_revid) {
// remove the temporary couchdb file
unlink($temp_couchdb_url);
}
}
$this->_state = false;
$_POST['process'] = "";
return $this->view_action($patient_id, $n->get_foreign_id());
}
public function default_action()
{
return $this->list_action();
}
public function view_action(string $patient_id = null, $doc_id)
{
global $ISSUE_TYPES;
require_once(dirname(__FILE__) . "/../library/lists.inc.php");
$d = new Document($doc_id);
$notes = $d->get_notes();
$this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
$this->assign("file", $d);
$this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
$this->assign("NOTE_ACTION", $this->_link("note"));
$this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
$this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
$this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
$this->assign("webroot", $GLOBALS['webroot']);
// Added by Rod to support document delete:
$delete_string = '';
if (AclMain::aclCheckCore('patients', 'docs_rm')) {
$delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
")'>" . xlt('Delete') . "</a>";
}
$this->assign("delete_string", $delete_string);
$this->assign("REFRESH_ACTION", $this->_link("list"));
$this->assign("VALIDATE_ACTION", $this->_link("validate") .
"document_id=" . $d->get_id() . "&process=true");
// Added by Rod to support document date update:
$this->assign("DOCDATE", $d->get_docdate());
$this->assign("UPDATE_ACTION", $this->_link("update") .
"document_id=" . $d->get_id() . "&process=true");
// Added by Rod to support document issue update:
$issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
$ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
"pid = ? " . // AND enddate IS NULL " .
"ORDER BY type, begdate", array($patient_id));
while ($irow = sqlFetchArray($ires)) {
$desc = $irow['type'];
if ($ISSUE_TYPES[$desc]) {
$desc = $ISSUE_TYPES[$desc][2];
}
$desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
$sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
$issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
}
$this->assign("ISSUES_LIST", $issues_options);
// For tagging to encounter
// Populate the dropdown with patient's encounter list
$this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
$encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
$result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
"LEFT JOIN openemr_postcalendar_categories ON fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = ? ORDER BY fe.date desc", array($patient_id));
if (sqlNumRows($result_docs) > 0) {
while ($row_result_docs = sqlFetchArray($result_docs)) {
$sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
$encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>" . text(oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date'])))) . "-" . text(xl_appt_category($row_result_docs['pc_catname'])) . "</option>";
}
}
$this->assign("ENC_LIST", $encOptions);
//clear encounter tag
if ($d->get_encounter_id() != 0) {
$this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
} else {
$this->assign('clear_encounter_tag', 'javascript:void(0)');
}
//Populate the dropdown with category list
$visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
$cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
while ($crow = sqlFetchArray($cres)) {
$catid = $crow['pc_catid'];
if ($catid < 9 && $catid != 5) {
continue; // Applying same logic as in new encounter page.
}
$visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
}
$this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
$this->assign("notes", $notes);
$this->assign("PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
// Populate the dropdown with procedure order list
$imgOptions = "<option value='0'>-- " . xlt('Select Procedure') . " --</option>";
$imgOrders = sqlStatement("select procedure_name,po.procedure_order_id,procedure_code,poc.procedure_order_title from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ?", array($patient_id));
$mapping = $this->get_mapped_procedure($d->get_id());
if (sqlNumRows($imgOrders) > 0) {
while ($row = sqlFetchArray($imgOrders)) {
$sel_proc = '';
if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
$sel_proc = 'selected';
}
$imgOptions .= "<option value='" . attr($row['procedure_order_id']) . "' data-code='" . attr($row['procedure_code']) . "' $sel_proc>" . text($row['procedure_name'] . ' - ' . $row['procedure_code'] . ' : ' . ucfirst($row['procedure_order_title'])) . "</option>";
}
}
$this->assign('TAG_PROCEDURE_LIST', $imgOptions);
$this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
$this->_last_node = null;
$menu = new HTML_TreeMenu();
//pass an empty array because we don't want the documents for each category showing up in this list box
$rnode = $this->array_recurse($this->tree->tree, $patient_id, array());
$menu->addItem($rnode);
$treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
$this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
$activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
$this->assign("activity", $activity);
return $this->list_action($patient_id);
}
/**
* Retrieve file from hard disk / CouchDB.
* In case that file isn't download this public function will return thumbnail image (if exist).
* @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
* @param (string) $context - given a special document scenario (e.g.: patient avatar, custom image viewer document, etc), the context can be set so that a switch statement can execute a custom strategy.
* */
public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
{
$encrypted = $_POST['encrypted'] ?? false;
$passphrase = $_POST['passphrase'] ?? '';
$doEncryption = false;
if (
!$GLOBALS['hide_document_encryption'] &&
$encrypted == "true" &&
$passphrase
) {
$doEncryption = true;
}
//controller public function ruins booleans, so need to manually re-convert to booleans
if ($as_file == "true") {
$as_file = true;
} elseif ($as_file == "false") {
$as_file = false;
}
if ($original_file == "true") {
$original_file = true;
} elseif ($original_file == "false") {
$original_file = false;
}
if ($disable_exit == "true") {
$disable_exit = true;
} elseif ($disable_exit == "false") {
$disable_exit = false;
}
if ($show_original == "true") {
$show_original = true;
} elseif ($show_original == "false") {
$show_original = false;
}
switch ($context) {
case "patient_picture":
$document_id = $this->patientService->getPatientPictureDocumentId($patient_id);
break;
}
$d = new Document($document_id);
// ensure user/patient has access
if (isset($_SESSION['patient_portal_onsite_two']) && isset($_SESSION['pid'])) {
// ensure patient has access (called from patient portal)
if (!$d->can_patient_access($_SESSION['pid'])) {
(new SystemLogger())->debug("An attempt was made by a patient to download a document from an unauthorized category", ['patient-id' => $_SESSION['pid'], 'document-id' => $document_id]);
die(xlt("Not authorized to view requested file"));
}
} else {
// ensure user has access
if (!$d->can_access()) {
(new SystemLogger())->debug("An attempt was made by a user to download a document from an unauthorized category", ['user-id' => $_SESSION['authUserID'], 'patient-id' => $patient_id, 'document-id' => $document_id]);
die(xlt("Not authorized to view requested file"));
}
}
$url = $d->get_url();
$th_url = $d->get_thumb_url();
$storagemethod = $d->get_storagemethod();
$couch_docid = $d->get_couch_docid();
$couch_revid = $d->get_couch_revid();
if ($couch_docid && $couch_revid && $original_file) {
// standard case for collecting a document from couchdb
$couch = new CouchDB();
$resp = $couch->retrieve_doc($couch_docid);
//Take thumbnail file when is not null and file is presented online
if (!$as_file && !is_null($th_url) && !$show_original) {
$content = $resp->th_data;
} else {
$content = $resp->data;
}
if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
$log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
$log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
$this->document_upload_download_log($d->get_foreign_id(), $log_content);
die(xlt("File retrieval from CouchDB failed"));
}
if ($d->get_encrypted() == 1) {
$filetext = $this->cryptoGen->decryptStandard($content, null, 'database');
} else {
$filetext = base64_decode($content);
}
if ($disable_exit == true) {
return $filetext;
}
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
if ($doEncryption) {
$ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
header("Content-Type: application/octet-stream");
header("Content-Length: " . strlen($ciphertext));
echo $ciphertext;
} else {
header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
header("Content-Type: " . $d->get_mimetype());
header("Content-Length: " . strlen($filetext));
echo $filetext;
}
exit;//exits only if file download from CouchDB is successfull.
}
if ($couch_docid && $couch_revid) {
//special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
//try to convert it if it has not yet been converted
//first, see if the converted jpg already exists
$couch = new CouchDB();
$resp = $couch->retrieve_doc("converted_" . $couch_docid);
$content = $resp->data;
if ($content == '') {
//create the converted jpg
$couchM = new CouchDB();
$respM = $couchM->retrieve_doc($couch_docid);
if ($d->get_encrypted() == 1) {
$contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');
} else {
$contentM = base64_decode($respM->data);
}
if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
$log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
$log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
$log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
$this->document_upload_download_log($d->get_foreign_id(), $log_content);
die(xlt("File retrieval from CouchDB failed"));
}
// place the from-file into a temporary file
$from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
file_put_contents($from_file_tmp_name, $contentM);
// prepare a temporary file for the to-file
$to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
$to_file_tmp_name = $to_file_tmp . ".jpg";
// convert file to jpg
exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
// remove from tmp file
unlink($from_file_tmp_name);
// save the to-file if a to-file was created in above convert call
if (is_file($to_file_tmp_name)) {
$couchI = new CouchDB();
if ($d->get_encrypted() == 1) {
$document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
} else {
$document = base64_encode(file_get_contents($to_file_tmp_name));
}
$couchI->save_doc(['_id' => "converted_" . $couch_docid, 'data' => $document]);
// remove to tmp files
unlink($to_file_tmp);
unlink($to_file_tmp_name);
} else {
error_log("ERROR: Document '" . errorLogEscape($d->get_name()) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
}
// now collect the newly created converted jpg
$couchF = new CouchDB();
$respF = $couchF->retrieve_doc("converted_" . $couch_docid);
if ($d->get_encrypted() == 1) {
$content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');
} else {
$content = base64_decode($respF->data);
}
} else {
// decrypt/decode when converted jpg already exists
if ($d->get_encrypted() == 1) {
$content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
} else {
$content = base64_decode($resp->data);
}
}
$filetext = $content;
if ($disable_exit == true) {
return $filetext;
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
header("Content-Type: image/jpeg");
header("Content-Length: " . strlen($filetext));
echo $filetext;
exit;
}
//Take thumbnail file when is not null and file is presented online
if (!$as_file && !is_null($th_url) && !$show_original) {
$url = $th_url;
}
//strip url of protocol handler
$url = preg_replace("|^(.*)://|", "", $url);
// change full path to current webroot. this is for documents that may have
// been moved from a different filesystem and the full path in the database
// is not current. this is also for documents that may of been moved to
// different patients. Note that the path_depth is used to see how far down
// the path to go. For example, originally the path_depth was always 1, which
// only allowed things like documents/1/<file>, but now can have more structured
// directories. For example a path_depth of 2 can give documents/encounters/1/<file>
// etc.
// NOTE that $from_filename and basename($url) are the same thing
$from_all = explode("/", $url);
$from_filename = array_pop($from_all);
// no point in doing any of these checks if $from_filename is empty which can lead to false positives on file_exists
if (!empty($from_filename)) {
$from_pathname_array = array();
for ($i = 0; $i < $d->get_path_depth(); $i++) {
$from_pathname_array[] = array_pop($from_all);
}
$from_pathname_array = array_reverse($from_pathname_array);
$from_pathname = implode("/", $from_pathname_array);
if ($couch_docid && $couch_revid) {
//for couchDB no URL is available in the table, hence using the foreign_id which is patientID
$temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
} else {
$temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
}
if (file_exists($temp_url)) {
$url = $temp_url;
}
$retrieveOffsiteDocument = new PatientRetrieveOffsiteDocument($d->get_url(), $d);
$updatedOffsiteDocumentEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch(
$retrieveOffsiteDocument,
PatientRetrieveOffsiteDocument::REMOTE_DOCUMENT_LOCATION
);
// if a module writer has an independent offsite storage mechanism used this accomdoates that.
// If the file is not found locally, it will be found remotely. Systems like s3, blob stores, etc, can
// be tied and and use those urls. Note NO security is handled here so any kind of security mechanism must
// be handled on the receiving end's URL (s3/azure for example use signed urls with signature verification)
if (
$updatedOffsiteDocumentEvent instanceof PatientRetrieveOffsiteDocument
&& $updatedOffsiteDocumentEvent->getOffsiteUrl() != null
) {
header('Content-Description: File Transfer');
header("Location: " . $updatedOffsiteDocumentEvent->getOffsiteUrl());
exit;
}
}
if (!file_exists($url)) {
echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $url;
} else {
if ($original_file) {
//normal case when serving the file referenced in database
if ($d->get_encrypted() == 1) {
$filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
} else {
if (!is_dir($url)) {
$filetext = file_get_contents($url);
}
}
if ($disable_exit == true) {
return $filetext ?? '';
}
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
if ($doEncryption) {
$ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
header("Content-Type: application/octet-stream");
header("Content-Length: " . strlen($ciphertext));
echo $ciphertext;
} else {
header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
header("Content-Type: " . $d->get_mimetype());
header("Content-Length: " . strlen($filetext ?? ''));
echo $filetext ?? '';
}
exit;
} else {
//special case when retrieving a document that has been converted to a jpg and not directly referenced in database
//try to convert it if it has not yet been converted
$originalUrl = $url;
if (strrpos(basename_international($url), '.') === false) {
$convertedFile = basename_international($url) . '_converted.jpg';
} else {
$convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
}
$url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
if (!is_file($url)) {
if ($d->get_encrypted() == 1) {
// decrypt the from-file into a temporary file
$from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
$from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
file_put_contents($from_file_tmp_name, $from_file_unencrypted);
// prepare a temporary file for the unencrypted to-file
$to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
$to_file_tmp_name = $to_file_tmp . ".jpg";
// convert file to jpg
exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
// remove unencrypted tmp file
unlink($from_file_tmp_name);
// make the encrypted to-file if a to-file was created in above convert call
if (is_file($to_file_tmp_name)) {
$to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
file_put_contents($url, $to_file_encrypted);
// remove unencrypted tmp files
unlink($to_file_tmp);
unlink($to_file_tmp_name);
}
} else {
// convert file to jpg
exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
}
}
if (is_file($url)) {
if ($d->get_encrypted() == 1) {
$filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
} else {
$filetext = file_get_contents($url);
}
} else {
$filetext = '';
error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
}
if ($disable_exit == true) {
return $filetext;
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
header("Content-Type: image/jpeg");
header("Content-Length: " . strlen($filetext));
echo $filetext;
exit;
}
}
}
public function move_action_process(string $patient_id = null, $document_id)
{
if ($_POST['process'] != "true") {
return;
}
$messages = '';
$new_category_id = $_POST['new_category_id'];
$new_patient_id = $_POST['new_patient_id'];
//move to new category
if (is_numeric($new_category_id) && is_numeric($document_id)) {
$sql = "UPDATE categories_to_documents set category_id = ? where document_id = ?";
$messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
//echo $sql;
$this->tree->_db->Execute($sql, [$new_category_id, $document_id]);
}
//move to new patient
if (is_numeric($new_patient_id) && is_numeric($document_id)) {
$d = new Document($document_id);
$sql = "SELECT pid from patient_data where pid = ?";
$result = $d->_db->Execute($sql, [$new_patient_id]);
if (!$result || $result->EOF) {
//patient id does not exist
$messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
} else {
$changefailed = !$d->change_patient($new_patient_id);
$this->_state = false;
if (!$changefailed) {
$messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
} else {
$messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
}
$this->assign("messages", $messages);
return $this->list_action($patient_id);
}
}
$this->_state = false;
$this->assign("messages", $messages);
return $this->view_action($patient_id, $document_id);
}
public function validate_action_process(string $patient_id = null, $document_id)
{
$d = new Document($document_id);
if ($d->couch_docid && $d->couch_revid) {
$file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
$url = $file_path . $d->get_url();
$couch = new CouchDB();
$resp = $couch->retrieve_doc($d->couch_docid);
if ($d->get_encrypted() == 1) {
$content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
} else {
$content = base64_decode($resp->data);
}
} else {
$url = $d->get_url();
//strip url of protocol handler
$url = preg_replace("|^(.*)://|", "", $url);
//change full path to current webroot. this is for documents that may have
//been moved from a different filesystem and the full path in the database
//is not current. this is also for documents that may of been moved to
//different patients. Note that the path_depth is used to see how far down
//the path to go. For example, originally the path_depth was always 1, which
//only allowed things like documents/1/<file>, but now can have more structured
//directories. For example a path_depth of 2 can give documents/encounters/1/<file>
// etc.
// NOTE that $from_filename and basename($url) are the same thing
$from_all = explode("/", $url);
$from_filename = array_pop($from_all);
$from_pathname_array = array();
for ($i = 0; $i < $d->get_path_depth(); $i++) {
$from_pathname_array[] = array_pop($from_all);
}
$from_pathname_array = array_reverse($from_pathname_array);
$from_pathname = implode("/", $from_pathname_array);
$temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
if (file_exists($temp_url)) {