Fix to support use of the Social Screening Tool encounter form in the patient portal
[openemr.git] / controllers / C_Document.class.php
blob5eb1b72178d4eeed4de83422323cf1dea3ec2bdc
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");
14 require_once(__DIR__ . "/../library/patient.inc");
16 use OpenEMR\Common\Acl\AclMain;
17 use OpenEMR\Common\Crypto\CryptoGen;
18 use OpenEMR\Common\Csrf\CsrfUtils;
19 use OpenEMR\Common\Twig\TwigContainer;
20 use OpenEMR\Services\FacilityService;
21 use OpenEMR\Services\PatientService;
22 use OpenEMR\Events\PatientDocuments\PatientDocumentTreeViewFilterEvent;
24 class C_Document extends Controller
26 public $documents;
27 public $document_categories;
28 public $tree;
29 public $_config;
30 public $manual_set_owner = false; // allows manual setting of a document owner/service
31 public $facilityService;
32 public $patientService;
33 public $_last_node;
34 private $Document;
35 private $cryptoGen;
37 public function __construct($template_mod = "general")
39 parent::__construct();
40 $this->facilityService = new FacilityService();
41 $this->patientService = new PatientService();
42 $this->documents = array();
43 $this->template_mod = $template_mod;
44 $this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING'] ?? ''));
45 $this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
47 if (php_sapi_name() !== 'cli') {
48 // skip when this is being called via command line for the ccda importing
49 $this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
52 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
54 //get global config options for this namespace
55 $this->_config = $GLOBALS['oer_config']['documents'];
57 $this->_args = array("patient_id" => ($_GET['patient_id'] ?? null));
59 $this->assign("STYLE", $GLOBALS['style']);
60 $t = new CategoryTree(1);
61 //print_r($t->tree);
62 $this->tree = $t;
63 $this->Document = new Document();
65 // Create a crypto object that will be used for for encryption/decryption
66 $this->cryptoGen = new CryptoGen();
69 public function upload_action($patient_id, $category_id)
71 $category_name = $this->tree->get_node_name($category_id);
72 $this->assign("category_id", $category_id);
73 $this->assign("category_name", $category_name);
74 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
75 $this->assign("patient_id", $patient_id);
77 // Added by Rod to support document template download from general_upload.html.
78 // Cloned from similar stuff in manage_document_templates.php.
79 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
80 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
81 if (file_exists($templatedir)) {
82 $dh = opendir($templatedir);
84 if (!empty($dh)) {
85 $templateslist = array();
86 while (false !== ($sfname = readdir($dh))) {
87 if (substr($sfname, 0, 1) == '.') {
88 continue;
90 $templateslist[$sfname] = $sfname;
92 closedir($dh);
93 ksort($templateslist);
94 foreach ($templateslist as $sfname) {
95 $templates_options .= "<option value='" . attr($sfname) .
96 "'>" . text($sfname) . "</option>";
99 $this->assign("TEMPLATES_LIST", $templates_options);
101 // duplicate template list for new template form editor sjp 05/20/2019
102 // will call as module or individual template.
103 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';
104 $templates_options = "<option value=''>-- " . xlt('Open Forms Module') . " --</option>";
105 if (file_exists($templatedir)) {
106 $dh = opendir($templatedir);
108 if ($dh) {
109 $templateslist = array();
110 while (false !== ($sfname = readdir($dh))) {
111 if (substr($sfname, 0, 1) == '.') {
112 continue;
114 if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {
115 $templateslist[$sfname] = $sfname;
118 closedir($dh);
119 ksort($templateslist);
120 foreach ($templateslist as $sfname) {
121 $optname = str_replace('_', ' ', basename($sfname, ".tpl"));
122 $templates_options .= "<option value='" . attr($sfname) . "'>" . text($optname) . "</option>";
125 $this->assign("TEMPLATES_LIST_PATIENT", $templates_options);
127 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
128 $this->assign("activity", $activity);
129 return $this->list_action($patient_id);
132 public function zip_dicom_folder($study_name = null)
134 $zip = new ZipArchive();
135 $zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
136 if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {
137 foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
138 $zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
139 $fparts = pathinfo($name);
140 if (empty($fparts['extension'])) {
141 // viewer requires lowercase.
142 $fparts['extension'] = "dcm";
143 $name = $fparts['filename'] . ".dcm";
145 if ($fparts['extension'] == "DCM") {
146 // viewer requires lowercase.
147 $fparts['extension'] = "dcm";
148 $name = $fparts['filename'] . ".dcm";
150 // required extension for viewer
151 if ($fparts['extension'] != "dcm") {
152 continue;
154 move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
155 $zip->addFile($zfn, $name);
157 $zip->close();
158 } else {
159 return false;
161 $file_array['name'][] = $study_name;
162 $file_array['type'][] = 'zip';
163 $file_array['tmp_name'][] = $zip_name;
164 $file_array['error'][] = '';
165 $file_array['size'][] = filesize($zip_name);
166 return $file_array;
169 //Upload multiple files on single click
170 public function upload_action_process()
173 // Collect a manually set owner if this has been set
174 // Used when want to manually assign the owning user/service such as the Direct mechanism
175 $non_HTTP_owner = false;
176 if ($this->manual_set_owner) {
177 $non_HTTP_owner = $this->manual_set_owner;
180 $couchDB = false;
181 $harddisk = false;
182 if ($GLOBALS['document_storage_method'] == 0) {
183 $harddisk = true;
185 if ($GLOBALS['document_storage_method'] == 1) {
186 $couchDB = true;
189 if ($_POST['process'] != "true") {
190 return;
193 $doDecryption = false;
194 $encrypted = $_POST['encrypted'] ?? false;
195 $passphrase = $_POST['passphrase'] ?? '';
196 if (
197 !$GLOBALS['hide_document_encryption'] &&
198 $encrypted && $passphrase
200 $doDecryption = true;
203 if (is_numeric($_POST['category_id'])) {
204 $category_id = $_POST['category_id'];
207 $patient_id = 0;
208 if (isset($_GET['patient_id']) && !$couchDB) {
209 $patient_id = $_GET['patient_id'];
210 } elseif (is_numeric($_POST['patient_id'])) {
211 $patient_id = $_POST['patient_id'];
214 if (!empty($_FILES['dicom_folder']['name'][0])) {
215 // let's zip um up then pass along new zip
216 $study_name = $_POST['destination'] ? (trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
217 $study_name = preg_replace('/\s+/', '_', $study_name);
218 $_POST['destination'] = "";
219 $zipped = $this->zip_dicom_folder($study_name);
220 if ($zipped) {
221 $_FILES['file'] = $zipped;
223 // and off we go! just fall through and let routine
224 // do its normal file processing..
227 $sentUploadStatus = array();
228 if (count($_FILES['file']['name']) > 0) {
229 $upl_inc = 0;
231 foreach ($_FILES['file']['name'] as $key => $value) {
232 $fname = $value;
233 $error = "";
234 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
235 $fname = $value;
236 if (empty($fname)) {
237 $fname = htmlentities("<empty>");
239 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
240 if ($_FILES['file']['size'][$key] == 0) {
241 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
243 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
244 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
245 } else {
246 // Test for a zip of DICOM images
247 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
248 $za = new ZipArchive();
249 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
250 if ($handler) {
251 $mimetype = "application/dicom+zip";
252 for ($i = 0; $i < $za->numFiles; $i++) {
253 $stat = $za->statIndex($i);
254 $fp = $za->getStream($stat['name']);
255 if ($fp) {
256 $head = fread($fp, 256);
257 fclose($fp);
258 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
259 $mimetype = "application/zip";
260 break;
262 unset($head);
263 // if here -then a DICOM
264 $parts = pathinfo($stat['name']);
265 if ($parts['extension'] != "dcm" || empty($parts['extension'])) { // required extension for viewer
266 $new_name = $parts['filename'] . ".dcm";
267 $za->renameIndex($i, $new_name);
268 $za->renameName($parts['filename'], $new_name);
270 } else { // Rarely here
271 $mimetype = "application/zip";
272 break;
275 $za->close();
276 if ($mimetype == "application/dicom+zip") {
277 $_FILES['file']['type'][$key] = $mimetype;
278 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
279 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
283 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
284 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
285 fclose($tmpfile);
286 if ($doDecryption) {
287 $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
288 if ($filetext === false) {
289 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
290 $filetext = "";
293 if ($_POST['destination'] != '') {
294 $fname = $_POST['destination'];
296 // set mime, test for single DICOM and assign extension if missing.
297 $mimetype = $_FILES['file']['type'][$key];
298 if (strpos($filetext, 'DICM') !== false) {
299 $mimetype = 'application/dicom';
300 $parts = pathinfo($fname);
301 if (!$parts['extension']) {
302 $fname .= '.dcm';
305 $d = new Document();
306 $rc = $d->createDocument(
307 $patient_id,
308 $category_id,
309 $fname,
310 $mimetype,
311 $filetext,
312 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
313 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
314 $non_HTTP_owner,
315 $_FILES['file']['tmp_name'][$key]
317 if ($rc) {
318 $error .= $rc . "\n";
319 } else {
320 $this->assign("upload_success", "true");
322 $sentUploadStatus[] = $d;
323 $this->assign("file", $sentUploadStatus);
326 // Option to run a custom plugin for each file upload.
327 // This was initially created to delete the original source file in a custom setting.
328 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
329 if (file_exists($upload_plugin)) {
330 include_once($upload_plugin);
332 $upload_plugin_pp = 'documentUploadPostProcess';
333 if (function_exists($upload_plugin_pp)) {
334 $tmp = call_user_func($upload_plugin_pp, $value, $d);
335 if ($tmp) {
336 $error = $tmp;
339 // Following is just an example of code in such a plugin file.
340 /*****************************************************
341 public function documentUploadPostProcess($filename, &$d) {
342 $userid = $_SESSION['authUserID'];
343 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
344 $owner = strtolower($row['username']);
345 $dn = '1_' . ucfirst($owner);
346 $filepath = "/shared_network_directory/$dn/$filename";
347 if (@unlink($filepath)) return '';
348 return "Failed to delete '$filepath'.";
350 *****************************************************/
354 $this->assign("error", $error);
355 //$this->_state = false;
356 $_POST['process'] = "";
357 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
360 public function note_action_process($patient_id)
362 // this public function is a dual public function that will set up a note associated with a document or send a document via email.
364 if ($_POST['process'] != "true") {
365 return;
368 $n = new Note();
369 $n->set_owner($_SESSION['authUserID']);
370 parent::populate_object($n);
371 if ($_POST['identifier'] == "no") {
372 // associate a note with a document
373 $n->persist();
374 } elseif ($_POST['identifier'] == "yes") {
375 // send the document via email
376 $d = new Document($_POST['foreign_id']);
377 $url = $d->get_url();
378 $storagemethod = $d->get_storagemethod();
379 $couch_docid = $d->get_couch_docid();
380 $couch_revid = $d->get_couch_revid();
381 if ($couch_docid && $couch_revid) {
382 $couch = new CouchDB();
383 $resp = $couch->retrieve_doc($couch_docid);
384 $content = $resp->data;
385 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
386 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
387 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
388 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
389 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
390 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
391 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
392 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
393 die(xlt("File retrieval from CouchDB failed"));
395 // place it in a temporary file and will remove the file below after emailed
396 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
397 $fh = fopen($temp_couchdb_url, "w");
398 fwrite($fh, base64_decode($content));
399 fclose($fh);
400 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
401 } else {
402 $url = preg_replace("|^(.*)://|", "", $url);
403 // Collect filename and path
404 $from_all = explode("/", $url);
405 $from_filename = array_pop($from_all);
406 $from_pathname_array = array();
407 for ($i = 0; $i < $d->get_path_depth(); $i++) {
408 $from_pathname_array[] = array_pop($from_all);
410 $from_pathname_array = array_reverse($from_pathname_array);
411 $from_pathname = implode("/", $from_pathname_array);
412 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
414 if (!file_exists($temp_url)) {
415 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;
417 $url = $temp_url;
418 $pdetails = getPatientData($patient_id);
419 $pname = $pdetails['fname'] . " " . $pdetails['lname'];
420 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
421 if ($couch_docid && $couch_revid) {
422 // remove the temporary couchdb file
423 unlink($temp_couchdb_url);
426 $this->_state = false;
427 $_POST['process'] = "";
428 return $this->view_action($patient_id, $n->get_foreign_id());
431 public function default_action()
433 return $this->list_action();
436 public function view_action(string $patient_id = null, $doc_id)
438 global $ISSUE_TYPES;
440 require_once(dirname(__FILE__) . "/../library/lists.inc");
442 $d = new Document($doc_id);
443 $notes = $d->get_notes();
445 $this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
447 $this->assign("file", $d);
448 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
449 $this->assign("NOTE_ACTION", $this->_link("note"));
450 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
451 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
452 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
453 $this->assign("webroot", $GLOBALS['webroot']);
455 // Added by Rod to support document delete:
456 $delete_string = '';
457 if (AclMain::aclCheckCore('patients', 'docs_rm')) {
458 $delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
459 ")'>" . xlt('Delete') . "</a>";
461 $this->assign("delete_string", $delete_string);
462 $this->assign("REFRESH_ACTION", $this->_link("list"));
464 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
465 "document_id=" . $d->get_id() . "&process=true");
467 // Added by Rod to support document date update:
468 $this->assign("DOCDATE", $d->get_docdate());
469 $this->assign("UPDATE_ACTION", $this->_link("update") .
470 "document_id=" . $d->get_id() . "&process=true");
472 // Added by Rod to support document issue update:
473 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
474 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
475 "pid = ? " . // AND enddate IS NULL " .
476 "ORDER BY type, begdate", array($patient_id));
477 while ($irow = sqlFetchArray($ires)) {
478 $desc = $irow['type'];
479 if ($ISSUE_TYPES[$desc]) {
480 $desc = $ISSUE_TYPES[$desc][2];
482 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
483 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
484 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
486 $this->assign("ISSUES_LIST", $issues_options);
488 // For tagging to encounter
489 // Populate the dropdown with patient's encounter list
490 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
491 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
492 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
493 "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));
494 if (sqlNumRows($result_docs) > 0) {
495 while ($row_result_docs = sqlFetchArray($result_docs)) {
496 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
497 $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>";
500 $this->assign("ENC_LIST", $encOptions);
502 //clear encounter tag
503 if ($d->get_encounter_id() != 0) {
504 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
505 } else {
506 $this->assign('clear_encounter_tag', 'javascript:void(0)');
509 //Populate the dropdown with category list
510 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
511 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
512 while ($crow = sqlFetchArray($cres)) {
513 $catid = $crow['pc_catid'];
514 if ($catid < 9 && $catid != 5) {
515 continue; // Applying same logic as in new encounter page.
517 $visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
519 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
521 $this->assign("notes", $notes);
523 $this->assign("PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
524 // Populate the dropdown with procedure order list
525 $imgOptions = "<option value='0'>-- " . xlt('Select Procedure') . " --</option>";
526 $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));
527 $mapping = $this->get_mapped_procedure($d->get_id());
528 if (sqlNumRows($imgOrders) > 0) {
529 while ($row = sqlFetchArray($imgOrders)) {
530 $sel_proc = '';
531 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
532 $sel_proc = 'selected';
534 $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>";
538 $this->assign('TAG_PROCEDURE_LIST', $imgOptions);
540 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
542 $this->_last_node = null;
544 $menu = new HTML_TreeMenu();
546 //pass an empty array because we don't want the documents for each category showing up in this list box
547 $rnode = $this->array_recurse($this->tree->tree, $patient_id, array());
548 $menu->addItem($rnode);
549 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
551 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
553 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
554 $this->assign("activity", $activity);
556 return $this->list_action($patient_id);
560 * Retrieve file from hard disk / CouchDB.
561 * In case that file isn't download this public function will return thumbnail image (if exist).
562 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
563 * @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.
564 * */
565 public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
567 $encrypted = $_POST['encrypted'] ?? false;
568 $passphrase = $_POST['passphrase'] ?? '';
569 $doEncryption = false;
570 if (
571 !$GLOBALS['hide_document_encryption'] &&
572 $encrypted == "true" &&
573 $passphrase
575 $doEncryption = true;
578 //controller public function ruins booleans, so need to manually re-convert to booleans
579 if ($as_file == "true") {
580 $as_file = true;
581 } elseif ($as_file == "false") {
582 $as_file = false;
584 if ($original_file == "true") {
585 $original_file = true;
586 } elseif ($original_file == "false") {
587 $original_file = false;
589 if ($disable_exit == "true") {
590 $disable_exit = true;
591 } elseif ($disable_exit == "false") {
592 $disable_exit = false;
594 if ($show_original == "true") {
595 $show_original = true;
596 } elseif ($show_original == "false") {
597 $show_original = false;
600 switch ($context) {
601 case "patient_picture":
602 $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);
603 break;
606 $d = new Document($document_id);
607 $url = $d->get_url();
608 $th_url = $d->get_thumb_url();
610 $storagemethod = $d->get_storagemethod();
611 $couch_docid = $d->get_couch_docid();
612 $couch_revid = $d->get_couch_revid();
614 if ($couch_docid && $couch_revid && $original_file) {
615 // standard case for collecting a document from couchdb
616 $couch = new CouchDB();
617 $resp = $couch->retrieve_doc($couch_docid);
618 //Take thumbnail file when is not null and file is presented online
619 if (!$as_file && !is_null($th_url) && !$show_original) {
620 $content = $resp->th_data;
621 } else {
622 $content = $resp->data;
624 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
625 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
626 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
627 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
628 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
629 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
630 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
631 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
632 die(xlt("File retrieval from CouchDB failed"));
634 if ($d->get_encrypted() == 1) {
635 $filetext = $this->cryptoGen->decryptStandard($content, null, 'database');
636 } else {
637 $filetext = base64_decode($content);
639 if ($disable_exit == true) {
640 return $filetext;
642 header('Content-Description: File Transfer');
643 header('Content-Transfer-Encoding: binary');
644 header('Expires: 0');
645 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
646 header('Pragma: public');
647 if ($doEncryption) {
648 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
649 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
650 header("Content-Type: application/octet-stream");
651 header("Content-Length: " . strlen($ciphertext));
652 echo $ciphertext;
653 } else {
654 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
655 header("Content-Type: " . $d->get_mimetype());
656 header("Content-Length: " . strlen($filetext));
657 echo $filetext;
659 exit;//exits only if file download from CouchDB is successfull.
661 if ($couch_docid && $couch_revid) {
662 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
663 //try to convert it if it has not yet been converted
664 //first, see if the converted jpg already exists
665 $couch = new CouchDB();
666 $resp = $couch->retrieve_doc("converted_" . $couch_docid);
667 $content = $resp->data;
668 if ($content == '') {
669 //create the converted jpg
670 $couchM = new CouchDB();
671 $respM = $couchM->retrieve_doc($couch_docid);
672 if ($d->get_encrypted() == 1) {
673 $contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');
674 } else {
675 $contentM = base64_decode($respM->data);
677 if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
678 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
679 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
680 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
681 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
682 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
683 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
684 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
685 die(xlt("File retrieval from CouchDB failed"));
687 // place the from-file into a temporary file
688 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
689 file_put_contents($from_file_tmp_name, $contentM);
690 // prepare a temporary file for the to-file
691 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
692 $to_file_tmp_name = $to_file_tmp . ".jpg";
693 // convert file to jpg
694 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
695 // remove from tmp file
696 unlink($from_file_tmp_name);
697 // save the to-file if a to-file was created in above convert call
698 if (is_file($to_file_tmp_name)) {
699 $couchI = new CouchDB();
700 if ($d->get_encrypted() == 1) {
701 $document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
702 } else {
703 $document = base64_encode(file_get_contents($to_file_tmp_name));
705 $couchI->save_doc(['_id' => "converted_" . $couch_docid, 'data' => $document]);
706 // remove to tmp files
707 unlink($to_file_tmp);
708 unlink($to_file_tmp_name);
709 } else {
710 error_log("ERROR: Document '" . errorLogEscape($d->get_name()) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
712 // now collect the newly created converted jpg
713 $couchF = new CouchDB();
714 $respF = $couchF->retrieve_doc("converted_" . $couch_docid);
715 if ($d->get_encrypted() == 1) {
716 $content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');
717 } else {
718 $content = base64_decode($respF->data);
720 } else {
721 // decrypt/decode when converted jpg already exists
722 if ($d->get_encrypted() == 1) {
723 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
724 } else {
725 $content = base64_decode($resp->data);
728 $filetext = $content;
729 if ($disable_exit == true) {
730 return $filetext;
732 header("Pragma: public");
733 header("Expires: 0");
734 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
735 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
736 header("Content-Type: image/jpeg");
737 header("Content-Length: " . strlen($filetext));
738 echo $filetext;
739 exit;
742 //Take thumbnail file when is not null and file is presented online
743 if (!$as_file && !is_null($th_url) && !$show_original) {
744 $url = $th_url;
747 //strip url of protocol handler
748 $url = preg_replace("|^(.*)://|", "", $url);
750 //change full path to current webroot. this is for documents that may have
751 //been moved from a different filesystem and the full path in the database
752 //is not current. this is also for documents that may of been moved to
753 //different patients. Note that the path_depth is used to see how far down
754 //the path to go. For example, originally the path_depth was always 1, which
755 //only allowed things like documents/1/<file>, but now can have more structured
756 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
757 // etc.
758 // NOTE that $from_filename and basename($url) are the same thing
759 $from_all = explode("/", $url);
760 $from_filename = array_pop($from_all);
761 $from_pathname_array = array();
762 for ($i = 0; $i < $d->get_path_depth(); $i++) {
763 $from_pathname_array[] = array_pop($from_all);
765 $from_pathname_array = array_reverse($from_pathname_array);
766 $from_pathname = implode("/", $from_pathname_array);
767 if ($couch_docid && $couch_revid) {
768 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
769 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
770 } else {
771 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
774 if (file_exists($temp_url)) {
775 $url = $temp_url;
778 if (!file_exists($url)) {
779 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;
780 } else {
781 if ($original_file) {
782 //normal case when serving the file referenced in database
783 if ($d->get_encrypted() == 1) {
784 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
785 } else {
786 if (!is_dir($url)) {
787 $filetext = file_get_contents($url);
790 if ($disable_exit == true) {
791 return $filetext ?? '';
793 header('Content-Description: File Transfer');
794 header('Content-Transfer-Encoding: binary');
795 header('Expires: 0');
796 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
797 header('Pragma: public');
798 if ($doEncryption) {
799 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
800 header('Content-Disposition: attachment; filename="' . "/encrypted_aes_" . $d->get_name() . '"');
801 header("Content-Type: application/octet-stream");
802 header("Content-Length: " . strlen($ciphertext));
803 echo $ciphertext;
804 } else {
805 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
806 header("Content-Type: " . $d->get_mimetype());
807 header("Content-Length: " . strlen($filetext ?? ''));
808 echo $filetext ?? '';
810 exit;
811 } else {
812 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
813 //try to convert it if it has not yet been converted
814 $originalUrl = $url;
815 if (strrpos(basename_international($url), '.') === false) {
816 $convertedFile = basename_international($url) . '_converted.jpg';
817 } else {
818 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
820 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
821 if (!is_file($url)) {
822 if ($d->get_encrypted() == 1) {
823 // decrypt the from-file into a temporary file
824 $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
825 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
826 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
827 // prepare a temporary file for the unencrypted to-file
828 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
829 $to_file_tmp_name = $to_file_tmp . ".jpg";
830 // convert file to jpg
831 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
832 // remove unencrypted tmp file
833 unlink($from_file_tmp_name);
834 // make the encrypted to-file if a to-file was created in above convert call
835 if (is_file($to_file_tmp_name)) {
836 $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
837 file_put_contents($url, $to_file_encrypted);
838 // remove unencrypted tmp files
839 unlink($to_file_tmp);
840 unlink($to_file_tmp_name);
842 } else {
843 // convert file to jpg
844 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
847 if (is_file($url)) {
848 if ($d->get_encrypted() == 1) {
849 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
850 } else {
851 $filetext = file_get_contents($url);
853 } else {
854 $filetext = '';
855 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
857 if ($disable_exit == true) {
858 return $filetext;
860 header("Pragma: public");
861 header("Expires: 0");
862 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
863 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . $d->get_name() . "\"");
864 header("Content-Type: image/jpeg");
865 header("Content-Length: " . strlen($filetext));
866 echo $filetext;
867 exit;
872 public function move_action_process(string $patient_id = null, $document_id)
874 if ($_POST['process'] != "true") {
875 return;
878 $messages = '';
880 $new_category_id = $_POST['new_category_id'];
881 $new_patient_id = $_POST['new_patient_id'];
883 //move to new category
884 if (is_numeric($new_category_id) && is_numeric($document_id)) {
885 $sql = "UPDATE categories_to_documents set category_id = ? where document_id = ?";
886 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
887 //echo $sql;
888 $this->tree->_db->Execute($sql, [$new_category_id, $document_id]);
891 //move to new patient
892 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
893 $d = new Document($document_id);
894 $sql = "SELECT pid from patient_data where pid = ?";
895 $result = $d->_db->Execute($sql, [$new_patient_id]);
897 if (!$result || $result->EOF) {
898 //patient id does not exist
899 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
900 } else {
901 $changefailed = !$d->change_patient($new_patient_id);
903 $this->_state = false;
904 if (!$changefailed) {
905 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
906 } else {
907 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
909 $this->assign("messages", $messages);
910 return $this->list_action($patient_id);
914 $this->_state = false;
915 $this->assign("messages", $messages);
916 return $this->view_action($patient_id, $document_id);
919 public function validate_action_process(string $patient_id = null, $document_id)
922 $d = new Document($document_id);
923 if ($d->couch_docid && $d->couch_revid) {
924 $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
925 $url = $file_path . $d->get_url();
926 $couch = new CouchDB();
927 $resp = $couch->retrieve_doc($d->couch_docid);
928 if ($d->get_encrypted() == 1) {
929 $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');
930 } else {
931 $content = base64_decode($resp->data);
933 } else {
934 $url = $d->get_url();
936 //strip url of protocol handler
937 $url = preg_replace("|^(.*)://|", "", $url);
939 //change full path to current webroot. this is for documents that may have
940 //been moved from a different filesystem and the full path in the database
941 //is not current. this is also for documents that may of been moved to
942 //different patients. Note that the path_depth is used to see how far down
943 //the path to go. For example, originally the path_depth was always 1, which
944 //only allowed things like documents/1/<file>, but now can have more structured
945 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
946 // etc.
947 // NOTE that $from_filename and basename($url) are the same thing
948 $from_all = explode("/", $url);
949 $from_filename = array_pop($from_all);
950 $from_pathname_array = array();
951 for ($i = 0; $i < $d->get_path_depth(); $i++) {
952 $from_pathname_array[] = array_pop($from_all);
954 $from_pathname_array = array_reverse($from_pathname_array);
955 $from_pathname = implode("/", $from_pathname_array);
956 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
957 if (file_exists($temp_url)) {
958 $url = $temp_url;
961 if ($_POST['process'] != "true") {
962 die("process is '" . text($_POST['process']) . "', expected 'true'");
963 return;
966 if ($d->get_encrypted() == 1) {
967 $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
968 } else {
969 $content = file_get_contents($url);
973 if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {
974 // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0
975 $current_hash = sha1($content);
976 } else {
977 $current_hash = hash('sha3-512', $content);
979 $messages = xl('Current Hash') . ": " . $current_hash . " | ";
980 $messages .= xl('Stored Hash') . ": " . $d->get_hash();
981 if ($d->get_hash() == '') {
982 $d->hash = $current_hash;
983 $d->persist();
984 $d->populate();
985 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
986 } elseif ($current_hash != $d->get_hash()) {
987 $messages .= xl('Hash does not match. Data integrity has been compromised.');
988 } else {
989 $messages = xl('Document passed integrity check.') . ' | ' . $messages;
991 $this->_state = false;
992 $this->assign("messages", $messages);
993 return $this->view_action($patient_id, $document_id);
996 // Added by Rod for metadata update.
998 public function update_action_process(string $patient_id = null, $document_id)
1001 if ($_POST['process'] != "true") {
1002 die("process is '" . $_POST['process'] . "', expected 'true'");
1003 return;
1006 $docdate = $_POST['docdate'];
1007 $docname = $_POST['docname'];
1008 $issue_id = $_POST['issue_id'];
1010 if (is_numeric($document_id)) {
1011 $messages = '';
1012 $d = new Document($document_id);
1013 $file_name = $d->get_name();
1014 if (
1015 $docname != '' &&
1016 $docname != $file_name
1018 // Rename
1019 $d->set_name($docname);
1020 $d->persist();
1021 $d->populate();
1022 $messages .= xl('Document successfully renamed.') . "<br />";
1025 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1026 $docdate = "$docdate";
1027 } else {
1028 $docdate = "NULL";
1030 if (!is_numeric($issue_id)) {
1031 $issue_id = 0;
1033 $couch_docid = $d->get_couch_docid();
1034 $couch_revid = $d->get_couch_revid();
1035 if ($couch_docid && $couch_revid) {
1036 $sql = "UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?";
1037 $this->tree->_db->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);
1038 } else {
1039 $sql = "UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?";
1040 $this->tree->_db->Execute($sql, [$docdate, $issue_id, $document_id]);
1042 $messages .= xl('Document date and issue updated successfully') . "<br />";
1045 $this->_state = false;
1046 $this->assign("messages", $messages);
1047 return $this->view_action($patient_id, $document_id);
1050 public function list_action($patient_id = "")
1052 $this->_last_node = null;
1053 $categories_list = $this->tree->_get_categories_array($patient_id);
1054 //print_r($categories_list);
1056 $menu = new HTML_TreeMenu();
1057 $rnode = $this->array_recurse($this->tree->tree, $patient_id, $categories_list);
1058 $menu->addItem($rnode);
1059 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1060 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1061 $this->assign("tree_html", $treeMenu->toHTML());
1063 $is_new = isset($_GET['patient_name']) ? 1 : false;
1064 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1065 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1066 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1067 if ($cur_pid == '00') {
1068 if (!AclMain::aclCheckCore('patients', 'docs', '', ['write', 'addonly'])) {
1069 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1070 exit;
1072 $cur_pid = '0';
1073 $is_new = 1;
1075 if (!AclMain::aclCheckCore('patients', 'docs')) {
1076 echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl("Documents")]);
1077 exit;
1079 $this->assign('is_new', $is_new);
1080 $this->assign('place_hld', $place_hld);
1081 $this->assign('cur_pid', $cur_pid);
1082 $this->assign('used_msg', $used_msg);
1083 $this->assign('demo_pid', ($_SESSION['pid'] ?? null));
1085 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1088 public function &array_recurse($array, $patient_id, $categories = array())
1090 if (!is_array($array)) {
1091 $array = array();
1093 $node = &$this->_last_node;
1094 $current_node = &$node;
1095 $expandedIcon = 'folder-expanded.gif';
1096 foreach ($array as $id => $ar) {
1097 $icon = 'folder.gif';
1098 if (is_array($ar) || !empty($id)) {
1099 if ($node == null) {
1100 //echo "r:" . $this->tree->get_node_name($id) . "<br />";
1101 $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));
1102 $this->_last_node = &$rnode;
1103 $node = &$rnode;
1104 $current_node = &$rnode;
1105 } else {
1106 //echo "p:" . $this->tree->get_node_name($id) . "<br />";
1107 $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)));
1108 $current_node = &$this->_last_node;
1111 $this->array_recurse($ar, $patient_id, $categories);
1112 } else {
1113 if ($id === 0 && !empty($ar)) {
1114 $info = $this->tree->get_node_info($id);
1115 //echo "b:" . $this->tree->get_node_name($id) . "<br />";
1116 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1117 } else {
1118 //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
1119 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1120 if ($id !== 0 && is_object($node)) {
1121 //echo "n:" . $this->tree->get_node_name($id) . "<br />";
1122 $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)));
1127 // If there are documents in this document category, then add their
1128 // attributes to the current node.
1129 $icon = "file3.png";
1130 if (!empty($categories[$id]) && is_array($categories[$id])) {
1131 foreach ($categories[$id] as $doc) {
1132 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1133 // If user has no access then there will be no link.
1134 if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {
1135 $link = '';
1137 // CCD view
1138 $nodeInfo = $this->tree->get_node_info($id);
1139 $treeViewFilterEvent = new PatientDocumentTreeViewFilterEvent();
1140 $treeViewFilterEvent->setCategoryTreeNode($this->tree);
1141 $treeViewFilterEvent->setDocumentId($doc['document_id']);
1142 $treeViewFilterEvent->setDocumentName($doc['document_name']);
1143 $treeViewFilterEvent->setCategoryId($id);
1144 $treeViewFilterEvent->setCategoryInfo($nodeInfo);
1145 $treeViewFilterEvent->setPid($patient_id);
1147 $htmlNode = new HTML_TreeNode(array(
1148 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],
1149 'link' => $link,
1150 'icon' => $icon,
1151 'expandedIcon' => $expandedIcon
1154 $treeViewFilterEvent->setHtmlTreeNode($htmlNode);
1155 $filteredEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch($treeViewFilterEvent, PatientDocumentTreeViewFilterEvent::EVENT_NAME);
1156 if ($filteredEvent->getHtmlTreeNode() != null) {
1157 $current_node->addItem($filteredEvent->getHtmlTreeNode());
1158 } else {
1159 // add the original node if we got back nothing from the server
1160 $current_node->addItem($htmlNode);
1165 return $node;
1168 //public function for logging the errors in writing file to CouchDB/Hard Disk
1169 public function document_upload_download_log($patientid, $content)
1171 $log_path = $GLOBALS['OE_SITE_DIR'] . "/documents/couchdb/";
1172 $log_file = 'log.txt';
1173 if (!is_dir($log_path)) {
1174 mkdir($log_path, 0777, true);
1177 $LOG = file_get_contents($log_path . $log_file);
1179 if ($this->cryptoGen->cryptCheckStandard($LOG)) {
1180 $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');
1183 $LOG .= $content;
1185 if (!empty($LOG)) {
1186 if ($GLOBALS['drive_encryption']) {
1187 $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');
1189 file_put_contents($log_path . $log_file, $LOG);
1193 public function document_send($email, $body, $attfile, $pname)
1195 if (empty($email)) {
1196 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1197 return;
1200 $desc = "Please check the attached patient document.\n Content:" . $body;
1201 $mail = new MyMailer();
1202 $from_name = $GLOBALS["practice_return_email_path"];
1203 $from = $GLOBALS["practice_return_email_path"];
1204 $mail->AddReplyTo($from, $from_name);
1205 $mail->SetFrom($from, $from);
1206 $to = $email ;
1207 $to_name = $email;
1208 $mail->AddAddress($to, $to_name);
1209 $subject = "Patient documents";
1210 $mail->Subject = $subject;
1211 $mail->Body = $desc;
1212 $mail->AddAttachment($attfile);
1213 if ($mail->Send()) {
1214 $retstatus = "email_sent";
1215 } else {
1216 $email_status = $mail->ErrorInfo;
1217 //echo "EMAIL ERROR: ".$email_status;
1218 $retstatus = "email_fail";
1222 //place to hold optional code
1223 //$first_node = array_keys($t->tree);
1224 //$first_node = $first_node[0];
1225 //$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')"));
1227 //$this->_last_node = &$node1;
1229 // public function to tag a document to an encounter.
1230 public function tag_action_process(string $patient_id = null, $document_id)
1232 if ($_POST['process'] != "true") {
1233 die("process is '" . text($_POST['process']) . "', expected 'true'");
1234 return;
1237 // Create Encounter and Tag it.
1238 $event_date = date('Y-m-d H:i:s');
1239 $encounter_id = $_POST['encounter_id'];
1240 $encounter_check = $_POST['encounter_check'];
1241 $visit_category_id = $_POST['visit_category_id'];
1243 if (is_numeric($document_id)) {
1244 $messages = '';
1245 $d = new Document($document_id);
1246 $file_name = $d->get_url_file();
1247 if (!is_numeric($encounter_id)) {
1248 $encounter_id = 0;
1251 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1252 if ($encounter_check) {
1253 $provider_id = $_SESSION['authUserID'] ;
1255 // Get the logged in user's facility
1256 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1257 $username = $facilityRow['username'];
1258 $facility = $facilityRow['facility'];
1259 $facility_id = $facilityRow['facility_id'];
1260 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1261 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1262 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1264 $conn = $GLOBALS['adodb']['db'];
1265 $encounter = $conn->GenID("sequences");
1266 $query = "INSERT INTO form_encounter SET
1267 date = ?,
1268 reason = ?,
1269 facility = ?,
1270 sensitivity = 'normal',
1271 pc_catid = ?,
1272 facility_id = ?,
1273 billing_facility = ?,
1274 provider_id = ?,
1275 pid = ?,
1276 encounter = ?";
1277 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1278 $formID = sqlInsert($query, $bindArray);
1279 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1280 $d->set_encounter_id($encounter);
1281 $this->image_result_indication($d->id, $encounter);
1282 } else {
1283 $d->set_encounter_id($encounter_id);
1284 $this->image_result_indication($d->id, $encounter_id);
1286 $d->set_encounter_check($encounter_check);
1287 $d->persist();
1289 $messages .= xlt('Document tagged to Encounter successfully') . "<br />";
1292 $this->_state = false;
1293 $this->assign("messages", $messages);
1295 return $this->view_action($patient_id, $document_id);
1298 public function image_procedure_action(string $patient_id = null, $document_id)
1301 $img_procedure_id = $_POST['image_procedure_id'];
1302 $proc_code = $_POST['procedure_code'];
1304 if (is_numeric($document_id)) {
1305 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1306 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1307 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1308 if ($img_report_id == 0) {
1309 $report_date = date('Y-m-d H:i:s');
1310 $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));
1313 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1314 if (empty($img_result)) {
1315 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));
1318 $this->image_result_indication($document_id, 0, $img_procedure_id);
1320 return $this->view_action($patient_id, $document_id);
1323 public function clear_procedure_tag_action(string $patient_id = null, $document_id)
1325 if (is_numeric($document_id)) {
1326 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1328 return $this->view_action($patient_id, $document_id);
1331 public function get_mapped_procedure($document_id)
1333 $map = array();
1334 if (is_numeric($document_id)) {
1335 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1336 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1337 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1338 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1339 where pres.document_id = ?", array($document_id));
1341 return $map;
1344 public function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1346 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1347 $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';
1349 // TODO: This should be moved into a service so we can handle things such as uuid generation....
1350 if ($encounter != 0) {
1351 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1352 } elseif ($image_procedure_id != 0) {
1353 $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));
1354 } else {
1355 $ep = array('assigned_to' => $_SESSION['authUser']);
1358 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1359 $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1360 setGpRelation(1, $doc_id, 6, $noteid);
1363 //clear encounter tag public function
1364 public function clear_encounter_tag_action(string $patient_id = null, $document_id)
1366 if (is_numeric($document_id)) {
1367 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1369 return $this->view_action($patient_id, $document_id);