feat: Displaying date in specimen column of lab results. (#6918)
[openemr.git] / controllers / C_Document.class.php
blob716e6c8c222baf53ef7c7e35ddac689e8cc10d07
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 * @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(__DIR__ . "/../library/forms.inc.php");
14 require_once(__DIR__ . "/../library/patient.inc.php");
16 use OpenEMR\Common\Acl\AclMain;
17 use OpenEMR\Common\Crypto\CryptoGen;
18 use OpenEMR\Common\Csrf\CsrfUtils;
19 use OpenEMR\Common\Logging\SystemLogger;
20 use OpenEMR\Common\Twig\TwigContainer;
21 use OpenEMR\Services\FacilityService;
22 use OpenEMR\Services\PatientService;
23 use OpenEMR\Events\PatientDocuments\PatientDocumentTreeViewFilterEvent;
25 class C_Document extends Controller
27 public $documents;
28 public $document_categories;
29 public $tree;
30 public $_config;
31 public $manual_set_owner = false; // allows manual setting of a document owner/service
32 public $facilityService;
33 public $patientService;
34 public $_last_node;
35 private $Document;
36 private $cryptoGen;
37 private bool $skip_acl_check = false;
39 public function __construct($template_mod = "general")
41 parent::__construct();
42 $this->facilityService = new FacilityService();
43 $this->patientService = new PatientService();
44 $this->documents = array();
45 $this->template_mod = $template_mod;
46 $this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING'] ?? ''));
47 $this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
49 if (php_sapi_name() !== 'cli') {
50 // skip when this is being called via command line for the ccda importing
51 $this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
54 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
56 //get global config options for this namespace
57 $this->_config = $GLOBALS['oer_config']['documents'];
59 $this->_args = array("patient_id" => ($_GET['patient_id'] ?? null));
61 $this->assign("STYLE", $GLOBALS['style']);
62 $t = new CategoryTree(1);
63 //print_r($t->tree);
64 $this->tree = $t;
65 $this->Document = new Document();
67 // Create a crypto object that will be used for for encryption/decryption
68 $this->cryptoGen = new CryptoGen();
71 public function upload_action($patient_id, $category_id)
73 $category_name = $this->tree->get_node_name($category_id);
74 $this->assign("category_id", $category_id);
75 $this->assign("category_name", $category_name);
76 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
77 $this->assign("patient_id", $patient_id);
79 // Added by Rod to support document template download from general_upload.html.
80 // Cloned from similar stuff in manage_document_templates.php.
81 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
82 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
83 if (file_exists($templatedir)) {
84 $dh = opendir($templatedir);
86 if (!empty($dh)) {
87 $templateslist = array();
88 while (false !== ($sfname = readdir($dh))) {
89 if (substr($sfname, 0, 1) == '.') {
90 continue;
92 $templateslist[$sfname] = $sfname;
94 closedir($dh);
95 ksort($templateslist);
96 foreach ($templateslist as $sfname) {
97 $templates_options .= "<option value='" . attr($sfname) .
98 "'>" . text($sfname) . "</option>";
101 $this->assign("TEMPLATES_LIST", $templates_options);
103 // duplicate template list for new template form editor sjp 05/20/2019
104 // will call as module or individual template.
105 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';
106 $templates_options = "<option value=''>-- " . xlt('Open Forms Module') . " --</option>";
107 if (file_exists($templatedir)) {
108 $dh = opendir($templatedir);
110 if ($dh) {
111 $templateslist = array();
112 while (false !== ($sfname = readdir($dh))) {
113 if (substr($sfname, 0, 1) == '.') {
114 continue;
116 if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {
117 $templateslist[$sfname] = $sfname;
120 closedir($dh);
121 ksort($templateslist);
122 foreach ($templateslist as $sfname) {
123 $optname = str_replace('_', ' ', basename($sfname, ".tpl"));
124 $templates_options .= "<option value='" . attr($sfname) . "'>" . text($optname) . "</option>";
127 $this->assign("TEMPLATES_LIST_PATIENT", $templates_options);
129 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
130 $this->assign("activity", $activity);
131 return $this->list_action($patient_id);
134 public function zip_dicom_folder($study_name = null)
136 $zip = new ZipArchive();
137 $zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
138 if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {
139 foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
140 $zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
141 $fparts = pathinfo($name);
142 if (empty($fparts['extension'])) {
143 // viewer requires lowercase.
144 $fparts['extension'] = "dcm";
145 $name = $fparts['filename'] . ".dcm";
147 if ($fparts['extension'] == "DCM") {
148 // viewer requires lowercase.
149 $fparts['extension'] = "dcm";
150 $name = $fparts['filename'] . ".dcm";
152 // required extension for viewer
153 if ($fparts['extension'] != "dcm") {
154 continue;
156 move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
157 $zip->addFile($zfn, $name);
159 $zip->close();
160 } else {
161 return false;
163 $file_array['name'][] = $study_name;
164 $file_array['type'][] = 'zip';
165 $file_array['tmp_name'][] = $zip_name;
166 $file_array['error'][] = '';
167 $file_array['size'][] = filesize($zip_name);
168 return $file_array;
171 //Upload multiple files on single click
172 public function upload_action_process()
175 // Collect a manually set owner if this has been set
176 // Used when want to manually assign the owning user/service such as the Direct mechanism
177 $non_HTTP_owner = false;
178 if ($this->manual_set_owner) {
179 $non_HTTP_owner = $this->manual_set_owner;
182 $couchDB = false;
183 $harddisk = false;
184 if ($GLOBALS['document_storage_method'] == 0) {
185 $harddisk = true;
187 if ($GLOBALS['document_storage_method'] == 1) {
188 $couchDB = true;
191 if ($_POST['process'] != "true") {
192 return;
195 $doDecryption = false;
196 $encrypted = $_POST['encrypted'] ?? false;
197 $passphrase = $_POST['passphrase'] ?? '';
198 if (
199 !$GLOBALS['hide_document_encryption'] &&
200 $encrypted && $passphrase
202 $doDecryption = true;
205 if (is_numeric($_POST['category_id'])) {
206 $category_id = $_POST['category_id'];
207 } else {
208 $category_id = 1;
211 $patient_id = 0;
212 if (isset($_GET['patient_id']) && !$couchDB) {
213 $patient_id = $_GET['patient_id'];
214 } elseif (is_numeric($_POST['patient_id'])) {
215 $patient_id = $_POST['patient_id'];
218 // ensure user has access to the category that is being uploaded to
219 $skipUpload = false;
220 if (!$this->isSkipAclCheck()) {
221 $acoSpec = sqlQuery("SELECT `aco_spec` from `categories` WHERE `id` = ?", [$category_id])['aco_spec'];
222 if (AclMain::aclCheckAcoSpec($acoSpec) === false) {
223 $error = xl("Not authorized to upload to the selected category.\n");
224 $skipUpload = true;
225 (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]);
229 if (!$skipUpload && !empty($_FILES['dicom_folder']['name'][0])) {
230 // let's zip um up then pass along new zip
231 $study_name = $_POST['destination'] ? (trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
232 $study_name = preg_replace('/\s+/', '_', $study_name);
233 $_POST['destination'] = "";
234 $zipped = $this->zip_dicom_folder($study_name);
235 if ($zipped) {
236 $_FILES['file'] = $zipped;
238 // and off we go! just fall through and let routine
239 // do its normal file processing..
242 $sentUploadStatus = array();
243 if (!$skipUpload && count($_FILES['file']['name']) > 0) {
244 $upl_inc = 0;
246 foreach ($_FILES['file']['name'] as $key => $value) {
247 $fname = $value;
248 $error = "";
249 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
250 $fname = $value;
251 if (empty($fname)) {
252 $fname = htmlentities("<empty>");
254 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
255 if ($_FILES['file']['size'][$key] == 0) {
256 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
258 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
259 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
260 } else {
261 // Test for a zip of DICOM images
262 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
263 $za = new ZipArchive();
264 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
265 if ($handler) {
266 $mimetype = "application/dicom+zip";
267 for ($i = 0; $i < $za->numFiles; $i++) {
268 $stat = $za->statIndex($i);
269 $fp = $za->getStream($stat['name']);
270 if ($fp) {
271 $head = fread($fp, 256);
272 fclose($fp);
273 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
274 $mimetype = "application/zip";
275 break;
277 unset($head);
278 // if here -then a DICOM
279 $parts = pathinfo($stat['name']);
280 if ($parts['extension'] != "dcm" || empty($parts['extension'])) { // required extension for viewer
281 $new_name = $parts['filename'] . ".dcm";
282 $za->renameIndex($i, $new_name);
283 $za->renameName($parts['filename'], $new_name);
285 } else { // Rarely here
286 $mimetype = "application/zip";
287 break;
290 $za->close();
291 if ($mimetype == "application/dicom+zip") {
292 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
293 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
297 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
298 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
299 fclose($tmpfile);
300 if ($doDecryption) {
301 $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
302 if ($filetext === false) {
303 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
304 $filetext = "";
307 if ($_POST['destination'] != '') {
308 $fname = $_POST['destination'];
310 // test for single DICOM and assign extension if missing.
311 if (strpos($filetext, 'DICM') !== false) {
312 $mimetype = 'application/dicom';
313 $parts = pathinfo($fname);
314 if (!$parts['extension']) {
315 $fname .= '.dcm';
318 // set mimetype (if not already set above)
319 if (empty($mimetype)) {
320 $mimetype = mime_content_type($_FILES['file']['tmp_name'][$key]);
322 // if mimetype still empty, then do not upload the file
323 if (empty($mimetype)) {
324 $error = xl("Unable to discover mimetype, so did not upload " . $_FILES['file']['tmp_name'][$key]) . ".\n";
325 continue;
327 $d = new Document();
328 $rc = $d->createDocument(
329 $patient_id,
330 $category_id,
331 $fname,
332 $mimetype,
333 $filetext,
334 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
335 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
336 $non_HTTP_owner,
337 $_FILES['file']['tmp_name'][$key]
339 if ($rc) {
340 $error .= $rc . "\n";
341 } else {
342 $this->assign("upload_success", "true");
344 $sentUploadStatus[] = $d;
345 $this->assign("file", $sentUploadStatus);
348 // Option to run a custom plugin for each file upload.
349 // This was initially created to delete the original source file in a custom setting.
350 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
351 if (file_exists($upload_plugin)) {
352 include_once($upload_plugin);
354 $upload_plugin_pp = 'documentUploadPostProcess';
355 if (function_exists($upload_plugin_pp)) {
356 $tmp = call_user_func($upload_plugin_pp, $value, $d);
357 if ($tmp) {
358 $error = $tmp;
361 // Following is just an example of code in such a plugin file.
362 /*****************************************************
363 public function documentUploadPostProcess($filename, &$d) {
364 $userid = $_SESSION['authUserID'];
365 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
366 $owner = strtolower($row['username']);
367 $dn = '1_' . ucfirst($owner);
368 $filepath = "/shared_network_directory/$dn/$filename";
369 if (@unlink($filepath)) return '';
370 return "Failed to delete '$filepath'.";
372 *****************************************************/
376 $this->assign("error", $error);
377 //$this->_state = false;
378 $_POST['process'] = "";
379 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
382 public function note_action_process($patient_id)
384 // this public function is a dual public function that will set up a note associated with a document or send a document via email.
386 if ($_POST['process'] != "true") {
387 return;
390 $n = new Note();
391 $n->set_owner($_SESSION['authUserID']);
392 parent::populate_object($n);
393 if ($_POST['identifier'] == "no") {
394 // associate a note with a document
395 $n->persist();
396 } elseif ($_POST['identifier'] == "yes") {
397 // send the document via email
398 $d = new Document($_POST['foreign_id']);
399 $url = $d->get_url();
400 $storagemethod = $d->get_storagemethod();
401 $couch_docid = $d->get_couch_docid();
402 $couch_revid = $d->get_couch_revid();
403 if ($couch_docid && $couch_revid) {
404 $couch = new CouchDB();
405 $resp = $couch->retrieve_doc($couch_docid);
406 $content = $resp->data;
407 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
408 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
409 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
410 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
411 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
412 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
413 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
414 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
415 die(xlt("File retrieval from CouchDB failed"));
417 // place it in a temporary file and will remove the file below after emailed
418 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
419 $fh = fopen($temp_couchdb_url, "w");
420 fwrite($fh, base64_decode($content));
421 fclose($fh);
422 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
423 } else {
424 $url = preg_replace("|^(.*)://|", "", $url);
425 // Collect filename and path
426 $from_all = explode("/", $url);
427 $from_filename = array_pop($from_all);
428 $from_pathname_array = array();
429 for ($i = 0; $i < $d->get_path_depth(); $i++) {
430 $from_pathname_array[] = array_pop($from_all);
432 $from_pathname_array = array_reverse($from_pathname_array);
433 $from_pathname = implode("/", $from_pathname_array);
434 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
436 if (!file_exists($temp_url)) {
437 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;
439 $url = $temp_url;
440 $pdetails = getPatientData($patient_id);
441 $pname = $pdetails['fname'] . " " . $pdetails['lname'];
442 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
443 if ($couch_docid && $couch_revid) {
444 // remove the temporary couchdb file
445 unlink($temp_couchdb_url);
448 $this->_state = false;
449 $_POST['process'] = "";
450 return $this->view_action($patient_id, $n->get_foreign_id());
453 public function default_action()
455 return $this->list_action();
458 public function view_action(string $patient_id = null, $doc_id)
460 global $ISSUE_TYPES;
462 require_once(dirname(__FILE__) . "/../library/lists.inc.php");
464 $d = new Document($doc_id);
465 $notes = $d->get_notes();
467 $this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
469 $this->assign("file", $d);
470 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
471 $this->assign("NOTE_ACTION", $this->_link("note"));
472 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
473 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
474 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
475 $this->assign("webroot", $GLOBALS['webroot']);
477 // Added by Rod to support document delete:
478 $delete_string = '';
479 if (AclMain::aclCheckCore('patients', 'docs_rm')) {
480 $delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
481 ")'>" . xlt('Delete') . "</a>";
483 $this->assign("delete_string", $delete_string);
484 $this->assign("REFRESH_ACTION", $this->_link("list"));
486 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
487 "document_id=" . $d->get_id() . "&process=true");
489 // Added by Rod to support document date update:
490 $this->assign("DOCDATE", $d->get_docdate());
491 $this->assign("UPDATE_ACTION", $this->_link("update") .
492 "document_id=" . $d->get_id() . "&process=true");
494 // Added by Rod to support document issue update:
495 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
496 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
497 "pid = ? " . // AND enddate IS NULL " .
498 "ORDER BY type, begdate", array($patient_id));
499 while ($irow = sqlFetchArray($ires)) {
500 $desc = $irow['type'];
501 if ($ISSUE_TYPES[$desc]) {
502 $desc = $ISSUE_TYPES[$desc][2];
504 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
505 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
506 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
508 $this->assign("ISSUES_LIST", $issues_options);
510 // For tagging to encounter
511 // Populate the dropdown with patient's encounter list
512 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
513 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
514 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
515 "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));
516 if (sqlNumRows($result_docs) > 0) {
517 while ($row_result_docs = sqlFetchArray($result_docs)) {
518 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
519 $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>";
522 $this->assign("ENC_LIST", $encOptions);
524 //clear encounter tag
525 if ($d->get_encounter_id() != 0) {
526 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
527 } else {
528 $this->assign('clear_encounter_tag', 'javascript:void(0)');
531 //Populate the dropdown with category list
532 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
533 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
534 while ($crow = sqlFetchArray($cres)) {
535 $catid = $crow['pc_catid'];
536 if ($catid < 9 && $catid != 5) {
537 continue; // Applying same logic as in new encounter page.
539 $visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
541 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
543 $this->assign("notes", $notes);
545 $this->assign("PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
546 // Populate the dropdown with procedure order list
547 $imgOptions = "<option value='0'>-- " . xlt('Select Procedure') . " --</option>";
548 $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));
549 $mapping = $this->get_mapped_procedure($d->get_id());
550 if (sqlNumRows($imgOrders) > 0) {
551 while ($row = sqlFetchArray($imgOrders)) {
552 $sel_proc = '';
553 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
554 $sel_proc = 'selected';
556 $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>";
560 $this->assign('TAG_PROCEDURE_LIST', $imgOptions);
562 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
564 $this->_last_node = null;
566 $menu = new HTML_TreeMenu();
568 //pass an empty array because we don't want the documents for each category showing up in this list box
569 $rnode = $this->array_recurse($this->tree->tree, $patient_id, array());
570 $menu->addItem($rnode);
571 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
573 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
575 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
576 $this->assign("activity", $activity);
578 return $this->list_action($patient_id);
582 * Retrieve file from hard disk / CouchDB.
583 * In case that file isn't download this public function will return thumbnail image (if exist).
584 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
585 * @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.
586 * */
587 public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
589 $encrypted = $_POST['encrypted'] ?? false;
590 $passphrase = $_POST['passphrase'] ?? '';
591 $doEncryption = false;
592 if (
593 !$GLOBALS['hide_document_encryption'] &&
594 $encrypted == "true" &&
595 $passphrase
597 $doEncryption = true;
600 //controller public function ruins booleans, so need to manually re-convert to booleans
601 if ($as_file == "true") {
602 $as_file = true;
603 } elseif ($as_file == "false") {
604 $as_file = false;
606 if ($original_file == "true") {
607 $original_file = true;
608 } elseif ($original_file == "false") {
609 $original_file = false;
611 if ($disable_exit == "true") {
612 $disable_exit = true;
613 } elseif ($disable_exit == "false") {
614 $disable_exit = false;
616 if ($show_original == "true") {
617 $show_original = true;
618 } elseif ($show_original == "false") {
619 $show_original = false;
622 switch ($context) {
623 case "patient_picture":
624 $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);
625 break;
628 $d = new Document($document_id);
630 // ensure user/patient has access
631 if (isset($_SESSION['patient_portal_onsite_two']) && isset($_SESSION['pid'])) {
632 // ensure patient has access (called from patient portal)
633 if (!$d->can_patient_access($_SESSION['pid'])) {
634 (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]);
635 die(xlt("Not authorized to view requested file"));
637 } else {
638 // ensure user has access
639 if (!$d->can_access()) {
640 (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]);
641 die(xlt("Not authorized to view requested file"));
645 $url = $d->get_url();
646 $th_url = $d->get_thumb_url();
648 $storagemethod = $d->get_storagemethod();
649 $couch_docid = $d->get_couch_docid();
650 $couch_revid = $d->get_couch_revid();
652 if ($couch_docid && $couch_revid && $original_file) {
653 // standard case for collecting a document from couchdb
654 $couch = new CouchDB();
655 $resp = $couch->retrieve_doc($couch_docid);
656 //Take thumbnail file when is not null and file is presented online
657 if (!$as_file && !is_null($th_url) && !$show_original) {
658 $content = $resp->th_data;
659 } else {
660 $content = $resp->data;
662 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
663 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
664 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
665 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
666 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
667 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
668 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
669 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
670 die(xlt("File retrieval from CouchDB failed"));
672 if ($d->get_encrypted() == 1) {
673 $filetext = $this->cryptoGen->decryptStandard($content, null, 'database');
674 } else {
675 $filetext = base64_decode($content);
677 if ($disable_exit == true) {
678 return $filetext;
680 header('Content-Description: File Transfer');
681 header('Content-Transfer-Encoding: binary');
682 header('Expires: 0');
683 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
684 header('Pragma: public');
685 if ($doEncryption) {
686 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
687 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
688 header("Content-Type: application/octet-stream");
689 header("Content-Length: " . strlen($ciphertext));
690 echo $ciphertext;
691 } else {
692 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
693 header("Content-Type: " . $d->get_mimetype());
694 header("Content-Length: " . strlen($filetext));
695 echo $filetext;
697 exit;//exits only if file download from CouchDB is successfull.
699 if ($couch_docid && $couch_revid) {
700 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
701 //try to convert it if it has not yet been converted
702 //first, see if the converted jpg already exists
703 $couch = new CouchDB();
704 $resp = $couch->retrieve_doc("converted_" . $couch_docid);
705 $content = $resp->data;
706 if ($content == '') {
707 //create the converted jpg
708 $couchM = new CouchDB();
709 $respM = $couchM->retrieve_doc($couch_docid);
710 if ($d->get_encrypted() == 1) {
711 $contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');
712 } else {
713 $contentM = base64_decode($respM->data);
715 if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
716 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
717 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
718 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
719 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
720 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
721 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
722 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
723 die(xlt("File retrieval from CouchDB failed"));
725 // place the from-file into a temporary file
726 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
727 file_put_contents($from_file_tmp_name, $contentM);
728 // prepare a temporary file for the to-file
729 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
730 $to_file_tmp_name = $to_file_tmp . ".jpg";
731 // convert file to jpg
732 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
733 // remove from tmp file
734 unlink($from_file_tmp_name);
735 // save the to-file if a to-file was created in above convert call
736 if (is_file($to_file_tmp_name)) {
737 $couchI = new CouchDB();
738 if ($d->get_encrypted() == 1) {
739 $document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
740 } else {
741 $document = base64_encode(file_get_contents($to_file_tmp_name));
743 $couchI->save_doc(['_id' => "converted_" . $couch_docid, 'data' => $document]);
744 // remove to tmp files
745 unlink($to_file_tmp);
746 unlink($to_file_tmp_name);
747 } else {
748 error_log("ERROR: Document '" . errorLogEscape($d->get_name()) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
750 // now collect the newly created converted jpg
751 $couchF = new CouchDB();
752 $respF = $couchF->retrieve_doc("converted_" . $couch_docid);
753 if ($d->get_encrypted() == 1) {
754 $content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');
755 } else {
756 $content = base64_decode($respF->data);
758 } else {
759 // decrypt/decode when converted jpg already exists
760 if ($d->get_encrypted() == 1) {
761 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
762 } else {
763 $content = base64_decode($resp->data);
766 $filetext = $content;
767 if ($disable_exit == true) {
768 return $filetext;
770 header("Pragma: public");
771 header("Expires: 0");
772 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
773 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
774 header("Content-Type: image/jpeg");
775 header("Content-Length: " . strlen($filetext));
776 echo $filetext;
777 exit;
780 //Take thumbnail file when is not null and file is presented online
781 if (!$as_file && !is_null($th_url) && !$show_original) {
782 $url = $th_url;
785 //strip url of protocol handler
786 $url = preg_replace("|^(.*)://|", "", $url);
788 //change full path to current webroot. this is for documents that may have
789 //been moved from a different filesystem and the full path in the database
790 //is not current. this is also for documents that may of been moved to
791 //different patients. Note that the path_depth is used to see how far down
792 //the path to go. For example, originally the path_depth was always 1, which
793 //only allowed things like documents/1/<file>, but now can have more structured
794 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
795 // etc.
796 // NOTE that $from_filename and basename($url) are the same thing
797 $from_all = explode("/", $url);
798 $from_filename = array_pop($from_all);
799 $from_pathname_array = array();
800 for ($i = 0; $i < $d->get_path_depth(); $i++) {
801 $from_pathname_array[] = array_pop($from_all);
803 $from_pathname_array = array_reverse($from_pathname_array);
804 $from_pathname = implode("/", $from_pathname_array);
805 if ($couch_docid && $couch_revid) {
806 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
807 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
808 } else {
809 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
812 if (file_exists($temp_url)) {
813 $url = $temp_url;
816 if (!file_exists($url)) {
817 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;
818 } else {
819 if ($original_file) {
820 //normal case when serving the file referenced in database
821 if ($d->get_encrypted() == 1) {
822 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
823 } else {
824 if (!is_dir($url)) {
825 $filetext = file_get_contents($url);
828 if ($disable_exit == true) {
829 return $filetext ?? '';
831 header('Content-Description: File Transfer');
832 header('Content-Transfer-Encoding: binary');
833 header('Expires: 0');
834 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
835 header('Pragma: public');
836 if ($doEncryption) {
837 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
838 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
839 header("Content-Type: application/octet-stream");
840 header("Content-Length: " . strlen($ciphertext));
841 echo $ciphertext;
842 } else {
843 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
844 header("Content-Type: " . $d->get_mimetype());
845 header("Content-Length: " . strlen($filetext ?? ''));
846 echo $filetext ?? '';
848 exit;
849 } else {
850 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
851 //try to convert it if it has not yet been converted
852 $originalUrl = $url;
853 if (strrpos(basename_international($url), '.') === false) {
854 $convertedFile = basename_international($url) . '_converted.jpg';
855 } else {
856 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
858 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
859 if (!is_file($url)) {
860 if ($d->get_encrypted() == 1) {
861 // decrypt the from-file into a temporary file
862 $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
863 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
864 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
865 // prepare a temporary file for the unencrypted to-file
866 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
867 $to_file_tmp_name = $to_file_tmp . ".jpg";
868 // convert file to jpg
869 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
870 // remove unencrypted tmp file
871 unlink($from_file_tmp_name);
872 // make the encrypted to-file if a to-file was created in above convert call
873 if (is_file($to_file_tmp_name)) {
874 $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
875 file_put_contents($url, $to_file_encrypted);
876 // remove unencrypted tmp files
877 unlink($to_file_tmp);
878 unlink($to_file_tmp_name);
880 } else {
881 // convert file to jpg
882 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
885 if (is_file($url)) {
886 if ($d->get_encrypted() == 1) {
887 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
888 } else {
889 $filetext = file_get_contents($url);
891 } else {
892 $filetext = '';
893 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
895 if ($disable_exit == true) {
896 return $filetext;
898 header("Pragma: public");
899 header("Expires: 0");
900 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
901 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
902 header("Content-Type: image/jpeg");
903 header("Content-Length: " . strlen($filetext));
904 echo $filetext;
905 exit;
910 public function move_action_process(string $patient_id = null, $document_id)
912 if ($_POST['process'] != "true") {
913 return;
916 $messages = '';
918 $new_category_id = $_POST['new_category_id'];
919 $new_patient_id = $_POST['new_patient_id'];
921 //move to new category
922 if (is_numeric($new_category_id) && is_numeric($document_id)) {
923 $sql = "UPDATE categories_to_documents set category_id = ? where document_id = ?";
924 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
925 //echo $sql;
926 $this->tree->_db->Execute($sql, [$new_category_id, $document_id]);
929 //move to new patient
930 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
931 $d = new Document($document_id);
932 $sql = "SELECT pid from patient_data where pid = ?";
933 $result = $d->_db->Execute($sql, [$new_patient_id]);
935 if (!$result || $result->EOF) {
936 //patient id does not exist
937 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
938 } else {
939 $changefailed = !$d->change_patient($new_patient_id);
941 $this->_state = false;
942 if (!$changefailed) {
943 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
944 } else {
945 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
947 $this->assign("messages", $messages);
948 return $this->list_action($patient_id);
952 $this->_state = false;
953 $this->assign("messages", $messages);
954 return $this->view_action($patient_id, $document_id);
957 public function validate_action_process(string $patient_id = null, $document_id)
960 $d = new Document($document_id);
961 if ($d->couch_docid && $d->couch_revid) {
962 $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
963 $url = $file_path . $d->get_url();
964 $couch = new CouchDB();
965 $resp = $couch->retrieve_doc($d->couch_docid);
966 if ($d->get_encrypted() == 1) {
967 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
968 } else {
969 $content = base64_decode($resp->data);
971 } else {
972 $url = $d->get_url();
974 //strip url of protocol handler
975 $url = preg_replace("|^(.*)://|", "", $url);
977 //change full path to current webroot. this is for documents that may have
978 //been moved from a different filesystem and the full path in the database
979 //is not current. this is also for documents that may of been moved to
980 //different patients. Note that the path_depth is used to see how far down
981 //the path to go. For example, originally the path_depth was always 1, which
982 //only allowed things like documents/1/<file>, but now can have more structured
983 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
984 // etc.
985 // NOTE that $from_filename and basename($url) are the same thing
986 $from_all = explode("/", $url);
987 $from_filename = array_pop($from_all);
988 $from_pathname_array = array();
989 for ($i = 0; $i < $d->get_path_depth(); $i++) {
990 $from_pathname_array[] = array_pop($from_all);
992 $from_pathname_array = array_reverse($from_pathname_array);
993 $from_pathname = implode("/", $from_pathname_array);
994 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
995 if (file_exists($temp_url)) {
996 $url = $temp_url;
999 if ($_POST['process'] != "true") {
1000 die("process is '" . text($_POST['process']) . "', expected 'true'");
1001 return;
1004 if ($d->get_encrypted() == 1) {
1005 $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
1006 } else {
1007 $content = file_get_contents($url);
1011 if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {
1012 // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0
1013 $current_hash = sha1($content);
1014 } else {
1015 $current_hash = hash('sha3-512', $content);
1017 $messages = xl('Current Hash') . ": " . $current_hash . " | ";
1018 $messages .= xl('Stored Hash') . ": " . $d->get_hash();
1019 if ($d->get_hash() == '') {
1020 $d->hash = $current_hash;
1021 $d->persist();
1022 $d->populate();
1023 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
1024 } elseif ($current_hash != $d->get_hash()) {
1025 $messages .= xl('Hash does not match. Data integrity has been compromised.');
1026 } else {
1027 $messages = xl('Document passed integrity check.') . ' | ' . $messages;
1029 $this->_state = false;
1030 $this->assign("messages", $messages);
1031 return $this->view_action($patient_id, $document_id);
1034 // Added by Rod for metadata update.
1036 public function update_action_process(string $patient_id = null, $document_id)
1039 if ($_POST['process'] != "true") {
1040 die("process is '" . $_POST['process'] . "', expected 'true'");
1041 return;
1044 $docdate = $_POST['docdate'];
1045 $docname = $_POST['docname'];
1046 $issue_id = $_POST['issue_id'];
1048 if (is_numeric($document_id)) {
1049 $messages = '';
1050 $d = new Document($document_id);
1051 $file_name = $d->get_name();
1052 if (
1053 $docname != '' &&
1054 $docname != $file_name
1056 // Rename
1057 $d->set_name($docname);
1058 $d->persist();
1059 $d->populate();
1060 $messages .= xl('Document successfully renamed.') . "<br />";
1063 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1064 $docdate = "$docdate";
1065 } else {
1066 $docdate = "NULL";
1068 if (!is_numeric($issue_id)) {
1069 $issue_id = 0;
1071 $couch_docid = $d->get_couch_docid();
1072 $couch_revid = $d->get_couch_revid();
1073 if ($couch_docid && $couch_revid) {
1074 $sql = "UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?";
1075 $this->tree->_db->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);
1076 } else {
1077 $sql = "UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?";
1078 $this->tree->_db->Execute($sql, [$docdate, $issue_id, $document_id]);
1080 $messages .= xl('Document date and issue updated successfully') . "<br />";
1083 $this->_state = false;
1084 $this->assign("messages", $messages);
1085 return $this->view_action($patient_id, $document_id);
1088 public function list_action($patient_id = "")
1090 $this->_last_node = null;
1091 $categories_list = $this->tree->_get_categories_array($patient_id);
1092 //print_r($categories_list);
1094 $menu = new HTML_TreeMenu();
1095 $rnode = $this->array_recurse($this->tree->tree, $patient_id, $categories_list);
1096 $menu->addItem($rnode);
1097 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1098 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1099 $this->assign("tree_html", $treeMenu->toHTML());
1101 $is_new = isset($_GET['patient_name']) ? 1 : false;
1102 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1103 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1104 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1105 if ($cur_pid == '00') {
1106 if (!AclMain::aclCheckCore('patients', 'docs', '', ['write', 'addonly'])) {
1107 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1108 exit;
1110 $cur_pid = '0';
1111 $is_new = 1;
1113 if (!AclMain::aclCheckCore('patients', 'docs')) {
1114 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1115 exit;
1117 $this->assign('is_new', $is_new);
1118 $this->assign('place_hld', $place_hld);
1119 $this->assign('cur_pid', $cur_pid);
1120 $this->assign('used_msg', $used_msg);
1121 $this->assign('demo_pid', ($_SESSION['pid'] ?? null));
1123 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1126 public function &array_recurse($array, $patient_id, $categories = array())
1128 if (!is_array($array)) {
1129 $array = array();
1131 $node = &$this->_last_node;
1132 $current_node = &$node;
1133 $expandedIcon = 'folder-expanded.gif';
1134 foreach ($array as $id => $ar) {
1135 $icon = 'folder.gif';
1136 if (is_array($ar) || !empty($id)) {
1137 if ($node == null) {
1138 //echo "r:" . $this->tree->get_node_name($id) . "<br />";
1139 $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));
1140 $this->_last_node = &$rnode;
1141 $node = &$rnode;
1142 $current_node = &$rnode;
1143 } else {
1144 //echo "p:" . $this->tree->get_node_name($id) . "<br />";
1145 $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)));
1146 $current_node = &$this->_last_node;
1149 $this->array_recurse($ar, $patient_id, $categories);
1150 } else {
1151 if ($id === 0 && !empty($ar)) {
1152 $info = $this->tree->get_node_info($id);
1153 //echo "b:" . $this->tree->get_node_name($id) . "<br />";
1154 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1155 } else {
1156 //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
1157 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1158 if ($id !== 0 && is_object($node)) {
1159 //echo "n:" . $this->tree->get_node_name($id) . "<br />";
1160 $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)));
1165 // If there are documents in this document category, then add their
1166 // attributes to the current node.
1167 $icon = "file3.png";
1168 if (!empty($categories[$id]) && is_array($categories[$id])) {
1169 foreach ($categories[$id] as $doc) {
1170 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1171 // If user has no access then there will be no link.
1172 if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {
1173 $link = '';
1175 // CCD view
1176 $nodeInfo = $this->tree->get_node_info($id);
1177 $treeViewFilterEvent = new PatientDocumentTreeViewFilterEvent();
1178 $treeViewFilterEvent->setCategoryTreeNode($this->tree);
1179 $treeViewFilterEvent->setDocumentId($doc['document_id']);
1180 $treeViewFilterEvent->setDocumentName($doc['document_name']);
1181 $treeViewFilterEvent->setCategoryId($id);
1182 $treeViewFilterEvent->setCategoryInfo($nodeInfo);
1183 $treeViewFilterEvent->setPid($patient_id);
1185 $htmlNode = new HTML_TreeNode(array(
1186 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1187 'link' => $link,
1188 'icon' => $icon,
1189 'expandedIcon' => $expandedIcon
1192 $treeViewFilterEvent->setHtmlTreeNode($htmlNode);
1193 $filteredEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch($treeViewFilterEvent, PatientDocumentTreeViewFilterEvent::EVENT_NAME);
1194 if ($filteredEvent->getHtmlTreeNode() != null) {
1195 $current_node->addItem($filteredEvent->getHtmlTreeNode());
1196 } else {
1197 // add the original node if we got back nothing from the server
1198 $current_node->addItem($htmlNode);
1203 return $node;
1206 //public function for logging the errors in writing file to CouchDB/Hard Disk
1207 public function document_upload_download_log($patientid, $content)
1209 $log_path = $GLOBALS['OE_SITE_DIR'] . "/documents/couchdb/";
1210 $log_file = 'log.txt';
1211 if (!is_dir($log_path)) {
1212 mkdir($log_path, 0777, true);
1215 $LOG = file_get_contents($log_path . $log_file);
1217 if ($this->cryptoGen->cryptCheckStandard($LOG)) {
1218 $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');
1221 $LOG .= $content;
1223 if (!empty($LOG)) {
1224 if ($GLOBALS['drive_encryption']) {
1225 $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');
1227 file_put_contents($log_path . $log_file, $LOG);
1231 public function document_send($email, $body, $attfile, $pname)
1233 if (empty($email)) {
1234 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1235 return;
1238 $desc = "Please check the attached patient document.\n Content:" . $body;
1239 $mail = new MyMailer();
1240 $from_name = $GLOBALS["practice_return_email_path"];
1241 $from = $GLOBALS["practice_return_email_path"];
1242 $mail->AddReplyTo($from, $from_name);
1243 $mail->SetFrom($from, $from);
1244 $to = $email ;
1245 $to_name = $email;
1246 $mail->AddAddress($to, $to_name);
1247 $subject = "Patient documents";
1248 $mail->Subject = $subject;
1249 $mail->Body = $desc;
1250 $mail->AddAttachment($attfile);
1251 if ($mail->Send()) {
1252 $retstatus = "email_sent";
1253 } else {
1254 $email_status = $mail->ErrorInfo;
1255 //echo "EMAIL ERROR: ".$email_status;
1256 $retstatus = "email_fail";
1260 //place to hold optional code
1261 //$first_node = array_keys($t->tree);
1262 //$first_node = $first_node[0];
1263 //$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')"));
1265 //$this->_last_node = &$node1;
1267 // public function to tag a document to an encounter.
1268 public function tag_action_process(string $patient_id = null, $document_id)
1270 if ($_POST['process'] != "true") {
1271 die("process is '" . text($_POST['process']) . "', expected 'true'");
1272 return;
1275 // Create Encounter and Tag it.
1276 $event_date = date('Y-m-d H:i:s');
1277 $encounter_id = $_POST['encounter_id'];
1278 $encounter_check = $_POST['encounter_check'];
1279 $visit_category_id = $_POST['visit_category_id'];
1281 if (is_numeric($document_id)) {
1282 $messages = '';
1283 $d = new Document($document_id);
1284 $file_name = $d->get_url_file();
1285 if (!is_numeric($encounter_id)) {
1286 $encounter_id = 0;
1289 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1290 if ($encounter_check) {
1291 $provider_id = $_SESSION['authUserID'] ;
1293 // Get the logged in user's facility
1294 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1295 $username = $facilityRow['username'];
1296 $facility = $facilityRow['facility'];
1297 $facility_id = $facilityRow['facility_id'];
1298 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1299 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1300 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1302 $conn = $GLOBALS['adodb']['db'];
1303 $encounter = $conn->GenID("sequences");
1304 $query = "INSERT INTO form_encounter SET
1305 date = ?,
1306 reason = ?,
1307 facility = ?,
1308 sensitivity = 'normal',
1309 pc_catid = ?,
1310 facility_id = ?,
1311 billing_facility = ?,
1312 provider_id = ?,
1313 pid = ?,
1314 encounter = ?";
1315 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1316 $formID = sqlInsert($query, $bindArray);
1317 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1318 $d->set_encounter_id($encounter);
1319 $this->image_result_indication($d->id, $encounter);
1320 } else {
1321 $d->set_encounter_id($encounter_id);
1322 $this->image_result_indication($d->id, $encounter_id);
1324 $d->set_encounter_check($encounter_check);
1325 $d->persist();
1327 $messages .= xlt('Document tagged to Encounter successfully') . "<br />";
1330 $this->_state = false;
1331 $this->assign("messages", $messages);
1333 return $this->view_action($patient_id, $document_id);
1336 public function image_procedure_action(string $patient_id = null, $document_id)
1339 $img_procedure_id = $_POST['image_procedure_id'];
1340 $proc_code = $_POST['procedure_code'];
1342 if (is_numeric($document_id)) {
1343 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1344 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1345 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1346 if ($img_report_id == 0) {
1347 $report_date = date('Y-m-d H:i:s');
1348 $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));
1351 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1352 if (empty($img_result)) {
1353 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));
1356 $this->image_result_indication($document_id, 0, $img_procedure_id);
1358 return $this->view_action($patient_id, $document_id);
1361 public function clear_procedure_tag_action(string $patient_id = null, $document_id)
1363 if (is_numeric($document_id)) {
1364 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1366 return $this->view_action($patient_id, $document_id);
1369 public function get_mapped_procedure($document_id)
1371 $map = array();
1372 if (is_numeric($document_id)) {
1373 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1374 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1375 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1376 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1377 where pres.document_id = ?", array($document_id));
1379 return $map;
1382 public function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1384 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1385 $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';
1387 // TODO: This should be moved into a service so we can handle things such as uuid generation....
1388 if ($encounter != 0) {
1389 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1390 } elseif ($image_procedure_id != 0) {
1391 $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));
1392 } else {
1393 $ep = array('assigned_to' => $_SESSION['authUser']);
1396 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1397 $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1398 setGpRelation(1, $doc_id, 6, $noteid);
1401 //clear encounter tag public function
1402 public function clear_encounter_tag_action(string $patient_id = null, $document_id)
1404 if (is_numeric($document_id)) {
1405 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1407 return $this->view_action($patient_id, $document_id);
1410 // this will set flag to skip acl check
1411 // this is needed for when uploading via services that piggyback on any user (ie. the background services) or via cron/cli
1412 public function skipAclCheck(): void
1414 $this->skip_acl_check = true;
1417 // this will check if flag has been set to skip the acl check
1418 // this is needed for when uploading via services that piggyback on any user (ie. the background services) or via cron/cli
1419 public function isSkipAclCheck(): bool
1421 return $this->skip_acl_check;