7 * @link https://www.open-emr.org
8 * @author Brady Miller <brady.g.miller@gmail.com>
9 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
10 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
13 require_once(dirname(__FILE__
) . "/../library/forms.inc");
15 use OpenEMR\Common\Acl\AclMain
;
16 use OpenEMR\Common\Crypto\CryptoGen
;
17 use OpenEMR\Common\Csrf\CsrfUtils
;
18 use OpenEMR\Services\FacilityService
;
19 use OpenEMR\Services\PatientService
;
21 class C_Document
extends Controller
26 var $document_categories;
29 var $manual_set_owner = false; // allows manual setting of a document owner/service
33 function __construct($template_mod = "general")
35 parent
::__construct();
36 $this->facilityService
= new FacilityService();
37 $this->patientService
= new PatientService();
38 $this->documents
= array();
39 $this->template_mod
= $template_mod;
40 $this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING']));
41 $this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
43 $this->assign("CSRF_TOKEN_FORM", CsrfUtils
::collectCsrfToken());
45 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
47 //get global config options for this namespace
48 $this->_config
= $GLOBALS['oer_config']['documents'];
50 $this->_args
= array("patient_id" => $_GET['patient_id']);
52 $this->assign("STYLE", $GLOBALS['style']);
53 $t = new CategoryTree(1);
56 $this->Document
= new Document();
58 // Create a crypto object that will be used for for encryption/decryption
59 $this->cryptoGen
= new CryptoGen();
62 function upload_action($patient_id, $category_id)
64 $category_name = $this->tree
->get_node_name($category_id);
65 $this->assign("category_id", $category_id);
66 $this->assign("category_name", $category_name);
67 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
68 $this->assign("patient_id", $patient_id);
70 // Added by Rod to support document template download from general_upload.html.
71 // Cloned from similar stuff in manage_document_templates.php.
72 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
73 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
74 if (file_exists($templatedir)) {
75 $dh = opendir($templatedir);
78 $templateslist = array();
79 while (false !== ($sfname = readdir($dh))) {
80 if (substr($sfname, 0, 1) == '.') {
83 $templateslist[$sfname] = $sfname;
86 ksort($templateslist);
87 foreach ($templateslist as $sfname) {
88 $templates_options .= "<option value='" . attr($sfname) .
89 "'>" . text($sfname) . "</option>";
92 $this->assign("TEMPLATES_LIST", $templates_options);
94 // duplicate template list for new template form editor sjp 05/20/2019
95 // will call as module or individual template.
96 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';
97 $templates_options = "<option value=''>-- " . xlt('Open Forms Module') . " --</option>";
98 if (file_exists($templatedir)) {
99 $dh = opendir($templatedir);
102 $templateslist = array();
103 while (false !== ($sfname = readdir($dh))) {
104 if (substr($sfname, 0, 1) == '.') {
107 if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {
108 $templateslist[$sfname] = $sfname;
112 ksort($templateslist);
113 foreach ($templateslist as $sfname) {
114 $optname = str_replace('_', ' ', basename($sfname, ".tpl"));
115 $templates_options .= "<option value='" . attr($sfname) . "'>" . text($optname) . "</option>";
118 $this->assign("TEMPLATES_LIST_PATIENT", $templates_options);
120 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
121 $this->assign("activity", $activity);
122 return $this->list_action($patient_id);
125 function zip_dicom_folder($study_name = null)
127 $zip = new ZipArchive();
128 $zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
129 if ($zip->open($zip_name, (ZipArchive
::CREATE | ZipArchive
::OVERWRITE
)) === true) {
130 foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
131 $zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
132 $fparts = pathinfo($name);
133 if (empty($fparts['extension'])) {
134 // viewer requires lowercase.
135 $fparts['extension'] = "dcm";
136 $name = $fparts['filename'] . ".dcm";
138 if ($fparts['extension'] == "DCM") {
139 // viewer requires lowercase.
140 $fparts['extension'] = "dcm";
141 $name = $fparts['filename'] . ".dcm";
143 // required extension for viewer
144 if ($fparts['extension'] != "dcm") {
147 move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
148 $zip->addFile($zfn, $name);
154 $file_array['name'][] = $study_name;
155 $file_array['type'][] = 'zip';
156 $file_array['tmp_name'][] = $zip_name;
157 $file_array['error'][] = '';
158 $file_array['size'][] = filesize($zip_name);
162 //Upload multiple files on single click
163 function upload_action_process()
166 // Collect a manually set owner if this has been set
167 // Used when want to manually assign the owning user/service such as the Direct mechanism
168 $non_HTTP_owner = false;
169 if ($this->manual_set_owner
) {
170 $non_HTTP_owner = $this->manual_set_owner
;
175 if ($GLOBALS['document_storage_method'] == 0) {
178 if ($GLOBALS['document_storage_method'] == 1) {
182 if ($_POST['process'] != "true") {
186 $doDecryption = false;
187 $encrypted = $_POST['encrypted'] ??
false;
188 $passphrase = $_POST['passphrase'] ??
'';
190 !$GLOBALS['hide_document_encryption'] &&
191 $encrypted && $passphrase
193 $doDecryption = true;
196 if (is_numeric($_POST['category_id'])) {
197 $category_id = $_POST['category_id'];
201 if (isset($_GET['patient_id']) && !$couchDB) {
202 $patient_id = $_GET['patient_id'];
203 } elseif (is_numeric($_POST['patient_id'])) {
204 $patient_id = $_POST['patient_id'];
207 if (!empty($_FILES['dicom_folder']['name'][0])) {
208 // let's zip um up then pass along new zip
209 $study_name = $_POST['destination'] ?
(trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
210 $study_name = preg_replace('/\s+/', '_', $study_name);
211 $_POST['destination'] = "";
212 $zipped = $this->zip_dicom_folder($study_name);
214 $_FILES['file'] = $zipped;
216 // and off we go! just fall through and let routine
217 // do its normal file processing..
220 $sentUploadStatus = array();
221 if (count($_FILES['file']['name']) > 0) {
224 foreach ($_FILES['file']['name'] as $key => $value) {
227 if ($_FILES['file']['error'][$key] > 0 ||
empty($fname) ||
$_FILES['file']['size'][$key] == 0) {
230 $fname = htmlentities("<empty>");
232 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
233 if ($_FILES['file']['size'][$key] == 0) {
234 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
236 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
237 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
239 // Test for a zip of DICOM images
240 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
241 $za = new ZipArchive();
242 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
244 $mimetype = "application/dicom+zip";
245 for ($i = 0; $i < $za->numFiles
; $i++
) {
246 $stat = $za->statIndex($i);
247 $fp = $za->getStream($stat['name']);
249 $head = fread($fp, 256);
251 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
252 $mimetype = "application/zip";
256 // if here -then a DICOM
257 $parts = pathinfo($stat['name']);
258 if ($parts['extension'] != "dcm" ||
empty($parts['extension'])) { // required extension for viewer
259 $new_name = $parts['filename'] . ".dcm";
260 $za->renameIndex($i, $new_name);
261 $za->renameName($parts['filename'], $new_name);
263 } else { // Rarely here
264 $mimetype = "application/zip";
269 if ($mimetype == "application/dicom+zip") {
270 $_FILES['file']['type'][$key] = $mimetype;
271 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
272 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
276 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
277 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
280 $filetext = $this->cryptoGen
->decryptStandard($filetext, $passphrase);
281 if ($filetext === false) {
282 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
286 if ($_POST['destination'] != '') {
287 $fname = $_POST['destination'];
289 // set mime, test for single DICOM and assign extension if missing.
290 $mimetype = $_FILES['file']['type'][$key];
291 if (strpos($filetext, 'DICM') !== false) {
292 $mimetype = 'application/dicom';
293 $parts = pathinfo($fname);
294 if (!$parts['extension']) {
299 $rc = $d->createDocument(
305 empty($_GET['higher_level_path']) ?
'' : $_GET['higher_level_path'],
306 empty($_POST['path_depth']) ?
1 : $_POST['path_depth'],
308 $_FILES['file']['tmp_name'][$key]
311 $error .= $rc . "\n";
313 $this->assign("upload_success", "true");
315 $sentUploadStatus[] = $d;
316 $this->assign("file", $sentUploadStatus);
319 // Option to run a custom plugin for each file upload.
320 // This was initially created to delete the original source file in a custom setting.
321 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
322 if (file_exists($upload_plugin)) {
323 include_once($upload_plugin);
325 $upload_plugin_pp = 'documentUploadPostProcess';
326 if (function_exists($upload_plugin_pp)) {
327 $tmp = call_user_func($upload_plugin_pp, $value, $d);
332 // Following is just an example of code in such a plugin file.
333 /*****************************************************
334 function documentUploadPostProcess($filename, &$d) {
335 $userid = $_SESSION['authUserID'];
336 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
337 $owner = strtolower($row['username']);
338 $dn = '1_' . ucfirst($owner);
339 $filepath = "/shared_network_directory/$dn/$filename";
340 if (@unlink($filepath)) return '';
341 return "Failed to delete '$filepath'.";
343 *****************************************************/
347 $this->assign("error", nl2br($error));
348 //$this->_state = false;
349 $_POST['process'] = "";
350 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
353 function note_action_process($patient_id)
355 // this function is a dual function that will set up a note associated with a document or send a document via email.
357 if ($_POST['process'] != "true") {
362 $n->set_owner($_SESSION['authUserID']);
363 parent
::populate_object($n);
364 if ($_POST['identifier'] == "no") {
365 // associate a note with a document
367 } elseif ($_POST['identifier'] == "yes") {
368 // send the document via email
369 $d = new Document($_POST['foreign_id']);
370 $url = $d->get_url();
371 $storagemethod = $d->get_storagemethod();
372 $couch_docid = $d->get_couch_docid();
373 $couch_revid = $d->get_couch_revid();
374 if ($couch_docid && $couch_revid) {
375 $couch = new CouchDB();
376 $resp = $couch->retrieve_doc($couch_docid);
377 $content = $resp->data
;
378 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
379 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
380 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
381 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
382 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
383 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
384 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
385 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
386 die(xlt("File retrieval from CouchDB failed"));
388 // place it in a temporary file and will remove the file below after emailed
389 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
390 $fh = fopen($temp_couchdb_url, "w");
391 fwrite($fh, base64_decode($content));
393 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
395 $url = preg_replace("|^(.*)://|", "", $url);
396 // Collect filename and path
397 $from_all = explode("/", $url);
398 $from_filename = array_pop($from_all);
399 $from_pathname_array = array();
400 for ($i = 0; $i < $d->get_path_depth(); $i++
) {
401 $from_pathname_array[] = array_pop($from_all);
403 $from_pathname_array = array_reverse($from_pathname_array);
404 $from_pathname = implode("/", $from_pathname_array);
405 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
407 if (!file_exists($temp_url)) {
408 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;
411 $pdetails = getPatientData($patient_id);
412 $pname = $pdetails['fname'] . " " . $pdetails['lname'];
413 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
414 if ($couch_docid && $couch_revid) {
415 // remove the temporary couchdb file
416 unlink($temp_couchdb_url);
419 $this->_state
= false;
420 $_POST['process'] = "";
421 return $this->view_action($patient_id, $n->get_foreign_id());
424 function default_action()
426 return $this->list_action();
429 function view_action(string $patient_id = null, $doc_id)
433 require_once(dirname(__FILE__
) . "/../library/lists.inc");
435 $d = new Document($doc_id);
436 $notes = $d->get_notes();
438 $this->assign("csrf_token_form", CsrfUtils
::collectCsrfToken());
440 $this->assign("file", $d);
441 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
442 $this->assign("NOTE_ACTION", $this->_link("note"));
443 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
444 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
445 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
446 $this->assign("webroot", $GLOBALS['webroot']);
448 // Added by Rod to support document delete:
450 if (AclMain
::aclCheckCore('patients', 'docs_rm')) {
451 $delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
452 ")'>" . xlt('Delete') . "</a>";
454 $this->assign("delete_string", $delete_string);
455 $this->assign("REFRESH_ACTION", $this->_link("list"));
457 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
458 "document_id=" . $d->get_id() . "&process=true");
460 // Added by Rod to support document date update:
461 $this->assign("DOCDATE", $d->get_docdate());
462 $this->assign("UPDATE_ACTION", $this->_link("update") .
463 "document_id=" . $d->get_id() . "&process=true");
465 // Added by Rod to support document issue update:
466 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
467 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
468 "pid = ? " . // AND enddate IS NULL " .
469 "ORDER BY type, begdate", array($patient_id));
470 while ($irow = sqlFetchArray($ires)) {
471 $desc = $irow['type'];
472 if ($ISSUE_TYPES[$desc]) {
473 $desc = $ISSUE_TYPES[$desc][2];
475 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
476 $sel = ($irow['id'] == $d->get_list_id()) ?
' selected' : '';
477 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
479 $this->assign("ISSUES_LIST", $issues_options);
481 // For tagging to encounter
482 // Populate the dropdown with patient's encounter list
483 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
484 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
485 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
486 "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));
487 if (sqlNumRows($result_docs) > 0) {
488 while ($row_result_docs = sqlFetchArray($result_docs)) {
489 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ?
' selected' : '';
490 $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>";
493 $this->assign("ENC_LIST", $encOptions);
495 //clear encounter tag
496 if ($d->get_encounter_id() != 0) {
497 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
499 $this->assign('clear_encounter_tag', 'javascript:void(0)');
502 //Populate the dropdown with category list
503 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
504 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
505 while ($crow = sqlFetchArray($cres)) {
506 $catid = $crow['pc_catid'];
507 if ($catid < 9 && $catid != 5) {
508 continue; // Applying same logic as in new encounter page.
510 $visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
512 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
514 $this->assign("notes", $notes);
516 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
517 // Populate the dropdown with image procedure order list
518 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
519 $imgOrders = sqlStatement("select procedure_name,po.procedure_order_id,procedure_code from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ? and poc.procedure_order_title = 'imaging'", array($patient_id));
520 $mapping = $this->get_mapped_procedure($d->get_id());
521 if (sqlNumRows($imgOrders) > 0) {
522 while ($row = sqlFetchArray($imgOrders)) {
524 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
525 $sel_proc = 'selected';
527 $imgOptions .= "<option value='" . attr($row['procedure_order_id']) . "' data-code='" . attr($row['procedure_code']) . "' $sel_proc>" . text($row['procedure_name'] . ' - ' . $row['procedure_code']) . "</option>";
531 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
533 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
535 $this->_last_node
= null;
537 $menu = new HTML_TreeMenu();
539 //pass an empty array because we don't want the documents for each category showing up in this list box
540 $rnode = $this->_array_recurse($this->tree
->tree
, array());
541 $menu->addItem($rnode);
542 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
544 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
546 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_view.html");
547 $this->assign("activity", $activity);
549 return $this->list_action($patient_id);
553 * Retrieve file from hard disk / CouchDB.
554 * In case that file isn't download this function will return thumbnail image (if exist).
555 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
556 * @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.
558 function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
560 $encrypted = $_POST['encrypted'] ??
false;
561 $passphrase = $_POST['passphrase'] ??
'';
562 $doEncryption = false;
564 !$GLOBALS['hide_document_encryption'] &&
565 $encrypted == "true" &&
568 $doEncryption = true;
571 //controller function ruins booleans, so need to manually re-convert to booleans
572 if ($as_file == "true") {
574 } elseif ($as_file == "false") {
577 if ($original_file == "true") {
578 $original_file = true;
579 } elseif ($original_file == "false") {
580 $original_file = false;
582 if ($disable_exit == "true") {
583 $disable_exit = true;
584 } elseif ($disable_exit == "false") {
585 $disable_exit = false;
587 if ($show_original == "true") {
588 $show_original = true;
589 } elseif ($show_original == "false") {
590 $show_original = false;
594 case "patient_picture":
595 $document_id = $this->patientService
->getPatientPictureDocumentId($patient_id);
599 $d = new Document($document_id);
600 $url = $d->get_url();
601 $th_url = $d->get_thumb_url();
603 $storagemethod = $d->get_storagemethod();
604 $couch_docid = $d->get_couch_docid();
605 $couch_revid = $d->get_couch_revid();
607 if ($couch_docid && $couch_revid && $original_file) {
608 // standard case for collecting a document from couchdb
609 $couch = new CouchDB();
610 $resp = $couch->retrieve_doc($couch_docid);
611 //Take thumbnail file when is not null and file is presented online
612 if (!$as_file && !is_null($th_url) && !$show_original) {
613 $content = $resp->th_data
;
615 $content = $resp->data
;
617 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
618 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
619 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
620 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
621 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
622 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
623 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
624 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
625 die(xlt("File retrieval from CouchDB failed"));
627 if ($d->get_encrypted() == 1) {
628 $filetext = $this->cryptoGen
->decryptStandard($content, null, 'database');
630 $filetext = base64_decode($content);
632 if ($disable_exit == true) {
635 header('Content-Description: File Transfer');
636 header('Content-Transfer-Encoding: binary');
637 header('Expires: 0');
638 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
639 header('Pragma: public');
641 $ciphertext = $this->cryptoGen
->encryptStandard($filetext, $passphrase);
642 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
643 header("Content-Type: application/octet-stream");
644 header("Content-Length: " . strlen($ciphertext));
647 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
648 header("Content-Type: " . $d->get_mimetype());
649 header("Content-Length: " . strlen($filetext));
652 exit;//exits only if file download from CouchDB is successfull.
654 if ($couch_docid && $couch_revid) {
655 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
656 //try to convert it if it has not yet been converted
657 //first, see if the converted jpg already exists
658 $couch = new CouchDB();
659 $resp = $couch->retrieve_doc("converted_" . $couch_docid);
660 $content = $resp->data
;
661 if ($content == '') {
662 //create the converted jpg
663 $couchM = new CouchDB();
664 $respM = $couchM->retrieve_doc($couch_docid);
665 if ($d->get_encrypted() == 1) {
666 $contentM = $this->cryptoGen
->decryptStandard($respM->data
, null, 'database');
668 $contentM = base64_decode($respM->data
);
670 if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
671 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
672 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
673 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
674 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
675 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
676 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
677 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
678 die(xlt("File retrieval from CouchDB failed"));
680 // place the from-file into a temporary file
681 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
682 file_put_contents($from_file_tmp_name, $contentM);
683 // prepare a temporary file for the to-file
684 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
685 $to_file_tmp_name = $to_file_tmp . ".jpg";
686 // convert file to jpg
687 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
688 // remove from tmp file
689 unlink($from_file_tmp_name);
690 // save the to-file if a to-file was created in above convert call
691 if (is_file($to_file_tmp_name)) {
692 $couchI = new CouchDB();
693 if ($d->get_encrypted() == 1) {
694 $document = $this->cryptoGen
->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
696 $document = base64_encode(file_get_contents($to_file_tmp_name));
698 $couchI->save_doc(['_id' => "converted_" . $couch_docid, 'data' => $document]);
699 // remove to tmp files
700 unlink($to_file_tmp);
701 unlink($to_file_tmp_name);
703 error_log("ERROR: Document '" . errorLogEscape($d->get_name()) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
705 // now collect the newly created converted jpg
706 $couchF = new CouchDB();
707 $respF = $couchF->retrieve_doc("converted_" . $couch_docid);
708 if ($d->get_encrypted() == 1) {
709 $content = $this->cryptoGen
->decryptStandard($respF->data
, null, 'database');
711 $content = base64_decode($respF->data
);
714 // decrypt/decode when converted jpg already exists
715 if ($d->get_encrypted() == 1) {
716 $content = $this->cryptoGen
->decryptStandard($resp->data
, null, 'database');
718 $content = base64_decode($resp->data
);
721 $filetext = $content;
722 if ($disable_exit == true) {
725 header("Pragma: public");
726 header("Expires: 0");
727 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
728 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
729 header("Content-Type: image/jpeg");
730 header("Content-Length: " . strlen($filetext));
735 //Take thumbnail file when is not null and file is presented online
736 if (!$as_file && !is_null($th_url) && !$show_original) {
740 //strip url of protocol handler
741 $url = preg_replace("|^(.*)://|", "", $url);
743 //change full path to current webroot. this is for documents that may have
744 //been moved from a different filesystem and the full path in the database
745 //is not current. this is also for documents that may of been moved to
746 //different patients. Note that the path_depth is used to see how far down
747 //the path to go. For example, originally the path_depth was always 1, which
748 //only allowed things like documents/1/<file>, but now can have more structured
749 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
751 // NOTE that $from_filename and basename($url) are the same thing
752 $from_all = explode("/", $url);
753 $from_filename = array_pop($from_all);
754 $from_pathname_array = array();
755 for ($i = 0; $i < $d->get_path_depth(); $i++
) {
756 $from_pathname_array[] = array_pop($from_all);
758 $from_pathname_array = array_reverse($from_pathname_array);
759 $from_pathname = implode("/", $from_pathname_array);
760 if ($couch_docid && $couch_revid) {
761 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
762 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
764 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
767 if (file_exists($temp_url)) {
771 if (!file_exists($url)) {
772 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;
774 if ($original_file) {
775 //normal case when serving the file referenced in database
776 if ($d->get_encrypted() == 1) {
777 $filetext = $this->cryptoGen
->decryptStandard(file_get_contents($url), null, 'database');
779 $filetext = file_get_contents($url);
781 if ($disable_exit == true) {
784 header('Content-Description: File Transfer');
785 header('Content-Transfer-Encoding: binary');
786 header('Expires: 0');
787 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
788 header('Pragma: public');
790 $ciphertext = $this->cryptoGen
->encryptStandard($filetext, $passphrase);
791 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
792 header("Content-Type: application/octet-stream");
793 header("Content-Length: " . strlen($ciphertext));
796 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
797 header("Content-Type: " . $d->get_mimetype());
798 header("Content-Length: " . strlen($filetext));
803 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
804 //try to convert it if it has not yet been converted
806 if (strrpos(basename_international($url), '.') === false) {
807 $convertedFile = basename_international($url) . '_converted.jpg';
809 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
811 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
812 if (!is_file($url)) {
813 if ($d->get_encrypted() == 1) {
814 // decrypt the from-file into a temporary file
815 $from_file_unencrypted = $this->cryptoGen
->decryptStandard(file_get_contents($originalUrl), null, 'database');
816 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
817 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
818 // prepare a temporary file for the unencrypted to-file
819 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
820 $to_file_tmp_name = $to_file_tmp . ".jpg";
821 // convert file to jpg
822 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
823 // remove unencrypted tmp file
824 unlink($from_file_tmp_name);
825 // make the encrypted to-file if a to-file was created in above convert call
826 if (is_file($to_file_tmp_name)) {
827 $to_file_encrypted = $this->cryptoGen
->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
828 file_put_contents($url, $to_file_encrypted);
829 // remove unencrypted tmp files
830 unlink($to_file_tmp);
831 unlink($to_file_tmp_name);
834 // convert file to jpg
835 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
839 if ($d->get_encrypted() == 1) {
840 $filetext = $this->cryptoGen
->decryptStandard(file_get_contents($url), null, 'database');
842 $filetext = file_get_contents($url);
846 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
848 if ($disable_exit == true) {
851 header("Pragma: public");
852 header("Expires: 0");
853 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
854 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
855 header("Content-Type: image/jpeg");
856 header("Content-Length: " . strlen($filetext));
863 function move_action_process(string $patient_id = null, $document_id)
865 if ($_POST['process'] != "true") {
871 $new_category_id = $_POST['new_category_id'];
872 $new_patient_id = $_POST['new_patient_id'];
874 //move to new category
875 if (is_numeric($new_category_id) && is_numeric($document_id)) {
876 $sql = "UPDATE categories_to_documents set category_id = ? where document_id = ?";
877 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
879 $this->tree
->_db
->Execute($sql, [$new_category_id, $document_id]);
882 //move to new patient
883 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
884 $d = new Document($document_id);
885 $sql = "SELECT pid from patient_data where pid = ?";
886 $result = $d->_db
->Execute($sql, [$new_patient_id]);
888 if (!$result ||
$result->EOF
) {
889 //patient id does not exist
890 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
892 $changefailed = !$d->change_patient($new_patient_id);
894 $this->_state
= false;
895 if (!$changefailed) {
896 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
898 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
900 $this->assign("messages", $messages);
901 return $this->list_action($patient_id);
905 $this->_state
= false;
906 $this->assign("messages", $messages);
907 return $this->view_action($patient_id, $document_id);
910 function validate_action_process(string $patient_id = null, $document_id)
913 $d = new Document($document_id);
914 if ($d->couch_docid
&& $d->couch_revid
) {
915 $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
916 $url = $file_path . $d->get_url();
917 $couch = new CouchDB();
918 $resp = $couch->retrieve_doc($d->couch_docid
);
919 if ($d->get_encrypted() == 1) {
920 $content = $this->cryptoGen
->decryptStandard($resp->data
, null, 'database');
922 $content = base64_decode($resp->data
);
925 $url = $d->get_url();
927 //strip url of protocol handler
928 $url = preg_replace("|^(.*)://|", "", $url);
930 //change full path to current webroot. this is for documents that may have
931 //been moved from a different filesystem and the full path in the database
932 //is not current. this is also for documents that may of been moved to
933 //different patients. Note that the path_depth is used to see how far down
934 //the path to go. For example, originally the path_depth was always 1, which
935 //only allowed things like documents/1/<file>, but now can have more structured
936 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
938 // NOTE that $from_filename and basename($url) are the same thing
939 $from_all = explode("/", $url);
940 $from_filename = array_pop($from_all);
941 $from_pathname_array = array();
942 for ($i = 0; $i < $d->get_path_depth(); $i++
) {
943 $from_pathname_array[] = array_pop($from_all);
945 $from_pathname_array = array_reverse($from_pathname_array);
946 $from_pathname = implode("/", $from_pathname_array);
947 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
948 if (file_exists($temp_url)) {
952 if ($_POST['process'] != "true") {
953 die("process is '" . text($_POST['process']) . "', expected 'true'");
957 if ($d->get_encrypted() == 1) {
958 $content = $this->cryptoGen
->decryptStandard(file_get_contents($url), null, 'database');
960 $content = file_get_contents($url);
964 if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {
965 // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0
966 $current_hash = sha1($content);
968 $current_hash = hash('sha3-512', $content);
970 $messages = xl('Current Hash') . ": " . $current_hash . " | ";
971 $messages .= xl('Stored Hash') . ": " . $d->get_hash();
972 if ($d->get_hash() == '') {
973 $d->hash
= $current_hash;
976 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
977 } elseif ($current_hash != $d->get_hash()) {
978 $messages .= xl('Hash does not match. Data integrity has been compromised.');
980 $messages = xl('Document passed integrity check.') . ' | ' . $messages;
982 $this->_state
= false;
983 $this->assign("messages", $messages);
984 return $this->view_action($patient_id, $document_id);
987 // Added by Rod for metadata update.
989 function update_action_process(string $patient_id = null, $document_id)
992 if ($_POST['process'] != "true") {
993 die("process is '" . $_POST['process'] . "', expected 'true'");
997 $docdate = $_POST['docdate'];
998 $docname = $_POST['docname'];
999 $issue_id = $_POST['issue_id'];
1001 if (is_numeric($document_id)) {
1003 $d = new Document($document_id);
1004 $file_name = $d->get_name();
1007 $docname != $file_name
1010 $d->set_name($docname);
1013 $messages .= xl('Document successfully renamed.') . "<br />";
1016 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1017 $docdate = "$docdate";
1021 if (!is_numeric($issue_id)) {
1024 $couch_docid = $d->get_couch_docid();
1025 $couch_revid = $d->get_couch_revid();
1026 if ($couch_docid && $couch_revid) {
1027 $sql = "UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?";
1028 $this->tree
->_db
->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);
1030 $sql = "UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?";
1031 $this->tree
->_db
->Execute($sql, [$docdate, $issue_id, $document_id]);
1033 $messages .= xl('Document date and issue updated successfully') . "<br />";
1036 $this->_state
= false;
1037 $this->assign("messages", $messages);
1038 return $this->view_action($patient_id, $document_id);
1041 function list_action($patient_id = "")
1043 $this->_last_node
= null;
1044 $categories_list = $this->tree
->_get_categories_array($patient_id);
1045 //print_r($categories_list);
1047 $menu = new HTML_TreeMenu();
1048 $rnode = $this->_array_recurse($this->tree
->tree
, $categories_list);
1049 $menu->addItem($rnode);
1050 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1051 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1052 $this->assign("tree_html", $treeMenu->toHTML());
1054 $is_new = isset($_GET['patient_name']) ?
1 : false;
1055 $place_hld = isset($_GET['patient_name']) ?
filter_input(INPUT_GET
, 'patient_name') : xl("Patient search or select.");
1056 $cur_pid = isset($_GET['patient_id']) ?
filter_input(INPUT_GET
, 'patient_id') : '';
1057 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1058 if ($cur_pid == '00') {
1062 $this->assign('is_new', $is_new);
1063 $this->assign('place_hld', $place_hld);
1064 $this->assign('cur_pid', $cur_pid);
1065 $this->assign('used_msg', $used_msg);
1066 $this->assign('demo_pid', ($_SESSION['pid'] ??
null));
1068 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
1071 function &_array_recurse($array, $categories = array())
1073 if (!is_array($array)) {
1076 $node = &$this->_last_node
;
1077 $current_node = &$node;
1078 $expandedIcon = 'folder-expanded.gif';
1079 foreach ($array as $id => $ar) {
1080 $icon = 'folder.gif';
1081 if (is_array($ar) ||
!empty($id)) {
1082 if ($node == null) {
1083 //echo "r:" . $this->tree->get_node_name($id) . "<br />";
1084 $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));
1085 $this->_last_node
= &$rnode;
1087 $current_node = &$rnode;
1089 //echo "p:" . $this->tree->get_node_name($id) . "<br />";
1090 $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)));
1091 $current_node = &$this->_last_node
;
1094 $this->_array_recurse($ar, $categories);
1096 if ($id === 0 && !empty($ar)) {
1097 $info = $this->tree
->get_node_info($id);
1098 //echo "b:" . $this->tree->get_node_name($id) . "<br />";
1099 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1101 //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
1102 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1103 if ($id !== 0 && is_object($node)) {
1104 //echo "n:" . $this->tree->get_node_name($id) . "<br />";
1105 $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)));
1110 // If there are documents in this document category, then add their
1111 // attributes to the current node.
1112 $icon = "file3.png";
1113 if (!empty($categories[$id]) && is_array($categories[$id])) {
1114 foreach ($categories[$id] as $doc) {
1115 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1116 // If user has no access then there will be no link.
1117 if (!AclMain
::aclCheckAcoSpec($doc['aco_spec'])) {
1120 if ($this->tree
->get_node_name($id) == "CCR") {
1121 $current_node->addItem(new HTML_TreeNode(array(
1122 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1125 'expandedIcon' => $expandedIcon,
1126 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1128 } elseif ($this->tree
->get_node_name($id) == "CCD") {
1129 $current_node->addItem(new HTML_TreeNode(array(
1130 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1133 'expandedIcon' => $expandedIcon,
1134 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1137 $current_node->addItem(new HTML_TreeNode(array(
1138 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1141 'expandedIcon' => $expandedIcon
1150 //function for logging the errors in writing file to CouchDB/Hard Disk
1151 function document_upload_download_log($patientid, $content)
1153 $log_path = $GLOBALS['OE_SITE_DIR'] . "/documents/couchdb/";
1154 $log_file = 'log.txt';
1155 if (!is_dir($log_path)) {
1156 mkdir($log_path, 0777, true);
1159 $LOG = file_get_contents($log_path . $log_file);
1161 if ($this->cryptoGen
->cryptCheckStandard($LOG)) {
1162 $LOG = $this->cryptoGen
->decryptStandard($LOG, null, 'database');
1168 if ($GLOBALS['drive_encryption']) {
1169 $LOG = $this->cryptoGen
->encryptStandard($LOG, null, 'database');
1171 file_put_contents($log_path . $log_file, $LOG);
1175 function document_send($email, $body, $attfile, $pname)
1177 if (empty($email)) {
1178 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1182 $desc = "Please check the attached patient document.\n Content:" . $body;
1183 $mail = new MyMailer();
1184 $from_name = $GLOBALS["practice_return_email_path"];
1185 $from = $GLOBALS["practice_return_email_path"];
1186 $mail->AddReplyTo($from, $from_name);
1187 $mail->SetFrom($from, $from);
1190 $mail->AddAddress($to, $to_name);
1191 $subject = "Patient documents";
1192 $mail->Subject
= $subject;
1193 $mail->Body
= $desc;
1194 $mail->AddAttachment($attfile);
1195 if ($mail->Send()) {
1196 $retstatus = "email_sent";
1198 $email_status = $mail->ErrorInfo
;
1199 //echo "EMAIL ERROR: ".$email_status;
1200 $retstatus = "email_fail";
1204 //place to hold optional code
1205 //$first_node = array_keys($t->tree);
1206 //$first_node = $first_node[0];
1207 //$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')"));
1209 //$this->_last_node = &$node1;
1211 // Function to tag a document to an encounter.
1212 function tag_action_process(string $patient_id = null, $document_id)
1214 if ($_POST['process'] != "true") {
1215 die("process is '" . text($_POST['process']) . "', expected 'true'");
1219 // Create Encounter and Tag it.
1220 $event_date = date('Y-m-d H:i:s');
1221 $encounter_id = $_POST['encounter_id'];
1222 $encounter_check = $_POST['encounter_check'];
1223 $visit_category_id = $_POST['visit_category_id'];
1225 if (is_numeric($document_id)) {
1227 $d = new Document($document_id);
1228 $file_name = $d->get_url_file();
1229 if (!is_numeric($encounter_id)) {
1233 $encounter_check = ( $encounter_check == 'on') ?
1 : 0;
1234 if ($encounter_check) {
1235 $provider_id = $_SESSION['authUserID'] ;
1237 // Get the logged in user's facility
1238 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1239 $username = $facilityRow['username'];
1240 $facility = $facilityRow['facility'];
1241 $facility_id = $facilityRow['facility_id'];
1242 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1243 $billingFacility = $this->facilityService
->getPrimaryBusinessEntity();
1244 $billingFacilityID = ( $billingFacility['id'] ) ?
$billingFacility['id'] : $facility_id;
1246 $conn = $GLOBALS['adodb']['db'];
1247 $encounter = $conn->GenID("sequences");
1248 $query = "INSERT INTO form_encounter SET
1252 sensitivity = 'normal',
1255 billing_facility = ?,
1259 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1260 $formID = sqlInsert($query, $bindArray);
1261 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1262 $d->set_encounter_id($encounter);
1263 $this->image_result_indication($d->id
, $encounter);
1265 $d->set_encounter_id($encounter_id);
1266 $this->image_result_indication($d->id
, $encounter_id);
1268 $d->set_encounter_check($encounter_check);
1271 $messages .= xlt('Document tagged to Encounter successfully') . "<br />";
1274 $this->_state
= false;
1275 $this->assign("messages", $messages);
1277 return $this->view_action($patient_id, $document_id);
1280 function image_procedure_action(string $patient_id = null, $document_id)
1283 $img_procedure_id = $_POST['image_procedure_id'];
1284 $proc_code = $_POST['procedure_code'];
1286 if (is_numeric($document_id)) {
1287 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1288 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1289 $img_report_id = !empty($img_report['procedure_report_id']) ?
$img_report['procedure_report_id'] : 0;
1290 if ($img_report_id == 0) {
1291 $report_date = date('Y-m-d H:i:s');
1292 $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));
1295 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1296 if (empty($img_result)) {
1297 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));
1300 $this->image_result_indication($document_id, 0, $img_procedure_id);
1302 return $this->view_action($patient_id, $document_id);
1305 function clear_procedure_tag_action(string $patient_id = null, $document_id)
1307 if (is_numeric($document_id)) {
1308 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1310 return $this->view_action($patient_id, $document_id);
1313 function get_mapped_procedure($document_id)
1316 if (is_numeric($document_id)) {
1317 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1318 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1319 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1320 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1321 where pres.document_id = ?", array($document_id));
1326 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1328 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1329 $narration = isset($doc_notes['note']) ?
'With Narration' : 'Without Narration';
1331 if ($encounter != 0) {
1332 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1333 } elseif ($image_procedure_id != 0) {
1334 $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));
1336 $ep = array('assigned_to' => $_SESSION['authUser']);
1339 $encounter_provider = isset($ep['assigned_to']) ?
$ep['assigned_to'] : $_SESSION['authUser'];
1340 $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1341 setGpRelation(1, $doc_id, 6, $noteid);
1344 //clear encounter tag function
1345 function clear_encounter_tag_action(string $patient_id = null, $document_id)
1347 if (is_numeric($document_id)) {
1348 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1350 return $this->view_action($patient_id, $document_id);