Dicom viewer update (#3762)
[openemr.git] / controllers / C_Document.class.php
blob8e0239404a30da9916057179f81d5b66518758c2
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(dirname(__FILE__) . "/../library/forms.inc");
15 use OpenEMR\Common\Acl\AclMain;
16 use OpenEMR\Common\Crypto\CryptoGen;
17 use OpenEMR\Common\Csrf\CsrfUtils;
18 use OpenEMR\Services\FacilityService;
19 use OpenEMR\Services\PatientService;
21 class C_Document extends Controller
24 var $template_mod;
25 var $documents;
26 var $document_categories;
27 var $tree;
28 var $_config;
29 var $manual_set_owner = false; // allows manual setting of a document owner/service
30 var $facilityService;
31 var $patientService;
33 function __construct($template_mod = "general")
35 parent::__construct();
36 $this->facilityService = new FacilityService();
37 $this->patientService = new PatientService();
38 $this->documents = array();
39 $this->template_mod = $template_mod;
40 $this->assign("FORM_ACTION", $GLOBALS['webroot'] . "/controller.php?" . attr($_SERVER['QUERY_STRING']));
41 $this->assign("CURRENT_ACTION", $GLOBALS['webroot'] . "/controller.php?" . "document&");
43 $this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
45 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
47 //get global config options for this namespace
48 $this->_config = $GLOBALS['oer_config']['documents'];
50 $this->_args = array("patient_id" => $_GET['patient_id']);
52 $this->assign("STYLE", $GLOBALS['style']);
53 $t = new CategoryTree(1);
54 //print_r($t->tree);
55 $this->tree = $t;
56 $this->Document = new Document();
58 // Create a crypto object that will be used for for encryption/decryption
59 $this->cryptoGen = new CryptoGen();
62 function upload_action($patient_id, $category_id)
64 $category_name = $this->tree->get_node_name($category_id);
65 $this->assign("category_id", $category_id);
66 $this->assign("category_name", $category_name);
67 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
68 $this->assign("patient_id", $patient_id);
70 // Added by Rod to support document template download from general_upload.html.
71 // Cloned from similar stuff in manage_document_templates.php.
72 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
73 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
74 if (file_exists($templatedir)) {
75 $dh = opendir($templatedir);
77 if ($dh) {
78 $templateslist = array();
79 while (false !== ($sfname = readdir($dh))) {
80 if (substr($sfname, 0, 1) == '.') {
81 continue;
83 $templateslist[$sfname] = $sfname;
85 closedir($dh);
86 ksort($templateslist);
87 foreach ($templateslist as $sfname) {
88 $templates_options .= "<option value='" . attr($sfname) .
89 "'>" . text($sfname) . "</option>";
92 $this->assign("TEMPLATES_LIST", $templates_options);
94 // duplicate template list for new template form editor sjp 05/20/2019
95 // will call as module or individual template.
96 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';
97 $templates_options = "<option value=''>-- " . xlt('Open Forms Module') . " --</option>";
98 if (file_exists($templatedir)) {
99 $dh = opendir($templatedir);
101 if ($dh) {
102 $templateslist = array();
103 while (false !== ($sfname = readdir($dh))) {
104 if (substr($sfname, 0, 1) == '.') {
105 continue;
107 if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {
108 $templateslist[$sfname] = $sfname;
111 closedir($dh);
112 ksort($templateslist);
113 foreach ($templateslist as $sfname) {
114 $optname = str_replace('_', ' ', basename($sfname, ".tpl"));
115 $templates_options .= "<option value='" . attr($sfname) . "'>" . text($optname) . "</option>";
118 $this->assign("TEMPLATES_LIST_PATIENT", $templates_options);
120 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
121 $this->assign("activity", $activity);
122 return $this->list_action($patient_id);
125 function zip_dicom_folder($study_name = null)
127 $zip = new ZipArchive();
128 $zip_name = $GLOBALS['temporary_files_dir'] . "/" . $study_name;
129 if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {
130 foreach ($_FILES['dicom_folder']['name'] as $i => $name) {
131 $zfn = $GLOBALS['temporary_files_dir'] . "/" . $name;
132 $fparts = pathinfo($name);
133 if (empty($fparts['extension'])) {
134 // viewer requires lowercase.
135 $fparts['extension'] = "dcm";
136 $name = $fparts['filename'] . ".dcm";
138 if ($fparts['extension'] == "DCM") {
139 // viewer requires lowercase.
140 $fparts['extension'] = "dcm";
141 $name = $fparts['filename'] . ".dcm";
143 // required extension for viewer
144 if ($fparts['extension'] != "dcm") {
145 continue;
147 move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);
148 $zip->addFile($zfn, $name);
150 $zip->close();
151 } else {
152 return false;
154 $file_array['name'][] = $study_name;
155 $file_array['type'][] = 'zip';
156 $file_array['tmp_name'][] = $zip_name;
157 $file_array['error'][] = '';
158 $file_array['size'][] = filesize($zip_name);
159 return $file_array;
162 //Upload multiple files on single click
163 function upload_action_process()
166 // Collect a manually set owner if this has been set
167 // Used when want to manually assign the owning user/service such as the Direct mechanism
168 $non_HTTP_owner = false;
169 if ($this->manual_set_owner) {
170 $non_HTTP_owner = $this->manual_set_owner;
173 $couchDB = false;
174 $harddisk = false;
175 if ($GLOBALS['document_storage_method'] == 0) {
176 $harddisk = true;
178 if ($GLOBALS['document_storage_method'] == 1) {
179 $couchDB = true;
182 if ($_POST['process'] != "true") {
183 return;
186 $doDecryption = false;
187 $encrypted = $_POST['encrypted'];
188 $passphrase = $_POST['passphrase'];
189 if (
190 !$GLOBALS['hide_document_encryption'] &&
191 $encrypted && $passphrase
193 $doDecryption = true;
196 if (is_numeric($_POST['category_id'])) {
197 $category_id = $_POST['category_id'];
200 $patient_id = 0;
201 if (isset($_GET['patient_id']) && !$couchDB) {
202 $patient_id = $_GET['patient_id'];
203 } elseif (is_numeric($_POST['patient_id'])) {
204 $patient_id = $_POST['patient_id'];
207 if (!empty($_FILES['dicom_folder']['name'][0])) {
208 // let's zip um up then pass along new zip
209 $study_name = $_POST['destination'] ? (trim($_POST['destination']) . ".zip") : 'DicomStudy.zip';
210 $study_name = preg_replace('/\s+/', '_', $study_name);
211 $_POST['destination'] = "";
212 $zipped = $this->zip_dicom_folder($study_name);
213 if ($zipped) {
214 $_FILES['file'] = $zipped;
216 // and off we go! just fall through and let routine
217 // do its normal file processing..
220 $sentUploadStatus = array();
221 if (count($_FILES['file']['name']) > 0) {
222 $upl_inc = 0;
224 foreach ($_FILES['file']['name'] as $key => $value) {
225 $fname = $value;
226 $error = "";
227 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
228 $fname = $value;
229 if (empty($fname)) {
230 $fname = htmlentities("<empty>");
232 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
233 if ($_FILES['file']['size'][$key] == 0) {
234 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
236 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
237 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
238 } else {
239 // Test for a zip of DICOM images
240 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
241 $za = new ZipArchive();
242 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
243 if ($handler) {
244 $mimetype = "application/dicom+zip";
245 for ($i = 0; $i < $za->numFiles; $i++) {
246 $stat = $za->statIndex($i);
247 $fp = $za->getStream($stat['name']);
248 if ($fp) {
249 $head = fread($fp, 256);
250 fclose($fp);
251 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
252 $mimetype = "application/zip";
253 break;
255 unset($head);
256 // if here -then a DICOM
257 $parts = pathinfo($stat['name']);
258 if ($parts['extension'] != "dcm" || empty($parts['extension'])) { // required extension for viewer
259 $new_name = $parts['filename'] . ".dcm";
260 $za->renameIndex($i, $new_name);
261 $za->renameName($parts['filename'], $new_name);
263 } else { // Rarely here
264 $mimetype = "application/zip";
265 break;
268 $za->close();
269 if ($mimetype == "application/dicom+zip") {
270 $_FILES['file']['type'][$key] = $mimetype;
271 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
272 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
276 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
277 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
278 fclose($tmpfile);
279 if ($doDecryption) {
280 $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
281 if ($filetext === false) {
282 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
283 $filetext = "";
286 if ($_POST['destination'] != '') {
287 $fname = $_POST['destination'];
289 // set mime, test for single DICOM and assign extension if missing.
290 $mimetype = $_FILES['file']['type'][$key];
291 if (strpos($filetext, 'DICM') !== false) {
292 $mimetype = 'application/dicom';
293 $parts = pathinfo($fname);
294 if (!$parts['extension']) {
295 $fname .= '.dcm';
298 $d = new Document();
299 $rc = $d->createDocument(
300 $patient_id,
301 $category_id,
302 $fname,
303 $mimetype,
304 $filetext,
305 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
306 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
307 $non_HTTP_owner,
308 $_FILES['file']['tmp_name'][$key]
310 if ($rc) {
311 $error .= $rc . "\n";
312 } else {
313 $this->assign("upload_success", "true");
315 $sentUploadStatus[] = $d;
316 $this->assign("file", $sentUploadStatus);
319 // Option to run a custom plugin for each file upload.
320 // This was initially created to delete the original source file in a custom setting.
321 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
322 if (file_exists($upload_plugin)) {
323 include_once($upload_plugin);
325 $upload_plugin_pp = 'documentUploadPostProcess';
326 if (function_exists($upload_plugin_pp)) {
327 $tmp = call_user_func($upload_plugin_pp, $value, $d);
328 if ($tmp) {
329 $error = $tmp;
332 // Following is just an example of code in such a plugin file.
333 /*****************************************************
334 function documentUploadPostProcess($filename, &$d) {
335 $userid = $_SESSION['authUserID'];
336 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
337 $owner = strtolower($row['username']);
338 $dn = '1_' . ucfirst($owner);
339 $filepath = "/shared_network_directory/$dn/$filename";
340 if (@unlink($filepath)) return '';
341 return "Failed to delete '$filepath'.";
343 *****************************************************/
347 $this->assign("error", nl2br($error));
348 //$this->_state = false;
349 $_POST['process'] = "";
350 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
353 function note_action_process($patient_id)
355 // this function is a dual function that will set up a note associated with a document or send a document via email.
357 if ($_POST['process'] != "true") {
358 return;
361 $n = new Note();
362 $n->set_owner($_SESSION['authUserID']);
363 parent::populate_object($n);
364 if ($_POST['identifier'] == "no") {
365 // associate a note with a document
366 $n->persist();
367 } elseif ($_POST['identifier'] == "yes") {
368 // send the document via email
369 $d = new Document($_POST['foreign_id']);
370 $url = $d->get_url();
371 $storagemethod = $d->get_storagemethod();
372 $couch_docid = $d->get_couch_docid();
373 $couch_revid = $d->get_couch_revid();
374 if ($couch_docid && $couch_revid) {
375 $couch = new CouchDB();
376 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
377 $resp = $couch->retrieve_doc($data);
378 $content = $resp->data;
379 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
380 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
381 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
382 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
383 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
384 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
385 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
386 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
387 die(xlt("File retrieval from CouchDB failed"));
389 // place it in a temporary file and will remove the file below after emailed
390 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date("YmdHis") . $d->get_url_file();
391 $fh = fopen($temp_couchdb_url, "w");
392 fwrite($fh, base64_decode($content));
393 fclose($fh);
394 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
395 } else {
396 $url = preg_replace("|^(.*)://|", "", $url);
397 // Collect filename and path
398 $from_all = explode("/", $url);
399 $from_filename = array_pop($from_all);
400 $from_pathname_array = array();
401 for ($i = 0; $i < $d->get_path_depth(); $i++) {
402 $from_pathname_array[] = array_pop($from_all);
404 $from_pathname_array = array_reverse($from_pathname_array);
405 $from_pathname = implode("/", $from_pathname_array);
406 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
408 if (!file_exists($temp_url)) {
409 echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $temp_url;
411 $url = $temp_url;
412 $pdetails = getPatientData($patient_id);
413 $pname = $pdetails['fname'] . " " . $pdetails['lname'];
414 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
415 if ($couch_docid && $couch_revid) {
416 // remove the temporary couchdb file
417 unlink($temp_couchdb_url);
420 $this->_state = false;
421 $_POST['process'] = "";
422 return $this->view_action($patient_id, $n->get_foreign_id());
425 function default_action()
427 return $this->list_action();
430 function view_action(string $patient_id = null, $doc_id)
432 global $ISSUE_TYPES;
434 require_once(dirname(__FILE__) . "/../library/lists.inc");
436 $d = new Document($doc_id);
437 $notes = $d->get_notes();
439 $this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
441 $this->assign("file", $d);
442 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
443 $this->assign("NOTE_ACTION", $this->_link("note"));
444 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
445 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
446 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
447 $this->assign("webroot", $GLOBALS['webroot']);
449 // Added by Rod to support document delete:
450 $delete_string = '';
451 if (AclMain::aclCheckCore('patients', 'docs_rm')) {
452 $delete_string = "<a href='' class='btn btn-danger' onclick='return deleteme(" . attr_js($d->get_id()) .
453 ")'>" . xlt('Delete') . "</a>";
455 $this->assign("delete_string", $delete_string);
456 $this->assign("REFRESH_ACTION", $this->_link("list"));
458 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
459 "document_id=" . $d->get_id() . "&process=true");
461 // Added by Rod to support document date update:
462 $this->assign("DOCDATE", $d->get_docdate());
463 $this->assign("UPDATE_ACTION", $this->_link("update") .
464 "document_id=" . $d->get_id() . "&process=true");
466 // Added by Rod to support document issue update:
467 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
468 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
469 "pid = ? " . // AND enddate IS NULL " .
470 "ORDER BY type, begdate", array($patient_id));
471 while ($irow = sqlFetchArray($ires)) {
472 $desc = $irow['type'];
473 if ($ISSUE_TYPES[$desc]) {
474 $desc = $ISSUE_TYPES[$desc][2];
476 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
477 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
478 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
480 $this->assign("ISSUES_LIST", $issues_options);
482 // For tagging to encounter
483 // Populate the dropdown with patient's encounter list
484 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
485 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
486 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
487 "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));
488 if (sqlNumRows($result_docs) > 0) {
489 while ($row_result_docs = sqlFetchArray($result_docs)) {
490 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
491 $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>";
494 $this->assign("ENC_LIST", $encOptions);
496 //clear encounter tag
497 if ($d->get_encounter_id() != 0) {
498 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . "document_id=" . urlencode($d->get_id()));
499 } else {
500 $this->assign('clear_encounter_tag', 'javascript:void(0)');
503 //Populate the dropdown with category list
504 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
505 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
506 while ($crow = sqlFetchArray($cres)) {
507 $catid = $crow['pc_catid'];
508 if ($catid < 9 && $catid != 5) {
509 continue; // Applying same logic as in new encounter page.
511 $visit_category_list .= "<option value='" . attr($catid) . "'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
513 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
515 $this->assign("notes", $notes);
517 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
518 // Populate the dropdown with image procedure order list
519 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
520 $imgOrders = sqlStatement("select procedure_name,po.procedure_order_id,procedure_code from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ? and poc.procedure_order_title = 'imaging'", array($patient_id));
521 $mapping = $this->get_mapped_procedure($d->get_id());
522 if (sqlNumRows($imgOrders) > 0) {
523 while ($row = sqlFetchArray($imgOrders)) {
524 $sel_proc = '';
525 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
526 $sel_proc = 'selected';
528 $imgOptions .= "<option value='" . attr($row['procedure_order_id']) . "' data-code='" . attr($row['procedure_code']) . "' $sel_proc>" . text($row['procedure_name'] . ' - ' . $row['procedure_code']) . "</option>";
532 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
534 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . "document_id=" . urlencode($d->get_id()));
536 $this->_last_node = null;
538 $menu = new HTML_TreeMenu();
540 //pass an empty array because we don't want the documents for each category showing up in this list box
541 $rnode = $this->_array_recurse($this->tree->tree, array());
542 $menu->addItem($rnode);
543 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
545 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
547 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
548 $this->assign("activity", $activity);
550 return $this->list_action($patient_id);
554 * Retrieve file from hard disk / CouchDB.
555 * In case that file isn't download this function will return thumbnail image (if exist).
556 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
557 * @param (string) $context - given a special document scenario (e.g.: patient avatar, custom image viewer document, etc), the context can be set so that a switch statement can execute a custom strategy.
558 * */
559 function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
561 $encrypted = $_POST['encrypted'];
562 $passphrase = $_POST['passphrase'];
563 $doEncryption = false;
564 if (
565 !$GLOBALS['hide_document_encryption'] &&
566 $encrypted == "true" &&
567 $passphrase
569 $doEncryption = true;
572 //controller function ruins booleans, so need to manually re-convert to booleans
573 if ($as_file == "true") {
574 $as_file = true;
575 } elseif ($as_file == "false") {
576 $as_file = false;
578 if ($original_file == "true") {
579 $original_file = true;
580 } elseif ($original_file == "false") {
581 $original_file = false;
583 if ($disable_exit == "true") {
584 $disable_exit = true;
585 } elseif ($disable_exit == "false") {
586 $disable_exit = false;
588 if ($show_original == "true") {
589 $show_original = true;
590 } elseif ($show_original == "false") {
591 $show_original = false;
594 switch ($context) {
595 case "patient_picture":
596 $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);
597 break;
600 $d = new Document($document_id);
601 $url = $d->get_url();
602 $th_url = $d->get_thumb_url();
604 $storagemethod = $d->get_storagemethod();
605 $couch_docid = $d->get_couch_docid();
606 $couch_revid = $d->get_couch_revid();
608 if ($couch_docid && $couch_revid && $original_file) {
609 // standard case for collecting a document from couchdb
610 $couch = new CouchDB();
611 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
612 $resp = $couch->retrieve_doc($data);
613 //Take thumbnail file when is not null and file is presented online
614 if (!$as_file && !is_null($th_url) && !$show_original) {
615 $content = $resp->th_data;
616 } else {
617 $content = $resp->data;
619 if ($content == '' && $GLOBALS['couchdb_log'] == 1) {
620 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
621 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
622 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
623 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
624 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
625 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
626 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
627 die(xlt("File retrieval from CouchDB failed"));
629 $filetext = base64_decode($content);
630 if ($disable_exit == true) {
631 return $filetext;
633 header('Content-Description: File Transfer');
634 header('Content-Transfer-Encoding: binary');
635 header('Expires: 0');
636 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
637 header('Pragma: public');
638 if ($doEncryption) {
639 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
640 header('Content-Disposition: attachment; filename="' . basename_international("/encrypted_aes_" . $d->get_url_file()) . '"');
641 header("Content-Type: application/octet-stream");
642 header("Content-Length: " . strlen($ciphertext));
643 echo $ciphertext;
644 } else {
645 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
646 header("Content-Type: " . $d->get_mimetype());
647 header("Content-Length: " . strlen($filetext));
648 echo $filetext;
650 exit;//exits only if file download from CouchDB is successfull.
652 if ($couch_docid && $couch_revid) {
653 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
654 //try to convert it if it has not yet been converted
655 //first, see if the converted jpg already exists
656 $couch = new CouchDB();
657 $data = array($GLOBALS['couchdb_dbase'], "converted_" . $couch_docid);
658 $resp = $couch->retrieve_doc($data);
659 $content = $resp->data;
660 if ($content == '') {
661 //create the converted jpg
662 $couchM = new CouchDB();
663 $dataM = array($GLOBALS['couchdb_dbase'], $couch_docid);
664 $respM = $couchM->retrieve_doc($dataM);
665 $contentM = $respM->data;
666 if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {
667 $log_content = date('Y-m-d H:i:s') . " ==> Retrieving document\r\n";
668 $log_content = date('Y-m-d H:i:s') . " ==> URL: " . $url . "\r\n";
669 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Document Id: " . $couch_docid . "\r\n";
670 $log_content .= date('Y-m-d H:i:s') . " ==> CouchDB Revision Id: " . $couch_revid . "\r\n";
671 $log_content .= date('Y-m-d H:i:s') . " ==> Failed to fetch document content from CouchDB.\r\n";
672 $log_content .= date('Y-m-d H:i:s') . " ==> Will try to download file from HardDisk if exists.\r\n\r\n";
673 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
674 die(xlt("File retrieval from CouchDB failed"));
676 // place the from-file into a temporary file
677 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
678 file_put_contents($from_file_tmp_name, base64_decode($contentM));
679 // prepare a temporary file for the to-file
680 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
681 $to_file_tmp_name = $to_file_tmp . ".jpg";
682 // convert file to jpg
683 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
684 // remove from tmp file
685 unlink($from_file_tmp_name);
686 // save the to-file if a to-file was created in above convert call
687 if (is_file($to_file_tmp_name)) {
688 $couchI = new CouchDB();
689 $json = json_encode(base64_encode(file_get_contents($to_file_tmp_name)));
690 $couchdata = array($GLOBALS['couchdb_dbase'], "converted_" . $couch_docid, $d->get_foreign_id(), "", "image/jpeg", $json);
691 $couchI->check_saveDOC($couchdata);
692 // remove to tmp files
693 unlink($to_file_tmp);
694 unlink($to_file_tmp_name);
695 } else {
696 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
698 // now collect the newly created converted jpg
699 $couchF = new CouchDB();
700 $dataF = array($GLOBALS['couchdb_dbase'], "converted_" . $couch_docid);
701 $respF = $couchF->retrieve_doc($dataF);
702 $content = $respF->data;
704 $filetext = base64_decode($content);
705 if ($disable_exit == true) {
706 return $filetext;
708 header("Pragma: public");
709 header("Expires: 0");
710 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
711 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
712 header("Content-Type: image/jpeg");
713 header("Content-Length: " . strlen($filetext));
714 echo $filetext;
715 exit;
718 //Take thumbnail file when is not null and file is presented online
719 if (!$as_file && !is_null($th_url) && !$show_original) {
720 $url = $th_url;
723 //strip url of protocol handler
724 $url = preg_replace("|^(.*)://|", "", $url);
726 //change full path to current webroot. this is for documents that may have
727 //been moved from a different filesystem and the full path in the database
728 //is not current. this is also for documents that may of been moved to
729 //different patients. Note that the path_depth is used to see how far down
730 //the path to go. For example, originally the path_depth was always 1, which
731 //only allowed things like documents/1/<file>, but now can have more structured
732 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
733 // etc.
734 // NOTE that $from_filename and basename($url) are the same thing
735 $from_all = explode("/", $url);
736 $from_filename = array_pop($from_all);
737 $from_pathname_array = array();
738 for ($i = 0; $i < $d->get_path_depth(); $i++) {
739 $from_pathname_array[] = array_pop($from_all);
741 $from_pathname_array = array_reverse($from_pathname_array);
742 $from_pathname = implode("/", $from_pathname_array);
743 if ($couch_docid && $couch_revid) {
744 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
745 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
746 } else {
747 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
750 if (file_exists($temp_url)) {
751 $url = $temp_url;
754 if (!file_exists($url)) {
755 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;
756 } else {
757 if ($original_file) {
758 //normal case when serving the file referenced in database
759 if ($d->get_encrypted() == 1) {
760 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
761 } else {
762 $filetext = file_get_contents($url);
764 if ($disable_exit == true) {
765 return $filetext;
767 header('Content-Description: File Transfer');
768 header('Content-Transfer-Encoding: binary');
769 header('Expires: 0');
770 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
771 header('Pragma: public');
772 if ($doEncryption) {
773 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
774 header('Content-Disposition: attachment; filename="' . basename_international("/encrypted_aes_" . $d->get_url_file()) . '"');
775 header("Content-Type: application/octet-stream");
776 header("Content-Length: " . strlen($ciphertext));
777 echo $ciphertext;
778 } else {
779 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
780 header("Content-Type: " . $d->get_mimetype());
781 header("Content-Length: " . strlen($filetext));
782 echo $filetext;
784 exit;
785 } else {
786 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
787 //try to convert it if it has not yet been converted
788 $originalUrl = $url;
789 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
790 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
791 if (!is_file($url)) {
792 if ($d->get_encrypted() == 1) {
793 // decrypt the from-file into a temporary file
794 $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
795 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
796 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
797 // prepare a temporary file for the unencrypted to-file
798 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
799 $to_file_tmp_name = $to_file_tmp . ".jpg";
800 // convert file to jpg
801 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
802 // remove unencrypted tmp file
803 unlink($from_file_tmp_name);
804 // make the encrypted to-file if a to-file was created in above convert call
805 if (is_file($to_file_tmp_name)) {
806 $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
807 file_put_contents($url, $to_file_encrypted);
808 // remove unencrypted tmp files
809 unlink($to_file_tmp);
810 unlink($to_file_tmp_name);
812 } else {
813 // convert file to jpg
814 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
817 if (is_file($url)) {
818 if ($d->get_encrypted() == 1) {
819 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
820 } else {
821 $filetext = file_get_contents($url);
823 } else {
824 $filetext = '';
825 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
827 if ($disable_exit == true) {
828 return $filetext;
830 header("Pragma: public");
831 header("Expires: 0");
832 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
833 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
834 header("Content-Type: image/jpeg");
835 header("Content-Length: " . strlen($filetext));
836 echo $filetext;
837 exit;
842 function queue_action($patient_id = "")
844 $messages = $this->_tpl_vars['messages'];
845 $queue_files = array();
847 //see if the repository exists and it is a directory else error
848 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
849 $dir = opendir($this->_config['repository']);
850 //read each entry in the directory
851 while (($file = readdir($dir)) !== false) {
852 //concat the filename and path
853 $file = $this->_config['repository'] . $file;
854 $file_info = array();
855 //if the filename is a file get its info and put into a tmp array
856 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
857 $file_info['filename'] = basename_international($file);
858 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
859 $d = $this->Document->document_factory_url("file://" . $file);
860 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
861 $file_info['patient_id'] = $patient_match[1];
862 $file_info['document_id'] = $d->get_id();
863 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . urlencode($d->get_id()) . "&";
865 //merge the tmp array into the larger array
866 $queue_files[] = $file_info;
869 closedir($dir);
870 } else {
871 $messages .= "The repository directory does not exist, it is not a directory or there are not sufficient permissions to access it. '" . $this->config['repository'] . "'\n";
875 $this->assign("queue_files", $queue_files);
876 $this->_last_node = null;
878 $menu = new HTML_TreeMenu();
880 //pass an empty array because we don't want the documents for each category showing up in this list box
881 $rnode = $this->_array_recurse($this->tree->tree, array());
882 $menu->addItem($rnode);
883 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
885 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
887 $this->assign("messages", nl2br($messages));
888 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
891 function queue_action_process()
893 if ($_POST['process'] != "true") {
894 return;
897 $messages = $this->_tpl_vars['messages'];
899 //build a category tree so we can have a list of category ids that are valid
900 $ct = new CategoryTree(1);
901 $categories = $ct->_id_name;
903 //see if there were and posted files and assign them
904 $files = null;
905 is_array($_POST['files']) ? $files = $_POST['files'] : $files = array();
907 //loop through posted files
908 foreach ($files as $doc_id => $file) {
909 //only operate on files checked as active
910 if (!$file['active']) {
911 continue;
914 //run basic validation checks
915 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
916 $messages .= "Error processing file '" . $file['name'] . "' the patient id must be a number and the category must exist.\n";
917 continue;
920 //validate that the pod exists
921 $d = new Document($doc_id);
922 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
923 $result = $d->_db->Execute($sql);
925 if (!$result || $result->EOF) {
926 //patient id does not exist
927 $messages .= "Error processing file '" . $file['name'] . " the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
928 continue;
931 //validate that the category id exists
932 if (!isset($categories[$file['category_id']])) {
933 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
934 continue;
937 //now do the work of moving the file
938 $new_path = $this->_config['repository'] . $file['patient_id'] . "/";
940 //see if the patient dir exists in the repository and create if not
941 if (!file_exists($new_path)) {
942 if (!mkdir($new_path, 0700)) {
943 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
944 continue;
948 //fname is the name of the file after it is moved
949 $fname = $file['name'];
951 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
952 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
953 if ($patient_match[1] == $file['patient_id']) {
954 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
957 //filenames should not have funny chars
958 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
960 //see if there is an existing file with the same name and rename as necessary
961 if (file_exists($new_path . $file['name'])) {
962 $messages .= "File with same name already exists at location: " . $new_path . "\n";
963 $fname = basename_international($this->_rename_file($new_path . $file['name']));
964 $messages .= "Current file name was changed to " . $fname . "\n";
967 //now move the file
968 if (rename($this->_config['repository'] . $file['name'], $new_path . $fname)) {
969 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] . "' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
970 $d->url = "file://" . $new_path . $fname;
971 $d->set_foreign_id($file['patient_id']);
972 $d->set_mimetype($mimetype);
973 $d->persist();
974 $d->populate();
976 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
977 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
978 $d->_db->Execute($sql);
980 } else {
981 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
984 $this->assign("messages", $messages);
985 $_POST['process'] = "";
988 function move_action_process(string $patient_id = null, $document_id)
990 if ($_POST['process'] != "true") {
991 return;
994 $new_category_id = $_POST['new_category_id'];
995 $new_patient_id = $_POST['new_patient_id'];
997 //move to new category
998 if (is_numeric($new_category_id) && is_numeric($document_id)) {
999 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id . "'";
1000 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
1001 //echo $sql;
1002 $this->tree->_db->Execute($sql);
1005 //move to new patient
1006 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
1007 $d = new Document($document_id);
1008 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
1009 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
1010 $result = $d->_db->Execute($sql);
1012 if (!$result || $result->EOF) {
1013 //patient id does not exist
1014 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
1015 } else {
1016 $couchsavefailed = !$d->change_patient($new_patient_id);
1018 $this->_state = false;
1019 if (!$couchsavefailed) {
1020 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
1021 } else {
1022 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
1024 $this->assign("messages", $messages);
1025 return $this->list_action($patient_id);
1027 } elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) { // in this case return the document
1028 // to the queue instead of moving it
1029 $d = new Document($document_id);
1030 $new_path = $this->_config['repository'];
1031 $fname = $d->get_url_file();
1033 //see if there is an existing file with the same name and rename as necessary
1034 if (file_exists($new_path . $d->get_url_file())) {
1035 $messages .= "File with same name already exists in the queue.\n";
1036 $fname = basename_international($this->_rename_file($new_path . $d->get_url_file()));
1037 $messages .= "Current file name was changed to " . $fname . "\n";
1040 //now move the file
1041 if (rename($d->get_url_filepath(), $new_path . $fname)) {
1042 $d->url = "file://" . $new_path . $fname;
1043 $d->set_foreign_id("");
1044 $d->persist();
1045 $d->persist();
1046 $d->populate();
1048 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
1049 $d->_db->Execute($sql);
1050 $messages .= "Document returned to queue successfully.\n";
1051 } else {
1052 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
1055 $this->_state = false;
1056 $this->assign("messages", $messages);
1057 return $this->list_action($patient_id);
1060 $this->_state = false;
1061 $this->assign("messages", $messages);
1062 return $this->view_action($patient_id, $document_id);
1065 function validate_action_process(string $patient_id = null, $document_id)
1068 $d = new Document($document_id);
1069 if ($d->couch_docid && $d->couch_revid) {
1070 $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';
1071 $url = $file_path . $d->get_url();
1072 $couch = new CouchDB();
1073 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
1074 $resp = $couch->retrieve_doc($data);
1075 $content = base64_decode($resp->data);
1076 } else {
1077 $url = $d->get_url();
1079 //strip url of protocol handler
1080 $url = preg_replace("|^(.*)://|", "", $url);
1082 //change full path to current webroot. this is for documents that may have
1083 //been moved from a different filesystem and the full path in the database
1084 //is not current. this is also for documents that may of been moved to
1085 //different patients. Note that the path_depth is used to see how far down
1086 //the path to go. For example, originally the path_depth was always 1, which
1087 //only allowed things like documents/1/<file>, but now can have more structured
1088 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
1089 // etc.
1090 // NOTE that $from_filename and basename($url) are the same thing
1091 $from_all = explode("/", $url);
1092 $from_filename = array_pop($from_all);
1093 $from_pathname_array = array();
1094 for ($i = 0; $i < $d->get_path_depth(); $i++) {
1095 $from_pathname_array[] = array_pop($from_all);
1097 $from_pathname_array = array_reverse($from_pathname_array);
1098 $from_pathname = implode("/", $from_pathname_array);
1099 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
1100 if (file_exists($temp_url)) {
1101 $url = $temp_url;
1104 if ($_POST['process'] != "true") {
1105 die("process is '" . text($_POST['process']) . "', expected 'true'");
1106 return;
1109 if ($d->get_encrypted() == 1) {
1110 $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
1111 } else {
1112 $content = file_get_contents($url);
1116 $current_hash = sha1($content);
1117 $messages = xl('Current Hash') . ": " . $current_hash . "<br />";
1118 $messages .= xl('Stored Hash') . ": " . $d->get_hash() . "<br />";
1119 if ($d->get_hash() == '') {
1120 $d->hash = $current_hash;
1121 $d->persist();
1122 $d->populate();
1123 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
1124 } elseif ($current_hash != $d->get_hash()) {
1125 $messages .= xl('Hash does not match. Data integrity has been compromised.');
1126 } else {
1127 $messages .= xl('Document passed integrity check.');
1129 $this->_state = false;
1130 $this->assign("messages", $messages);
1131 return $this->view_action($patient_id, $document_id);
1134 // Added by Rod for metadata update.
1136 function update_action_process(string $patient_id = null, $document_id)
1139 if ($_POST['process'] != "true") {
1140 die("process is '" . $_POST['process'] . "', expected 'true'");
1141 return;
1144 $docdate = $_POST['docdate'];
1145 $docname = $_POST['docname'];
1146 $issue_id = $_POST['issue_id'];
1148 if (is_numeric($document_id)) {
1149 $messages = '';
1150 $d = new Document($document_id);
1151 $file_name = $d->get_url_file();
1152 if (
1153 $docname != '' &&
1154 $docname != $file_name
1156 // Ready to rename - check for relocation
1157 $old_url = $this->_check_relocation($d->get_url());
1158 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1159 $messages .= sprintf("%s -> %s<br />", $old_url, $new_url);
1160 if (rename($old_url, $new_url)) {
1161 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1162 if (file_exists($old_url)) {
1163 unlink($old_url);
1165 $d->url = $new_url;
1166 $d->persist();
1167 $d->populate();
1168 $messages .= xl('Document successfully renamed.') . "<br />";
1169 } else {
1170 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.') . "<br />";
1174 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1175 $docdate = "'$docdate'";
1176 } else {
1177 $docdate = "NULL";
1179 if (!is_numeric($issue_id)) {
1180 $issue_id = 0;
1182 $couch_docid = $d->get_couch_docid();
1183 $couch_revid = $d->get_couch_revid();
1184 if ($couch_docid && $couch_revid) {
1185 $sql = "UPDATE documents SET docdate = $docdate, url = '" . $_POST['docname'] . "', " .
1186 "list_id = '$issue_id' " .
1187 "WHERE id = '$document_id'";
1188 $this->tree->_db->Execute($sql);
1189 } else {
1190 $sql = "UPDATE documents SET docdate = $docdate, " .
1191 "list_id = '$issue_id' " .
1192 "WHERE id = '$document_id'";
1193 $this->tree->_db->Execute($sql);
1195 $messages .= xl('Document date and issue updated successfully') . "<br />";
1198 $this->_state = false;
1199 $this->assign("messages", $messages);
1200 return $this->view_action($patient_id, $document_id);
1203 function list_action($patient_id = "")
1205 $this->_last_node = null;
1206 $categories_list = $this->tree->_get_categories_array($patient_id);
1207 //print_r($categories_list);
1209 $menu = new HTML_TreeMenu();
1210 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1211 $menu->addItem($rnode);
1212 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1213 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1214 $this->assign("tree_html", $treeMenu->toHTML());
1216 $is_new = isset($_GET['patient_name']) ? 1 : false;
1217 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1218 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1219 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1220 if ($cur_pid == '00') {
1221 $cur_pid = '0';
1222 $is_new = 1;
1224 $this->assign('is_new', $is_new);
1225 $this->assign('place_hld', $place_hld);
1226 $this->assign('cur_pid', $cur_pid);
1227 $this->assign('used_msg', $used_msg);
1228 $this->assign('demo_pid', $_SESSION['pid']);
1230 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1233 /* This is a recursive function to rename a file to something that doesn't already exist.
1234 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1235 * at end) to ensure documents opened correctly by external browser viewers. If the
1236 * counter is at the end of the file, then will use it (to continue to work with older
1237 * files), however all new counters will be placed within filenames.
1239 * Modified to only deal with base file name when renaming, to avoid issues with directory
1240 * names with dots.
1242 function _rename_file($fname, $self = false)
1244 // Allow same routine for new file name check
1245 if (!file_exists($fname)) {
1246 return($fname);
1249 $path = dirname($fname);
1250 $file = basename_international($fname);
1252 $fparts = explode(".", $file);
1253 switch (count($fparts)) {
1254 case 1:
1255 // Has a single node (base file name). Create counter node with value 0
1256 $fparts[1] = '1';
1257 break;
1258 case 2:
1259 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1260 if (is_numeric($fparts[1])) {
1261 $fparts[1] += 1;
1262 } else {
1263 array_push($fparts, $fparts[1]);
1264 $fparts[1] = '1';
1266 break;
1267 default:
1268 // Multiple nodes
1269 $ix_end = count($fparts) - 1;
1270 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1271 // Switch old style to new and check again
1272 $wrk = $fparts[$ix_end - 1];
1273 $fparts[$ix_end - 1] = $fparts[$ix_end];
1274 $fparts[$ix_end] = $wrk;
1275 } elseif (is_numeric($fparts[$ix_end - 1])) {
1276 $fparts[$ix_end - 1] += 1;
1277 } else {
1278 array_push($fparts, $fparts[$ix_end]);
1279 $fparts[$ix_end] = '1';
1281 break;
1284 $fname = $path . DIRECTORY_SEPARATOR . join(".", $fparts);
1286 if (file_exists($fname)) {
1287 return $this->_rename_file($fname, true);
1288 } else {
1289 return($fname);
1293 function &_array_recurse($array, $categories = array())
1295 if (!is_array($array)) {
1296 $array = array();
1298 $node = &$this->_last_node;
1299 $current_node = &$node;
1300 $expandedIcon = 'folder-expanded.gif';
1301 foreach ($array as $id => $ar) {
1302 $icon = 'folder.gif';
1303 if (is_array($ar) || !empty($id)) {
1304 if ($node == null) {
1305 //echo "r:" . $this->tree->get_node_name($id) . "<br />";
1306 $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));
1307 $this->_last_node = &$rnode;
1308 $node = &$rnode;
1309 $current_node = &$rnode;
1310 } else {
1311 //echo "p:" . $this->tree->get_node_name($id) . "<br />";
1312 $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)));
1313 $current_node = &$this->_last_node;
1316 $this->_array_recurse($ar, $categories);
1317 } else {
1318 if ($id === 0 && !empty($ar)) {
1319 $info = $this->tree->get_node_info($id);
1320 //echo "b:" . $this->tree->get_node_name($id) . "<br />";
1321 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1322 } else {
1323 //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
1324 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1325 if ($id !== 0 && is_object($node)) {
1326 //echo "n:" . $this->tree->get_node_name($id) . "<br />";
1327 $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)));
1332 // If there are documents in this document category, then add their
1333 // attributes to the current node.
1334 $icon = "file3.png";
1335 if (is_array($categories[$id])) {
1336 foreach ($categories[$id] as $doc) {
1337 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1338 // If user has no access then there will be no link.
1339 if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {
1340 $link = '';
1342 if ($this->tree->get_node_name($id) == "CCR") {
1343 $current_node->addItem(new HTML_TreeNode(array(
1344 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1345 'link' => $link,
1346 'icon' => $icon,
1347 'expandedIcon' => $expandedIcon,
1348 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1349 )));
1350 } elseif ($this->tree->get_node_name($id) == "CCD") {
1351 $current_node->addItem(new HTML_TreeNode(array(
1352 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1353 'link' => $link,
1354 'icon' => $icon,
1355 'expandedIcon' => $expandedIcon,
1356 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1357 )));
1358 } else {
1359 $current_node->addItem(new HTML_TreeNode(array(
1360 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1361 'link' => $link,
1362 'icon' => $icon,
1363 'expandedIcon' => $expandedIcon
1364 )));
1369 return $node;
1372 //function for logging the errors in writing file to CouchDB/Hard Disk
1373 function document_upload_download_log($patientid, $content)
1375 $log_path = $GLOBALS['OE_SITE_DIR'] . "/documents/couchdb/";
1376 $log_file = 'log.txt';
1377 if (!is_dir($log_path)) {
1378 mkdir($log_path, 0777, true);
1381 $LOG = file_get_contents($log_path . $log_file);
1383 if ($this->cryptoGen->cryptCheckStandard($LOG)) {
1384 $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');
1387 $LOG .= $content;
1389 if (!empty($LOG)) {
1390 if ($GLOBALS['drive_encryption']) {
1391 $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');
1393 file_put_contents($log_path . $log_file, $LOG);
1397 function document_send($email, $body, $attfile, $pname)
1399 if (empty($email)) {
1400 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1401 return;
1404 $desc = "Please check the attached patient document.\n Content:" . $body;
1405 $mail = new MyMailer();
1406 $from_name = $GLOBALS["practice_return_email_path"];
1407 $from = $GLOBALS["practice_return_email_path"];
1408 $mail->AddReplyTo($from, $from_name);
1409 $mail->SetFrom($from, $from);
1410 $to = $email ;
1411 $to_name = $email;
1412 $mail->AddAddress($to, $to_name);
1413 $subject = "Patient documents";
1414 $mail->Subject = $subject;
1415 $mail->Body = $desc;
1416 $mail->AddAttachment($attfile);
1417 if ($mail->Send()) {
1418 $retstatus = "email_sent";
1419 } else {
1420 $email_status = $mail->ErrorInfo;
1421 //echo "EMAIL ERROR: ".$email_status;
1422 $retstatus = "email_fail";
1426 //place to hold optional code
1427 //$first_node = array_keys($t->tree);
1428 //$first_node = $first_node[0];
1429 //$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')"));
1431 //$this->_last_node = &$node1;
1433 // Function to tag a document to an encounter.
1434 function tag_action_process(string $patient_id = null, $document_id)
1436 if ($_POST['process'] != "true") {
1437 die("process is '" . text($_POST['process']) . "', expected 'true'");
1438 return;
1441 // Create Encounter and Tag it.
1442 $event_date = date('Y-m-d H:i:s');
1443 $encounter_id = $_POST['encounter_id'];
1444 $encounter_check = $_POST['encounter_check'];
1445 $visit_category_id = $_POST['visit_category_id'];
1447 if (is_numeric($document_id)) {
1448 $messages = '';
1449 $d = new Document($document_id);
1450 $file_name = $d->get_url_file();
1451 if (!is_numeric($encounter_id)) {
1452 $encounter_id = 0;
1455 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1456 if ($encounter_check) {
1457 $provider_id = $_SESSION['authUserID'] ;
1459 // Get the logged in user's facility
1460 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1461 $username = $facilityRow['username'];
1462 $facility = $facilityRow['facility'];
1463 $facility_id = $facilityRow['facility_id'];
1464 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1465 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1466 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1468 $conn = $GLOBALS['adodb']['db'];
1469 $encounter = $conn->GenID("sequences");
1470 $query = "INSERT INTO form_encounter SET
1471 date = ?,
1472 reason = ?,
1473 facility = ?,
1474 sensitivity = 'normal',
1475 pc_catid = ?,
1476 facility_id = ?,
1477 billing_facility = ?,
1478 provider_id = ?,
1479 pid = ?,
1480 encounter = ?";
1481 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1482 $formID = sqlInsert($query, $bindArray);
1483 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1484 $d->set_encounter_id($encounter);
1485 $this->image_result_indication($d->id, $encounter);
1486 } else {
1487 $d->set_encounter_id($encounter_id);
1488 $this->image_result_indication($d->id, $encounter_id);
1490 $d->set_encounter_check($encounter_check);
1491 $d->persist();
1493 $messages .= xlt('Document tagged to Encounter successfully') . "<br />";
1496 $this->_state = false;
1497 $this->assign("messages", $messages);
1499 return $this->view_action($patient_id, $document_id);
1502 function image_procedure_action(string $patient_id = null, $document_id)
1505 $img_procedure_id = $_POST['image_procedure_id'];
1506 $proc_code = $_POST['procedure_code'];
1508 if (is_numeric($document_id)) {
1509 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1510 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1511 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1512 if ($img_report_id == 0) {
1513 $report_date = date('Y-m-d H:i:s');
1514 $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));
1517 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1518 if (empty($img_result)) {
1519 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));
1522 $this->image_result_indication($document_id, 0, $img_procedure_id);
1524 return $this->view_action($patient_id, $document_id);
1527 function clear_procedure_tag_action(string $patient_id = null, $document_id)
1529 if (is_numeric($document_id)) {
1530 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1532 return $this->view_action($patient_id, $document_id);
1535 function get_mapped_procedure($document_id)
1537 $map = array();
1538 if (is_numeric($document_id)) {
1539 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1540 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1541 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1542 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1543 where pres.document_id = ?", array($document_id));
1545 return $map;
1548 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1550 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1551 $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';
1553 if ($encounter != 0) {
1554 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1555 } elseif ($image_procedure_id != 0) {
1556 $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));
1557 } else {
1558 $ep = array('assigned_to' => $_SESSION['authUser']);
1561 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1562 $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1563 setGpRelation(1, $doc_id, 6, $noteid);
1566 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1567 * Also usable for documents that may of been moved to different patients.
1569 * @param string $url - Current url string from database.
1570 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1571 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1573 * @return string
1575 function _check_relocation($url, $new_pid = null, $new_name = null)
1577 //strip url of protocol handler
1578 $url = preg_replace("|^(.*)://|", "", $url);
1579 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1580 while (current($fsnodes) != "documents") {
1581 array_shift($fsnodes);
1583 if ($new_pid) {
1584 $fsnodes[1] = $new_pid;
1586 if ($new_name) {
1587 $fsnodes[count($fsnodes) - 1] = $new_name;
1589 $url = $GLOBALS['OE_SITE_DIR'] . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $fsnodes);
1590 // Make sure the url is available after corrections
1591 if ($new_pid || $new_name) {
1592 $url = $this->_rename_file($url);
1594 //Add full path and remaining nodes
1595 return $url;
1598 //clear encounter tag function
1599 function clear_encounter_tag_action(string $patient_id = null, $document_id)
1601 if (is_numeric($document_id)) {
1602 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1604 return $this->view_action($patient_id, $document_id);