Fee sheet and Codes revenue code (#7415)
[openemr.git] / controllers / C_Document.class.php
blob4f674e4ba0b2a8cad3f3ac9c9efaccf04a56ec9f
1 <?php
3 /**
4 * C_Document.class.php
6 * @package OpenEMR
7 * @link https://www.open-emr.org
8 * @author Brady Miller <brady.g.miller@gmail.com>
9 * @author Jerry Padgett <sjpadgett@gmail.com>
10 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
11 * @copyright Copyright (c) 2019-2024 Jerry Padgett <sjpadgett@gmail.com>
12 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
15 require_once(__DIR__ . "/../library/forms.inc.php");
16 require_once(__DIR__ . "/../library/patient.inc.php");
18 use OpenEMR\Common\Acl\AclMain;
19 use OpenEMR\Common\Crypto\CryptoGen;
20 use OpenEMR\Common\Csrf\CsrfUtils;
21 use OpenEMR\Common\Logging\SystemLogger;
22 use OpenEMR\Common\Twig\TwigContainer;
23 use OpenEMR\Services\DocumentTemplates\DocumentTemplateService;
24 use OpenEMR\Services\FacilityService;
25 use OpenEMR\Services\PatientService;
26 use OpenEMR\Events\PatientDocuments\PatientDocumentTreeViewFilterEvent;
27 use OpenEMR\Events\PatientDocuments\PatientRetrieveOffsiteDocument;
29 class C_Document extends Controller
31 public $documents;
32 public $document_categories;
33 public $tree;
34 public $_config;
35 public $manual_set_owner = false; // allows manual setting of a document owner/service
36 public $facilityService;
37 public $patientService;
38 public $_last_node;
39 private $Document;
40 private $cryptoGen;
41 private bool $skip_acl_check = false;
42 private DocumentTemplateService $templateService;
44 public function __construct($template_mod = "general")
46 parent::__construct();
47 $this->facilityService = new FacilityService();
48 $this->patientService = new PatientService();
49 $this->documents = array();
50 $this->template_mod = $template_mod;
51 $this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING'] ?? ''));
52 $this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
54 if (php_sapi_name() !== 'cli') {
55 // skip when this is being called via command line for the ccda importing
56 $this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
59 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
61 //get global config options for this namespace
62 $this->_config = $GLOBALS['oer_config']['documents'];
64 $this->_args = array("patient_id" => ($_GET['patient_id'] ?? null));
66 $this->assign("STYLE", $GLOBALS['style']);
67 $t = new CategoryTree(1);
68 //print_r($t->tree);
69 $this->tree = $t;
70 $this->Document = new Document();
72 // Create a crypto object that will be used for for encryption/decryption
73 $this->cryptoGen = new CryptoGen();
74 $this->templateService = new DocumentTemplateService();
77 public function upload_action($patient_id, $category_id)
79 $category_name = $this->tree->get_node_name($category_id);
80 $this->assign("category_id", $category_id);
81 $this->assign("category_name", $category_name);
82 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
83 $this->assign("patient_id", $patient_id);
85 // Added by Rod to support document template download from general_upload.html.
86 // Cloned from similar stuff in manage_document_templates.php.
87 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
88 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
89 if (file_exists($templatedir)) {
90 $dh = opendir($templatedir);
92 if (!empty($dh)) {
93 $templateslist = array();
94 while (false !== ($sfname = readdir($dh))) {
95 if (substr($sfname, 0, 1) == '.') {
96 continue;
98 $templateslist[$sfname] = $sfname;
100 closedir($dh);
101 ksort($templateslist);
102 foreach ($templateslist as $sfname) {
103 $templates_options .= "<option value='" . attr($sfname) .
104 "'>" . text($sfname) . "</option>";
107 $this->assign("TEMPLATES_LIST", $templates_options);
109 // will call as module or individual template.
110 $templates_list = $this->templateService->renderPortalTemplateMenu($patient_id, '-patient-', false) ?? [];
111 $this->assign("TEMPLATES_LIST_PATIENT", $templates_list);
113 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
114 $this->assign("activity", $activity);
115 return $this->list_action($patient_id);
118 public function zip_dicom_folder($study_name = null)
120 $zip = new ZipArchive();
121 $zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
122 if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {
123 foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
124 $zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
125 $fparts = pathinfo($name);
126 if (empty($fparts['extension'])) {
127 // viewer requires lowercase.
128 $fparts['extension'] = "dcm";
129 $name = $fparts['filename'] . ".dcm";
131 if ($fparts['extension'] == "DCM") {
132 // viewer requires lowercase.
133 $fparts['extension'] = "dcm";
134 $name = $fparts['filename'] . ".dcm";
136 // required extension for viewer
137 if ($fparts['extension'] != "dcm") {
138 continue;
140 move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
141 $zip->addFile($zfn, $name);
143 $zip->close();
144 } else {
145 return false;
147 $file_array['name'][] = $study_name;
148 $file_array['type'][] = 'zip';
149 $file_array['tmp_name'][] = $zip_name;
150 $file_array['error'][] = '';
151 $file_array['size'][] = filesize($zip_name);
152 return $file_array;
155 //Upload multiple files on single click
156 public function upload_action_process()
159 // Collect a manually set owner if this has been set
160 // Used when want to manually assign the owning user/service such as the Direct mechanism
161 $non_HTTP_owner = false;
162 if ($this->manual_set_owner) {
163 $non_HTTP_owner = $this->manual_set_owner;
166 $couchDB = false;
167 $harddisk = false;
168 if ($GLOBALS['document_storage_method'] == 0) {
169 $harddisk = true;
171 if ($GLOBALS['document_storage_method'] == 1) {
172 $couchDB = true;
175 if ($_POST['process'] != "true") {
176 return;
179 $doDecryption = false;
180 $encrypted = $_POST['encrypted'] ?? false;
181 $passphrase = $_POST['passphrase'] ?? '';
182 if (
183 !$GLOBALS['hide_document_encryption'] &&
184 $encrypted && $passphrase
186 $doDecryption = true;
189 if (is_numeric($_POST['category_id'])) {
190 $category_id = $_POST['category_id'];
191 } else {
192 $category_id = 1;
195 $patient_id = 0;
196 if (isset($_GET['patient_id']) && !$couchDB) {
197 $patient_id = $_GET['patient_id'];
198 } elseif (is_numeric($_POST['patient_id'])) {
199 $patient_id = $_POST['patient_id'];
202 // ensure user has access to the category that is being uploaded to
203 $skipUpload = false;
204 if (!$this->isSkipAclCheck()) {
205 $acoSpec = sqlQuery("SELECT `aco_spec` from `categories` WHERE `id` = ?", [$category_id])['aco_spec'];
206 if (AclMain::aclCheckAcoSpec($acoSpec) === false) {
207 $error = xl("Not authorized to upload to the selected category.\n");
208 $skipUpload = true;
209 (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]);
213 if (!$skipUpload && !empty($_FILES['dicom_folder']['name'][0])) {
214 // let's zip um up then pass along new zip
215 $study_name = $_POST['destination'] ? (trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
216 $study_name = preg_replace('/\s+/', '_', $study_name);
217 $_POST['destination'] = "";
218 $zipped = $this->zip_dicom_folder($study_name);
219 if ($zipped) {
220 $_FILES['file'] = $zipped;
222 // and off we go! just fall through and let routine
223 // do its normal file processing..
226 $sentUploadStatus = array();
227 if (!$skipUpload && count($_FILES['file']['name']) > 0) {
228 $upl_inc = 0;
230 foreach ($_FILES['file']['name'] as $key => $value) {
231 $fname = $value;
232 $error = "";
233 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
234 $fname = $value;
235 if (empty($fname)) {
236 $fname = htmlentities("<empty>");
238 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
239 if ($_FILES['file']['size'][$key] == 0) {
240 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
242 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
243 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
244 } else {
245 // Test for a zip of DICOM images
246 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
247 $za = new ZipArchive();
248 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
249 if ($handler) {
250 $mimetype = "application/dicom+zip";
251 for ($i = 0; $i < $za->numFiles; $i++) {
252 $stat = $za->statIndex($i);
253 $fp = $za->getStream($stat['name']);
254 if ($fp) {
255 $head = fread($fp, 256);
256 fclose($fp);
257 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
258 $mimetype = "application/zip";
259 break;
261 unset($head);
262 // if here -then a DICOM
263 $parts = pathinfo($stat['name']);
264 if ($parts['extension'] != "dcm" || empty($parts['extension'])) { // required extension for viewer
265 $new_name = $parts['filename'] . ".dcm";
266 $za->renameIndex($i, $new_name);
267 $za->renameName($parts['filename'], $new_name);
269 } else { // Rarely here
270 $mimetype = "application/zip";
271 break;
274 $za->close();
275 if ($mimetype == "application/dicom+zip") {
276 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
277 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
281 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
282 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
283 fclose($tmpfile);
284 if ($doDecryption) {
285 $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
286 if ($filetext === false) {
287 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
288 $filetext = "";
291 if ($_POST['destination'] != '') {
292 $fname = $_POST['destination'];
294 // test for single DICOM and assign extension if missing.
295 if (strpos($filetext, 'DICM') !== false) {
296 $mimetype = 'application/dicom';
297 $parts = pathinfo($fname);
298 if (!$parts['extension']) {
299 $fname .= '.dcm';
302 // set mimetype (if not already set above)
303 if (empty($mimetype)) {
304 $mimetype = mime_content_type($_FILES['file']['tmp_name'][$key]);
306 // if mimetype still empty, then do not upload the file
307 if (empty($mimetype)) {
308 $error = xl("Unable to discover mimetype, so did not upload " . $_FILES['file']['tmp_name'][$key]) . ".\n";
309 continue;
311 $d = new Document();
312 $rc = $d->createDocument(
313 $patient_id,
314 $category_id,
315 $fname,
316 $mimetype,
317 $filetext,
318 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
319 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
320 $non_HTTP_owner,
321 $_FILES['file']['tmp_name'][$key]
323 if ($rc) {
324 $error .= $rc . "\n";
325 } else {
326 $this->assign("upload_success", "true");
328 $sentUploadStatus[] = $d;
329 $this->assign("file", $sentUploadStatus);
332 // Option to run a custom plugin for each file upload.
333 // This was initially created to delete the original source file in a custom setting.
334 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
335 if (file_exists($upload_plugin)) {
336 include_once($upload_plugin);
338 $upload_plugin_pp = 'documentUploadPostProcess';
339 if (function_exists($upload_plugin_pp)) {
340 $tmp = call_user_func($upload_plugin_pp, $value, $d);
341 if ($tmp) {
342 $error = $tmp;
345 // Following is just an example of code in such a plugin file.
346 /*****************************************************
347 public function documentUploadPostProcess($filename, &$d) {
348 $userid = $_SESSION['authUserID'];
349 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
350 $owner = strtolower($row['username']);
351 $dn = '1_' . ucfirst($owner);
352 $filepath = "/shared_network_directory/$dn/$filename";
353 if (@unlink($filepath)) return '';
354 return "Failed to delete '$filepath'.";
356 *****************************************************/
360 $this->assign("error", $error);
361 //$this->_state = false;
362 $_POST['process'] = "";
363 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
366 public function note_action_process($patient_id)
368 // this public function is a dual public function that will set up a note associated with a document or send a document via email.
370 if ($_POST['process'] != "true") {
371 return;
374 $n = new Note();
375 $n->set_owner($_SESSION['authUserID']);
376 parent::populate_object($n);
377 if ($_POST['identifier'] == "no") {
378 // associate a note with a document
379 $n->persist();
380 } elseif ($_POST['identifier'] == "yes") {
381 // send the document via email
382 $d = new Document($_POST['foreign_id']);
383 $url = $d->get_url();
384 $storagemethod = $d->get_storagemethod();
385 $couch_docid = $d->get_couch_docid();
386 $couch_revid = $d->get_couch_revid();
387 if ($couch_docid && $couch_revid) {
388 $couch = new CouchDB();
389 $resp = $couch->retrieve_doc($couch_docid);
390 $content = $resp->data;
391 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
392 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
393 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
394 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
395 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
396 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
397 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
398 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
399 die(xlt("File retrieval from CouchDB failed"));
401 // place it in a temporary file and will remove the file below after emailed
402 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
403 $fh = fopen($temp_couchdb_url, "w");
404 fwrite($fh, base64_decode($content));
405 fclose($fh);
406 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
407 } else {
408 $url = preg_replace("|^(.*)://|", "", $url);
409 // Collect filename and path
410 $from_all = explode("/", $url);
411 $from_filename = array_pop($from_all);
412 $from_pathname_array = array();
413 for ($i = 0; $i < $d->get_path_depth(); $i++) {
414 $from_pathname_array[] = array_pop($from_all);
416 $from_pathname_array = array_reverse($from_pathname_array);
417 $from_pathname = implode("/", $from_pathname_array);
418 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
420 if (!file_exists($temp_url)) {
421 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;
423 $url = $temp_url;
424 $pdetails = getPatientData($patient_id);
425 $pname = $pdetails['fname'] . " " . $pdetails['lname'];
426 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
427 if ($couch_docid && $couch_revid) {
428 // remove the temporary couchdb file
429 unlink($temp_couchdb_url);
432 $this->_state = false;
433 $_POST['process'] = "";
434 return $this->view_action($patient_id, $n->get_foreign_id());
437 public function default_action()
439 return $this->list_action();
442 public function view_action(string $patient_id = null, $doc_id)
444 global $ISSUE_TYPES;
446 require_once(dirname(__FILE__) . "/../library/lists.inc.php");
448 $d = new Document($doc_id);
449 $notes = $d->get_notes();
451 $this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
453 $this->assign("file", $d);
454 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
455 $this->assign("NOTE_ACTION", $this->_link("note"));
456 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
457 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
458 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
459 $this->assign("webroot", $GLOBALS['webroot']);
461 // Added by Rod to support document delete:
462 $delete_string = '';
463 if (AclMain::aclCheckCore('patients', 'docs_rm')) {
464 $delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
465 ")'>" . xlt('Delete') . "</a>";
467 $this->assign("delete_string", $delete_string);
468 $this->assign("REFRESH_ACTION", $this->_link("list"));
470 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
471 "document_id=" . $d->get_id() . "&process=true");
473 // Added by Rod to support document date update:
474 $this->assign("DOCDATE", $d->get_docdate());
475 $this->assign("UPDATE_ACTION", $this->_link("update") .
476 "document_id=" . $d->get_id() . "&process=true");
478 // Added by Rod to support document issue update:
479 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
480 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
481 "pid = ? " . // AND enddate IS NULL " .
482 "ORDER BY type, begdate", array($patient_id));
483 while ($irow = sqlFetchArray($ires)) {
484 $desc = $irow['type'];
485 if ($ISSUE_TYPES[$desc]) {
486 $desc = $ISSUE_TYPES[$desc][2];
488 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
489 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
490 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
492 $this->assign("ISSUES_LIST", $issues_options);
494 // For tagging to encounter
495 // Populate the dropdown with patient's encounter list
496 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
497 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
498 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
499 "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));
500 if (sqlNumRows($result_docs) > 0) {
501 while ($row_result_docs = sqlFetchArray($result_docs)) {
502 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
503 $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>";
506 $this->assign("ENC_LIST", $encOptions);
508 //clear encounter tag
509 if ($d->get_encounter_id() != 0) {
510 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
511 } else {
512 $this->assign('clear_encounter_tag', 'javascript:void(0)');
515 //Populate the dropdown with category list
516 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
517 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
518 while ($crow = sqlFetchArray($cres)) {
519 $catid = $crow['pc_catid'];
520 if ($catid < 9 && $catid != 5) {
521 continue; // Applying same logic as in new encounter page.
523 $visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
525 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
527 $this->assign("notes", $notes);
529 $this->assign("PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
530 // Populate the dropdown with procedure order list
531 $imgOptions = "<option value='0'>-- " . xlt('Select Procedure') . " --</option>";
532 $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));
533 $mapping = $this->get_mapped_procedure($d->get_id());
534 if (sqlNumRows($imgOrders) > 0) {
535 while ($row = sqlFetchArray($imgOrders)) {
536 $sel_proc = '';
537 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
538 $sel_proc = 'selected';
540 $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>";
544 $this->assign('TAG_PROCEDURE_LIST', $imgOptions);
546 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
548 $this->_last_node = null;
550 $menu = new HTML_TreeMenu();
552 //pass an empty array because we don't want the documents for each category showing up in this list box
553 $rnode = $this->array_recurse($this->tree->tree, $patient_id, array());
554 $menu->addItem($rnode);
555 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
557 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
559 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
560 $this->assign("activity", $activity);
562 return $this->list_action($patient_id);
566 * Retrieve file from hard disk / CouchDB.
567 * In case that file isn't download this public function will return thumbnail image (if exist).
568 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
569 * @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.
570 * */
571 public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
573 $encrypted = $_POST['encrypted'] ?? false;
574 $passphrase = $_POST['passphrase'] ?? '';
575 $doEncryption = false;
576 if (
577 !$GLOBALS['hide_document_encryption'] &&
578 $encrypted == "true" &&
579 $passphrase
581 $doEncryption = true;
584 //controller public function ruins booleans, so need to manually re-convert to booleans
585 if ($as_file == "true") {
586 $as_file = true;
587 } elseif ($as_file == "false") {
588 $as_file = false;
590 if ($original_file == "true") {
591 $original_file = true;
592 } elseif ($original_file == "false") {
593 $original_file = false;
595 if ($disable_exit == "true") {
596 $disable_exit = true;
597 } elseif ($disable_exit == "false") {
598 $disable_exit = false;
600 if ($show_original == "true") {
601 $show_original = true;
602 } elseif ($show_original == "false") {
603 $show_original = false;
606 switch ($context) {
607 case "patient_picture":
608 $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);
609 break;
612 $d = new Document($document_id);
614 // ensure user/patient has access
615 if (isset($_SESSION['patient_portal_onsite_two']) && isset($_SESSION['pid'])) {
616 // ensure patient has access (called from patient portal)
617 if (!$d->can_patient_access($_SESSION['pid'])) {
618 (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]);
619 die(xlt("Not authorized to view requested file"));
621 } else {
622 // ensure user has access
623 if (!$d->can_access()) {
624 (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]);
625 die(xlt("Not authorized to view requested file"));
629 $url = $d->get_url();
630 $th_url = $d->get_thumb_url();
632 $storagemethod = $d->get_storagemethod();
633 $couch_docid = $d->get_couch_docid();
634 $couch_revid = $d->get_couch_revid();
636 if ($couch_docid && $couch_revid && $original_file) {
637 // standard case for collecting a document from couchdb
638 $couch = new CouchDB();
639 $resp = $couch->retrieve_doc($couch_docid);
640 //Take thumbnail file when is not null and file is presented online
641 if (!$as_file && !is_null($th_url) && !$show_original) {
642 $content = $resp->th_data;
643 } else {
644 $content = $resp->data;
646 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
647 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
648 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
649 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
650 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
651 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
652 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
653 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
654 die(xlt("File retrieval from CouchDB failed"));
656 if ($d->get_encrypted() == 1) {
657 $filetext = $this->cryptoGen->decryptStandard($content, null, 'database');
658 } else {
659 $filetext = base64_decode($content);
661 if ($disable_exit == true) {
662 return $filetext;
664 header('Content-Description: File Transfer');
665 header('Content-Transfer-Encoding: binary');
666 header('Expires: 0');
667 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
668 header('Pragma: public');
669 if ($doEncryption) {
670 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
671 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
672 header("Content-Type: application/octet-stream");
673 header("Content-Length: " . strlen($ciphertext));
674 echo $ciphertext;
675 } else {
676 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
677 header("Content-Type: " . $d->get_mimetype());
678 header("Content-Length: " . strlen($filetext));
679 echo $filetext;
681 exit;//exits only if file download from CouchDB is successfull.
683 if ($couch_docid && $couch_revid) {
684 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
685 //try to convert it if it has not yet been converted
686 //first, see if the converted jpg already exists
687 $couch = new CouchDB();
688 $resp = $couch->retrieve_doc("converted_" . $couch_docid);
689 $content = $resp->data;
690 if ($content == '') {
691 //create the converted jpg
692 $couchM = new CouchDB();
693 $respM = $couchM->retrieve_doc($couch_docid);
694 if ($d->get_encrypted() == 1) {
695 $contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');
696 } else {
697 $contentM = base64_decode($respM->data);
699 if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
700 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
701 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
702 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
703 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
704 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
705 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
706 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
707 die(xlt("File retrieval from CouchDB failed"));
709 // place the from-file into a temporary file
710 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
711 file_put_contents($from_file_tmp_name, $contentM);
712 // prepare a temporary file for the to-file
713 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
714 $to_file_tmp_name = $to_file_tmp . ".jpg";
715 // convert file to jpg
716 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
717 // remove from tmp file
718 unlink($from_file_tmp_name);
719 // save the to-file if a to-file was created in above convert call
720 if (is_file($to_file_tmp_name)) {
721 $couchI = new CouchDB();
722 if ($d->get_encrypted() == 1) {
723 $document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
724 } else {
725 $document = base64_encode(file_get_contents($to_file_tmp_name));
727 $couchI->save_doc(['_id' => "converted_" . $couch_docid, 'data' => $document]);
728 // remove to tmp files
729 unlink($to_file_tmp);
730 unlink($to_file_tmp_name);
731 } else {
732 error_log("ERROR: Document '" . errorLogEscape($d->get_name()) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
734 // now collect the newly created converted jpg
735 $couchF = new CouchDB();
736 $respF = $couchF->retrieve_doc("converted_" . $couch_docid);
737 if ($d->get_encrypted() == 1) {
738 $content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');
739 } else {
740 $content = base64_decode($respF->data);
742 } else {
743 // decrypt/decode when converted jpg already exists
744 if ($d->get_encrypted() == 1) {
745 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
746 } else {
747 $content = base64_decode($resp->data);
750 $filetext = $content;
751 if ($disable_exit == true) {
752 return $filetext;
754 header("Pragma: public");
755 header("Expires: 0");
756 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
757 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
758 header("Content-Type: image/jpeg");
759 header("Content-Length: " . strlen($filetext));
760 echo $filetext;
761 exit;
764 //Take thumbnail file when is not null and file is presented online
765 if (!$as_file && !is_null($th_url) && !$show_original) {
766 $url = $th_url;
769 //strip url of protocol handler
770 $url = preg_replace("|^(.*)://|", "", $url);
772 // change full path to current webroot. this is for documents that may have
773 // been moved from a different filesystem and the full path in the database
774 // is not current. this is also for documents that may of been moved to
775 // different patients. Note that the path_depth is used to see how far down
776 // the path to go. For example, originally the path_depth was always 1, which
777 // only allowed things like documents/1/<file>, but now can have more structured
778 // directories. For example a path_depth of 2 can give documents/encounters/1/<file>
779 // etc.
780 // NOTE that $from_filename and basename($url) are the same thing
781 $from_all = explode("/", $url);
782 $from_filename = array_pop($from_all);
783 // no point in doing any of these checks if $from_filename is empty which can lead to false positives on file_exists
784 if (!empty($from_filename)) {
785 $from_pathname_array = array();
786 for ($i = 0; $i < $d->get_path_depth(); $i++) {
787 $from_pathname_array[] = array_pop($from_all);
789 $from_pathname_array = array_reverse($from_pathname_array);
790 $from_pathname = implode("/", $from_pathname_array);
791 if ($couch_docid && $couch_revid) {
792 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
793 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
794 } else {
795 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
798 if (file_exists($temp_url)) {
799 $url = $temp_url;
802 $retrieveOffsiteDocument = new PatientRetrieveOffsiteDocument($d->get_url(), $d);
803 $updatedOffsiteDocumentEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch(
804 $retrieveOffsiteDocument,
805 PatientRetrieveOffsiteDocument::REMOTE_DOCUMENT_LOCATION
807 // if a module writer has an independent offsite storage mechanism used this accomdoates that.
808 // If the file is not found locally, it will be found remotely. Systems like s3, blob stores, etc, can
809 // be tied and and use those urls. Note NO security is handled here so any kind of security mechanism must
810 // be handled on the receiving end's URL (s3/azure for example use signed urls with signature verification)
811 if (
812 $updatedOffsiteDocumentEvent instanceof PatientRetrieveOffsiteDocument
813 && $updatedOffsiteDocumentEvent->getOffsiteUrl() != null
815 header('Content-Description: File Transfer');
816 header("Location: " . $updatedOffsiteDocumentEvent->getOffsiteUrl());
817 exit;
821 if (!file_exists($url)) {
822 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;
823 } else {
824 if ($original_file) {
825 //normal case when serving the file referenced in database
826 if ($d->get_encrypted() == 1) {
827 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
828 } else {
829 if (!is_dir($url)) {
830 $filetext = file_get_contents($url);
833 if ($disable_exit == true) {
834 return $filetext ?? '';
836 header('Content-Description: File Transfer');
837 header('Content-Transfer-Encoding: binary');
838 header('Expires: 0');
839 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
840 header('Pragma: public');
841 if ($doEncryption) {
842 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
843 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
844 header("Content-Type: application/octet-stream");
845 header("Content-Length: " . strlen($ciphertext));
846 echo $ciphertext;
847 } else {
848 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
849 header("Content-Type: " . $d->get_mimetype());
850 header("Content-Length: " . strlen($filetext ?? ''));
851 echo $filetext ?? '';
853 exit;
854 } else {
855 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
856 //try to convert it if it has not yet been converted
857 $originalUrl = $url;
858 if (strrpos(basename_international($url), '.') === false) {
859 $convertedFile = basename_international($url) . '_converted.jpg';
860 } else {
861 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
863 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
864 if (!is_file($url)) {
865 if ($d->get_encrypted() == 1) {
866 // decrypt the from-file into a temporary file
867 $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
868 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
869 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
870 // prepare a temporary file for the unencrypted to-file
871 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
872 $to_file_tmp_name = $to_file_tmp . ".jpg";
873 // convert file to jpg
874 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
875 // remove unencrypted tmp file
876 unlink($from_file_tmp_name);
877 // make the encrypted to-file if a to-file was created in above convert call
878 if (is_file($to_file_tmp_name)) {
879 $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
880 file_put_contents($url, $to_file_encrypted);
881 // remove unencrypted tmp files
882 unlink($to_file_tmp);
883 unlink($to_file_tmp_name);
885 } else {
886 // convert file to jpg
887 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
890 if (is_file($url)) {
891 if ($d->get_encrypted() == 1) {
892 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
893 } else {
894 $filetext = file_get_contents($url);
896 } else {
897 $filetext = '';
898 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
900 if ($disable_exit == true) {
901 return $filetext;
903 header("Pragma: public");
904 header("Expires: 0");
905 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
906 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
907 header("Content-Type: image/jpeg");
908 header("Content-Length: " . strlen($filetext));
909 echo $filetext;
910 exit;
915 public function move_action_process(string $patient_id = null, $document_id)
917 if ($_POST['process'] != "true") {
918 return;
921 $messages = '';
923 $new_category_id = $_POST['new_category_id'];
924 $new_patient_id = $_POST['new_patient_id'];
926 //move to new category
927 if (is_numeric($new_category_id) && is_numeric($document_id)) {
928 $sql = "UPDATE categories_to_documents set category_id = ? where document_id = ?";
929 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
930 //echo $sql;
931 $this->tree->_db->Execute($sql, [$new_category_id, $document_id]);
934 //move to new patient
935 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
936 $d = new Document($document_id);
937 $sql = "SELECT pid from patient_data where pid = ?";
938 $result = $d->_db->Execute($sql, [$new_patient_id]);
940 if (!$result || $result->EOF) {
941 //patient id does not exist
942 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
943 } else {
944 $changefailed = !$d->change_patient($new_patient_id);
946 $this->_state = false;
947 if (!$changefailed) {
948 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
949 } else {
950 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
952 $this->assign("messages", $messages);
953 return $this->list_action($patient_id);
957 $this->_state = false;
958 $this->assign("messages", $messages);
959 return $this->view_action($patient_id, $document_id);
962 public function validate_action_process(string $patient_id = null, $document_id)
965 $d = new Document($document_id);
966 if ($d->couch_docid && $d->couch_revid) {
967 $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
968 $url = $file_path . $d->get_url();
969 $couch = new CouchDB();
970 $resp = $couch->retrieve_doc($d->couch_docid);
971 if ($d->get_encrypted() == 1) {
972 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
973 } else {
974 $content = base64_decode($resp->data);
976 } else {
977 $url = $d->get_url();
979 //strip url of protocol handler
980 $url = preg_replace("|^(.*)://|", "", $url);
982 //change full path to current webroot. this is for documents that may have
983 //been moved from a different filesystem and the full path in the database
984 //is not current. this is also for documents that may of been moved to
985 //different patients. Note that the path_depth is used to see how far down
986 //the path to go. For example, originally the path_depth was always 1, which
987 //only allowed things like documents/1/<file>, but now can have more structured
988 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
989 // etc.
990 // NOTE that $from_filename and basename($url) are the same thing
991 $from_all = explode("/", $url);
992 $from_filename = array_pop($from_all);
993 $from_pathname_array = array();
994 for ($i = 0; $i < $d->get_path_depth(); $i++) {
995 $from_pathname_array[] = array_pop($from_all);
997 $from_pathname_array = array_reverse($from_pathname_array);
998 $from_pathname = implode("/", $from_pathname_array);
999 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
1000 if (file_exists($temp_url)) {
1001 $url = $temp_url;
1004 if ($_POST['process'] != "true") {
1005 die("process is '" . text($_POST['process']) . "', expected 'true'");
1006 return;
1009 if ($d->get_encrypted() == 1) {
1010 $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
1011 } else {
1012 $content = file_get_contents($url);
1016 if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {
1017 // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0
1018 $current_hash = sha1($content);
1019 } else {
1020 $current_hash = hash('sha3-512', $content);
1022 $messages = xl('Current Hash') . ": " . $current_hash . " | ";
1023 $messages .= xl('Stored Hash') . ": " . $d->get_hash();
1024 if ($d->get_hash() == '') {
1025 $d->hash = $current_hash;
1026 $d->persist();
1027 $d->populate();
1028 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
1029 } elseif ($current_hash != $d->get_hash()) {
1030 $messages .= xl('Hash does not match. Data integrity has been compromised.');
1031 } else {
1032 $messages = xl('Document passed integrity check.') . ' | ' . $messages;
1034 $this->_state = false;
1035 $this->assign("messages", $messages);
1036 return $this->view_action($patient_id, $document_id);
1039 // Added by Rod for metadata update.
1041 public function update_action_process(string $patient_id = null, $document_id)
1044 if ($_POST['process'] != "true") {
1045 die("process is '" . $_POST['process'] . "', expected 'true'");
1046 return;
1049 $docdate = $_POST['docdate'];
1050 $docname = $_POST['docname'];
1051 $issue_id = $_POST['issue_id'];
1053 if (is_numeric($document_id)) {
1054 $messages = '';
1055 $d = new Document($document_id);
1056 $file_name = $d->get_name();
1057 if (
1058 $docname != '' &&
1059 $docname != $file_name
1061 // Rename
1062 $d->set_name($docname);
1063 $d->persist();
1064 $d->populate();
1065 $messages .= xl('Document successfully renamed.') . "<br />";
1068 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1069 $docdate = "$docdate";
1070 } else {
1071 $docdate = "NULL";
1073 if (!is_numeric($issue_id)) {
1074 $issue_id = 0;
1076 $couch_docid = $d->get_couch_docid();
1077 $couch_revid = $d->get_couch_revid();
1078 if ($couch_docid && $couch_revid) {
1079 $sql = "UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?";
1080 $this->tree->_db->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);
1081 } else {
1082 $sql = "UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?";
1083 $this->tree->_db->Execute($sql, [$docdate, $issue_id, $document_id]);
1085 $messages .= xl('Document date and issue updated successfully') . "<br />";
1088 $this->_state = false;
1089 $this->assign("messages", $messages);
1090 return $this->view_action($patient_id, $document_id);
1093 public function list_action($patient_id = "")
1095 $this->_last_node = null;
1096 $categories_list = $this->tree->_get_categories_array($patient_id);
1097 //print_r($categories_list);
1099 $menu = new HTML_TreeMenu();
1100 $rnode = $this->array_recurse($this->tree->tree, $patient_id, $categories_list);
1101 $menu->addItem($rnode);
1102 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1103 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1104 $this->assign("tree_html", $treeMenu->toHTML());
1106 $is_new = isset($_GET['patient_name']) ? 1 : false;
1107 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1108 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1109 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1110 if ($cur_pid == '00') {
1111 if (!AclMain::aclCheckCore('patients', 'docs', '', ['write', 'addonly'])) {
1112 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1113 exit;
1115 $cur_pid = '0';
1116 $is_new = 1;
1118 if (!AclMain::aclCheckCore('patients', 'docs')) {
1119 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1120 exit;
1122 $this->assign('is_new', $is_new);
1123 $this->assign('place_hld', $place_hld);
1124 $this->assign('cur_pid', $cur_pid);
1125 $this->assign('used_msg', $used_msg);
1126 $this->assign('demo_pid', ($_SESSION['pid'] ?? null));
1128 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1131 public function &array_recurse($array, $patient_id, $categories = array())
1133 if (!is_array($array)) {
1134 $array = array();
1136 $node = &$this->_last_node;
1137 $current_node = &$node;
1138 $expandedIcon = 'folder-expanded.gif';
1139 foreach ($array as $id => $ar) {
1140 $icon = 'folder.gif';
1141 if (is_array($ar) || !empty($id)) {
1142 if ($node == null) {
1143 //echo "r:" . $this->tree->get_node_name($id) . "<br />";
1144 $rnode = new HTML_TreeNode(array("id" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => false));
1145 $this->_last_node = &$rnode;
1146 $node = &$rnode;
1147 $current_node = &$rnode;
1148 } else {
1149 //echo "p:" . $this->tree->get_node_name($id) . "<br />";
1150 $this->_last_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1151 $current_node = &$this->_last_node;
1154 $this->array_recurse($ar, $patient_id, $categories);
1155 } else {
1156 if ($id === 0 && !empty($ar)) {
1157 $info = $this->tree->get_node_info($id);
1158 //echo "b:" . $this->tree->get_node_name($id) . "<br />";
1159 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1160 } else {
1161 //there is a third case that is implicit here when title === 0 and $ar is empty, in that case we do not want to do anything
1162 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1163 if ($id !== 0 && is_object($node)) {
1164 //echo "n:" . $this->tree->get_node_name($id) . "<br />";
1165 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1170 // If there are documents in this document category, then add their
1171 // attributes to the current node.
1172 $icon = "file3.png";
1173 if (!empty($categories[$id]) && is_array($categories[$id])) {
1174 foreach ($categories[$id] as $doc) {
1175 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1176 // If user has no access then there will be no link.
1177 if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {
1178 $link = '';
1180 // CCD view
1181 $nodeInfo = $this->tree->get_node_info($id);
1182 $treeViewFilterEvent = new PatientDocumentTreeViewFilterEvent();
1183 $treeViewFilterEvent->setCategoryTreeNode($this->tree);
1184 $treeViewFilterEvent->setDocumentId($doc['document_id']);
1185 $treeViewFilterEvent->setDocumentName($doc['document_name']);
1186 $treeViewFilterEvent->setCategoryId($id);
1187 $treeViewFilterEvent->setCategoryInfo($nodeInfo);
1188 $treeViewFilterEvent->setPid($patient_id);
1190 $htmlNode = new HTML_TreeNode(array(
1191 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1192 'link' => $link,
1193 'icon' => $icon,
1194 'expandedIcon' => $expandedIcon
1197 $treeViewFilterEvent->setHtmlTreeNode($htmlNode);
1198 $filteredEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch($treeViewFilterEvent, PatientDocumentTreeViewFilterEvent::EVENT_NAME);
1199 if ($filteredEvent->getHtmlTreeNode() != null) {
1200 $current_node->addItem($filteredEvent->getHtmlTreeNode());
1201 } else {
1202 // add the original node if we got back nothing from the server
1203 $current_node->addItem($htmlNode);
1208 return $node;
1211 //public function for logging the errors in writing file to CouchDB/Hard Disk
1212 public function document_upload_download_log($patientid, $content)
1214 $log_path = $GLOBALS['OE_SITE_DIR'] . "/documents/couchdb/";
1215 $log_file = 'log.txt';
1216 if (!is_dir($log_path)) {
1217 mkdir($log_path, 0777, true);
1220 $LOG = file_get_contents($log_path . $log_file);
1222 if ($this->cryptoGen->cryptCheckStandard($LOG)) {
1223 $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');
1226 $LOG .= $content;
1228 if (!empty($LOG)) {
1229 if ($GLOBALS['drive_encryption']) {
1230 $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');
1232 file_put_contents($log_path . $log_file, $LOG);
1236 public function document_send($email, $body, $attfile, $pname)
1238 if (empty($email)) {
1239 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1240 return;
1243 $desc = "Please check the attached patient document.\n Content:" . $body;
1244 $mail = new MyMailer();
1245 $from_name = $GLOBALS["practice_return_email_path"];
1246 $from = $GLOBALS["practice_return_email_path"];
1247 $mail->AddReplyTo($from, $from_name);
1248 $mail->SetFrom($from, $from);
1249 $to = $email ;
1250 $to_name = $email;
1251 $mail->AddAddress($to, $to_name);
1252 $subject = "Patient documents";
1253 $mail->Subject = $subject;
1254 $mail->Body = $desc;
1255 $mail->AddAttachment($attfile);
1256 if ($mail->Send()) {
1257 $retstatus = "email_sent";
1258 } else {
1259 $email_status = $mail->ErrorInfo;
1260 //echo "EMAIL ERROR: ".$email_status;
1261 $retstatus = "email_fail";
1265 //place to hold optional code
1266 //$first_node = array_keys($t->tree);
1267 //$first_node = $first_node[0];
1268 //$node1 = new HTML_TreeNode(array('text' => $t->get_node_name($first_node), 'link' => "test.php", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true), array('onclick' => "alert('foo'); return false", 'onexpand' => "alert('Expanded')"));
1270 //$this->_last_node = &$node1;
1272 // public function to tag a document to an encounter.
1273 public function tag_action_process(string $patient_id = null, $document_id)
1275 if ($_POST['process'] != "true") {
1276 die("process is '" . text($_POST['process']) . "', expected 'true'");
1277 return;
1280 // Create Encounter and Tag it.
1281 $event_date = date('Y-m-d H:i:s');
1282 $encounter_id = $_POST['encounter_id'];
1283 $encounter_check = $_POST['encounter_check'];
1284 $visit_category_id = $_POST['visit_category_id'];
1286 if (is_numeric($document_id)) {
1287 $messages = '';
1288 $d = new Document($document_id);
1289 $file_name = $d->get_url_file();
1290 if (!is_numeric($encounter_id)) {
1291 $encounter_id = 0;
1294 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1295 if ($encounter_check) {
1296 $provider_id = $_SESSION['authUserID'] ;
1298 // Get the logged in user's facility
1299 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1300 $username = $facilityRow['username'];
1301 $facility = $facilityRow['facility'];
1302 $facility_id = $facilityRow['facility_id'];
1303 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1304 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1305 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1307 $conn = $GLOBALS['adodb']['db'];
1308 $encounter = $conn->GenID("sequences");
1309 $query = "INSERT INTO form_encounter SET
1310 date = ?,
1311 reason = ?,
1312 facility = ?,
1313 sensitivity = 'normal',
1314 pc_catid = ?,
1315 facility_id = ?,
1316 billing_facility = ?,
1317 provider_id = ?,
1318 pid = ?,
1319 encounter = ?";
1320 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1321 $formID = sqlInsert($query, $bindArray);
1322 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1323 $d->set_encounter_id($encounter);
1324 $this->image_result_indication($d->id, $encounter);
1325 } else {
1326 $d->set_encounter_id($encounter_id);
1327 $this->image_result_indication($d->id, $encounter_id);
1329 $d->set_encounter_check($encounter_check);
1330 $d->persist();
1332 $messages .= xlt('Document tagged to Encounter successfully') . "<br />";
1335 $this->_state = false;
1336 $this->assign("messages", $messages);
1338 return $this->view_action($patient_id, $document_id);
1341 public function image_procedure_action(string $patient_id = null, $document_id)
1344 $img_procedure_id = $_POST['image_procedure_id'];
1345 $proc_code = $_POST['procedure_code'];
1347 if (is_numeric($document_id)) {
1348 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1349 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1350 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1351 if ($img_report_id == 0) {
1352 $report_date = date('Y-m-d H:i:s');
1353 $img_report_id = sqlInsert("INSERT INTO procedure_report(procedure_order_id,procedure_order_seq,date_collected,date_report,report_status) values(?,?,?,?,'final')", array($img_procedure_id,$img_order['procedure_order_seq'],$img_order['date_collected'],$report_date));
1356 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1357 if (empty($img_result)) {
1358 sqlStatement("INSERT INTO procedure_result(procedure_report_id,date,document_id,result_status) values(?,?,?,'final')", array($img_report_id,date('Y-m-d H:i:s'),$document_id));
1361 $this->image_result_indication($document_id, 0, $img_procedure_id);
1363 return $this->view_action($patient_id, $document_id);
1366 public function clear_procedure_tag_action(string $patient_id = null, $document_id)
1368 if (is_numeric($document_id)) {
1369 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1371 return $this->view_action($patient_id, $document_id);
1374 public function get_mapped_procedure($document_id)
1376 $map = array();
1377 if (is_numeric($document_id)) {
1378 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1379 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1380 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1381 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1382 where pres.document_id = ?", array($document_id));
1384 return $map;
1387 public function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1389 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1390 $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';
1392 // TODO: This should be moved into a service so we can handle things such as uuid generation....
1393 if ($encounter != 0) {
1394 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1395 } elseif ($image_procedure_id != 0) {
1396 $ep = sqlQuery("select u.username as assigned_to from procedure_order inner join users u on u.id = provider_id where procedure_order_id = ?", array($image_procedure_id));
1397 } else {
1398 $ep = array('assigned_to' => $_SESSION['authUser']);
1401 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1402 $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1403 setGpRelation(1, $doc_id, 6, $noteid);
1406 //clear encounter tag public function
1407 public function clear_encounter_tag_action(string $patient_id = null, $document_id)
1409 if (is_numeric($document_id)) {
1410 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1412 return $this->view_action($patient_id, $document_id);
1415 // this will set flag to skip acl check
1416 // this is needed for when uploading via services that piggyback on any user (ie. the background services) or via cron/cli
1417 public function skipAclCheck(): void
1419 $this->skip_acl_check = true;
1422 // this will check if flag has been set to skip the acl check
1423 // this is needed for when uploading via services that piggyback on any user (ie. the background services) or via cron/cli
1424 public function isSkipAclCheck(): bool
1426 return $this->skip_acl_check;