Merge branch 'master' of https://github.com/openemr/openemr into signer-templates
[openemr.git] / controllers / C_Document.class.php
blob1d8203f7a60009c031cc1cd99477060d8bbc67ed
1 <?php
2 /**
3 * C_Document.class.php
5 * @package OpenEMR
6 * @link https://www.open-emr.org
7 * @author Brady Miller <brady.g.miller@gmail.com>
8 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
9 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
12 require_once(dirname(__FILE__) . "/../library/forms.inc");
14 use OpenEMR\Common\Crypto\CryptoGen;
15 use OpenEMR\Common\Csrf\CsrfUtils;
16 use OpenEMR\Services\FacilityService;
17 use OpenEMR\Services\PatientService;
19 class C_Document extends Controller
22 var $template_mod;
23 var $documents;
24 var $document_categories;
25 var $tree;
26 var $_config;
27 var $manual_set_owner=false; // allows manual setting of a document owner/service
28 var $facilityService;
29 var $patientService;
31 function __construct($template_mod = "general")
33 parent::__construct();
34 $this->facilityService = new FacilityService();
35 $this->patientService = new PatientService();
36 $this->documents = array();
37 $this->template_mod = $template_mod;
38 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . attr($_SERVER['QUERY_STRING']));
39 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
41 $this->assign("CSRF_TOKEN_FORM", CsrfUtils::collectCsrfToken());
43 $this->assign("IMAGES_STATIC_RELATIVE", $GLOBALS['images_static_relative']);
45 //get global config options for this namespace
46 $this->_config = $GLOBALS['oer_config']['documents'];
48 $this->_args = array("patient_id" => $_GET['patient_id']);
50 $this->assign("STYLE", $GLOBALS['style']);
51 $t = new CategoryTree(1);
52 //print_r($t->tree);
53 $this->tree = $t;
54 $this->Document = new Document();
56 // Create a crypto object that will be used for for encryption/decryption
57 $this->cryptoGen = new CryptoGen();
60 function upload_action($patient_id, $category_id)
62 $category_name = $this->tree->get_node_name($category_id);
63 $this->assign("category_id", $category_id);
64 $this->assign("category_name", $category_name);
65 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
66 $this->assign("patient_id", $patient_id);
68 // Added by Rod to support document template download from general_upload.html.
69 // Cloned from similar stuff in manage_document_templates.php.
70 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
71 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
72 if (file_exists($templatedir)) {
73 $dh = opendir($templatedir);
75 if ($dh) {
76 $templateslist = array();
77 while (false !== ($sfname = readdir($dh))) {
78 if (substr($sfname, 0, 1) == '.') {
79 continue;
81 $templateslist[$sfname] = $sfname;
83 closedir($dh);
84 ksort($templateslist);
85 foreach ($templateslist as $sfname) {
86 $templates_options .= "<option value='" . attr($sfname) .
87 "'>" . text($sfname) . "</option>";
90 $this->assign("TEMPLATES_LIST", $templates_options);
92 // duplicate template list for new template form editor sjp 05/20/2019
93 // will call as module or individual template.
94 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';
95 $templates_options = "<option value=''>-- " . xlt('Open Forms Module') . " --</option>";
96 if (file_exists($templatedir)) {
97 $dh = opendir($templatedir);
99 if ($dh) {
100 $templateslist = array();
101 while (false !== ($sfname = readdir($dh))) {
102 if (substr($sfname, 0, 1) == '.') {
103 continue;
105 if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {
106 $templateslist[$sfname] = $sfname;
109 closedir($dh);
110 ksort($templateslist);
111 foreach ($templateslist as $sfname) {
112 $optname = str_replace('_', ' ', basename($sfname, ".tpl"));
113 $templates_options .= "<option value='" . attr($sfname) . "'>" . text($optname) . "</option>";
116 $this->assign("TEMPLATES_LIST_PATIENT", $templates_options);
118 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
119 $this->assign("activity", $activity);
120 return $this->list_action($patient_id);
123 //Upload multiple files on single click
124 function upload_action_process()
127 // Collect a manually set owner if this has been set
128 // Used when want to manually assign the owning user/service such as the Direct mechanism
129 $non_HTTP_owner=false;
130 if ($this->manual_set_owner) {
131 $non_HTTP_owner=$this->manual_set_owner;
134 $couchDB = false;
135 $harddisk = false;
136 if ($GLOBALS['document_storage_method']==0) {
137 $harddisk = true;
139 if ($GLOBALS['document_storage_method']==1) {
140 $couchDB = true;
143 if ($_POST['process'] != "true") {
144 return;
147 $doDecryption = false;
148 $encrypted = $_POST['encrypted'];
149 $passphrase = $_POST['passphrase'];
150 if (!$GLOBALS['hide_document_encryption'] &&
151 $encrypted && $passphrase ) {
152 $doDecryption = true;
155 if (is_numeric($_POST['category_id'])) {
156 $category_id = $_POST['category_id'];
159 $patient_id = 0;
160 if (isset($_GET['patient_id']) && !$couchDB) {
161 $patient_id = $_GET['patient_id'];
162 } else if (is_numeric($_POST['patient_id'])) {
163 $patient_id = $_POST['patient_id'];
166 $sentUploadStatus = array();
167 if (count($_FILES['file']['name']) > 0) {
168 $upl_inc = 0;
170 foreach ($_FILES['file']['name'] as $key => $value) {
171 $fname = $value;
172 $error = "";
173 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
174 $fname = $value;
175 if (empty($fname)) {
176 $fname = htmlentities("<empty>");
178 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
179 if ($_FILES['file']['size'][$key] == 0) {
180 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
182 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
183 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
184 } else {
185 // Test for a zip of DICOM images
186 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
187 $za = new ZipArchive();
188 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
189 if ($handler) {
190 $mimetype = "application/dicom+zip";
191 for ($i = 0; $i < $za->numFiles; $i++) {
192 $stat = $za->statIndex($i);
193 $fp = $za->getStream($stat['name']);
194 if ($fp) {
195 $head = fread($fp, 256);
196 fclose($fp);
197 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
198 $mimetype = "application/zip";
199 break;
201 unset($head);
202 // if here -then a DICOM
203 $parts = pathinfo($stat['name']);
204 if (strtolower($parts['extension']) != "dcm") { // require extension for viewer
205 $new_name = $stat['name'] . ".dcm";
206 $za->renameIndex($i, $new_name); // only use index rename!
208 } else { // Rarely here
209 $mimetype = "application/zip";
210 break;
213 $za->close();
214 if ($mimetype == "application/dicom+zip") {
215 $_FILES['file']['type'][$key] = $mimetype;
216 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
217 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
221 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
222 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
223 fclose($tmpfile);
224 if ($doDecryption) {
225 $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);
226 if ($filetext === false) {
227 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
228 $filetext = "";
231 if ($_POST['destination'] != '') {
232 $fname = $_POST['destination'];
234 // set mime, test for single DICOM and assign extension if missing.
235 $mimetype = $_FILES['file']['type'][$key];
236 if (strpos($filetext, 'DICM') !== false) {
237 $mimetype = 'application/dicom';
238 $parts = pathinfo($fname);
239 if (!$parts['extension']) {
240 $fname .= '.dcm';
243 $d = new Document();
244 $rc = $d->createDocument(
245 $patient_id,
246 $category_id,
247 $fname,
248 $mimetype,
249 $filetext,
250 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
251 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
252 $non_HTTP_owner,
253 $_FILES['file']['tmp_name'][$key]
255 if ($rc) {
256 $error .= $rc . "\n";
257 } else {
258 $this->assign("upload_success", "true");
260 $sentUploadStatus[] = $d;
261 $this->assign("file", $sentUploadStatus);
264 // Option to run a custom plugin for each file upload.
265 // This was initially created to delete the original source file in a custom setting.
266 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
267 if (file_exists($upload_plugin)) {
268 include_once($upload_plugin);
270 $upload_plugin_pp = 'documentUploadPostProcess';
271 if (function_exists($upload_plugin_pp)) {
272 $tmp = call_user_func($upload_plugin_pp, $value, $d);
273 if ($tmp) {
274 $error = $tmp;
277 // Following is just an example of code in such a plugin file.
278 /*****************************************************
279 function documentUploadPostProcess($filename, &$d) {
280 $userid = $_SESSION['authUserID'];
281 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
282 $owner = strtolower($row['username']);
283 $dn = '1_' . ucfirst($owner);
284 $filepath = "/shared_network_directory/$dn/$filename";
285 if (@unlink($filepath)) return '';
286 return "Failed to delete '$filepath'.";
288 *****************************************************/
292 $this->assign("error", nl2br($error));
293 //$this->_state = false;
294 $_POST['process'] = "";
295 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
298 function note_action_process($patient_id)
300 // this function is a dual function that will set up a note associated with a document or send a document via email.
302 if ($_POST['process'] != "true") {
303 return;
306 $n = new Note();
307 $n->set_owner($_SESSION['authUserID']);
308 parent::populate_object($n);
309 if ($_POST['identifier'] == "no") {
310 // associate a note with a document
311 $n->persist();
312 } elseif ($_POST['identifier'] == "yes") {
313 // send the document via email
314 $d = new Document($_POST['foreign_id']);
315 $url = $d->get_url();
316 $storagemethod = $d->get_storagemethod();
317 $couch_docid = $d->get_couch_docid();
318 $couch_revid = $d->get_couch_revid();
319 if ($couch_docid && $couch_revid) {
320 $couch = new CouchDB();
321 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
322 $resp = $couch->retrieve_doc($data);
323 $content = $resp->data;
324 if ($content=='' && $GLOBALS['couchdb_log']==1) {
325 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
326 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
327 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
328 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
329 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
330 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
331 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
332 die(xlt("File retrieval from CouchDB failed"));
334 // place it in a temporary file and will remove the file below after emailed
335 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
336 $fh = fopen($temp_couchdb_url, "w");
337 fwrite($fh, base64_decode($content));
338 fclose($fh);
339 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
340 } else {
341 $url = preg_replace("|^(.*)://|", "", $url);
342 // Collect filename and path
343 $from_all = explode("/", $url);
344 $from_filename = array_pop($from_all);
345 $from_pathname_array = array();
346 for ($i=0; $i<$d->get_path_depth(); $i++) {
347 $from_pathname_array[] = array_pop($from_all);
349 $from_pathname_array = array_reverse($from_pathname_array);
350 $from_pathname = implode("/", $from_pathname_array);
351 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
353 if (!file_exists($temp_url)) {
354 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;
356 $url = $temp_url;
357 $pdetails = getPatientData($patient_id);
358 $pname = $pdetails['fname']." ".$pdetails['lname'];
359 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
360 if ($couch_docid && $couch_revid) {
361 // remove the temporary couchdb file
362 unlink($temp_couchdb_url);
365 $this->_state = false;
366 $_POST['process'] = "";
367 return $this->view_action($patient_id, $n->get_foreign_id());
370 function default_action()
372 return $this->list_action();
375 function view_action($patient_id = "", $doc_id)
377 // Added by Rod to support document delete:
378 global $gacl_object, $phpgacl_location;
379 global $ISSUE_TYPES;
381 require_once(dirname(__FILE__) . "/../library/acl.inc");
382 require_once(dirname(__FILE__) . "/../library/lists.inc");
384 $d = new Document($doc_id);
385 $notes = $d->get_notes();
387 $this->assign("csrf_token_form", CsrfUtils::collectCsrfToken());
389 $this->assign("file", $d);
390 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . urlencode($d->get_id()) . "&");
391 $this->assign("NOTE_ACTION", $this->_link("note"));
392 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . urlencode($d->get_id()) . "&process=true");
393 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
394 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
395 $this->assign("webroot", $GLOBALS['webroot']);
397 // Added by Rod to support document delete:
398 $delete_string = '';
399 if (acl_check('patients', 'docs_rm')) {
400 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . attr_js($d->get_id()) .
401 ")'><span><font color='red'>" . xlt('Delete') . "</font></span></a>";
403 $this->assign("delete_string", $delete_string);
404 $this->assign("REFRESH_ACTION", $this->_link("list"));
406 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
407 "document_id=" . $d->get_id() . "&process=true");
409 // Added by Rod to support document date update:
410 $this->assign("DOCDATE", $d->get_docdate());
411 $this->assign("UPDATE_ACTION", $this->_link("update") .
412 "document_id=" . $d->get_id() . "&process=true");
414 // Added by Rod to support document issue update:
415 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
416 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
417 "pid = ? " . // AND enddate IS NULL " .
418 "ORDER BY type, begdate", array($patient_id));
419 while ($irow = sqlFetchArray($ires)) {
420 $desc = $irow['type'];
421 if ($ISSUE_TYPES[$desc]) {
422 $desc = $ISSUE_TYPES[$desc][2];
424 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
425 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
426 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
428 $this->assign("ISSUES_LIST", $issues_options);
430 // For tagging to encounter
431 // Populate the dropdown with patient's encounter list
432 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . urlencode($d->get_id()) . "&process=true");
433 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
434 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
435 "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));
436 if (sqlNumRows($result_docs) > 0) {
437 while ($row_result_docs = sqlFetchArray($result_docs)) {
438 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
439 $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>";
442 $this->assign("ENC_LIST", $encOptions);
444 //clear encounter tag
445 if ($d->get_encounter_id() != 0) {
446 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . urlencode($d->get_id()));
447 } else {
448 $this->assign('clear_encounter_tag', 'javascript:void(0)');
451 //Populate the dropdown with category list
452 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
453 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
454 while ($crow = sqlFetchArray($cres)) {
455 $catid = $crow['pc_catid'];
456 if ($catid < 9 && $catid != 5) {
457 continue; // Applying same logic as in new encounter page.
459 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
461 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
463 $this->assign("notes", $notes);
465 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . urlencode($d->get_id()));
466 // Populate the dropdown with image procedure order list
467 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
468 $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));
469 $mapping = $this->get_mapped_procedure($d->get_id());
470 if (sqlNumRows($imgOrders) > 0) {
471 while ($row = sqlFetchArray($imgOrders)) {
472 $sel_proc = '';
473 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
474 $sel_proc = 'selected';
476 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
480 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
482 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . urlencode($d->get_id()));
484 $this->_last_node = null;
486 $menu = new HTML_TreeMenu();
488 //pass an empty array because we don't want the documents for each category showing up in this list box
489 $rnode = $this->_array_recurse($this->tree->tree, array());
490 $menu->addItem($rnode);
491 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
493 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
495 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
496 $this->assign("activity", $activity);
498 return $this->list_action($patient_id);
502 * Retrieve file from hard disk / CouchDB.
503 * In case that file isn't download this function will return thumbnail image (if exist).
504 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
505 * @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.
506 * */
507 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
509 $encrypted = $_POST['encrypted'];
510 $passphrase = $_POST['passphrase'];
511 $doEncryption = false;
512 if (!$GLOBALS['hide_document_encryption'] &&
513 $encrypted == "true" &&
514 $passphrase ) {
515 $doEncryption = true;
518 //controller function ruins booleans, so need to manually re-convert to booleans
519 if ($as_file == "true") {
520 $as_file=true;
521 } else if ($as_file == "false") {
522 $as_file=false;
524 if ($original_file == "true") {
525 $original_file=true;
526 } else if ($original_file == "false") {
527 $original_file=false;
529 if ($disable_exit == "true") {
530 $disable_exit=true;
531 } else if ($disable_exit == "false") {
532 $disable_exit=false;
534 if ($show_original == "true") {
535 $show_original=true;
536 } else if ($show_original == "false") {
537 $show_original=false;
540 switch ($context) {
541 case "patient_picture":
542 $this->patientService->setPid($patient_id);
543 $document_id = $this->patientService->getPatientPictureDocumentId();
544 break;
547 $d = new Document($document_id);
548 $url = $d->get_url();
549 $th_url = $d->get_thumb_url();
551 $storagemethod = $d->get_storagemethod();
552 $couch_docid = $d->get_couch_docid();
553 $couch_revid = $d->get_couch_revid();
555 if ($couch_docid && $couch_revid && $original_file) {
556 // standard case for collecting a document from couchdb
557 $couch = new CouchDB();
558 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
559 $resp = $couch->retrieve_doc($data);
560 //Take thumbnail file when is not null and file is presented online
561 if (!$as_file && !is_null($th_url) && !$show_original) {
562 $content = $resp->th_data;
563 } else {
564 $content = $resp->data;
566 if ($content=='' && $GLOBALS['couchdb_log']==1) {
567 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
568 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
569 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
570 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
571 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
572 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
573 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
574 die(xlt("File retrieval from CouchDB failed"));
576 $filetext = base64_decode($content);
577 if ($disable_exit == true) {
578 return $filetext;
580 header('Content-Description: File Transfer');
581 header('Content-Transfer-Encoding: binary');
582 header('Expires: 0');
583 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
584 header('Pragma: public');
585 if ($doEncryption) {
586 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
587 header('Content-Disposition: attachment; filename="' . basename_international("/encrypted_aes_".$d->get_url_file()) . '"');
588 header("Content-Type: application/octet-stream");
589 header("Content-Length: " . strlen($ciphertext));
590 echo $ciphertext;
591 } else {
592 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
593 header("Content-Type: " . $d->get_mimetype());
594 header("Content-Length: " . strlen($filetext));
595 echo $filetext;
597 exit;//exits only if file download from CouchDB is successfull.
599 if ($couch_docid && $couch_revid) {
600 //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table
601 //try to convert it if it has not yet been converted
602 //first, see if the converted jpg already exists
603 $couch = new CouchDB();
604 $data = array($GLOBALS['couchdb_dbase'], "converted_".$couch_docid);
605 $resp = $couch->retrieve_doc($data);
606 $content = $resp->data;
607 if ($content == '') {
608 //create the converted jpg
609 $couchM = new CouchDB();
610 $dataM = array($GLOBALS['couchdb_dbase'], $couch_docid);
611 $respM = $couchM->retrieve_doc($dataM);
612 $contentM = $respM->data;
613 if ($contentM=='' && $GLOBALS['couchdb_log']==1) {
614 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
615 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
616 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
617 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
618 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
619 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
620 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
621 die(xlt("File retrieval from CouchDB failed"));
623 // place the from-file into a temporary file
624 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
625 file_put_contents($from_file_tmp_name, base64_decode($contentM));
626 // prepare a temporary file for the to-file
627 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
628 $to_file_tmp_name = $to_file_tmp . ".jpg";
629 // convert file to jpg
630 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
631 // remove from tmp file
632 unlink($from_file_tmp_name);
633 // save the to-file if a to-file was created in above convert call
634 if (is_file($to_file_tmp_name)) {
635 $couchI = new CouchDB();
636 $json = json_encode(base64_encode(file_get_contents($to_file_tmp_name)));
637 $couchdata = array($GLOBALS['couchdb_dbase'], "converted_" . $couch_docid, $d->get_foreign_id(), "", "image/jpeg", $json);
638 $couchI->check_saveDOC($couchdata);
639 // remove to tmp files
640 unlink($to_file_tmp);
641 unlink($to_file_tmp_name);
642 } else {
643 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
645 // now collect the newly created converted jpg
646 $couchF = new CouchDB();
647 $dataF = array($GLOBALS['couchdb_dbase'], "converted_".$couch_docid);
648 $respF = $couchF->retrieve_doc($dataF);
649 $content = $respF->data;
651 $filetext = base64_decode($content);
652 if ($disable_exit == true) {
653 return $filetext;
655 header("Pragma: public");
656 header("Expires: 0");
657 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
658 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
659 header("Content-Type: image/jpeg");
660 header("Content-Length: " . strlen($filetext));
661 echo $filetext;
662 exit;
665 //Take thumbnail file when is not null and file is presented online
666 if (!$as_file && !is_null($th_url) && !$show_original) {
667 $url = $th_url;
670 //strip url of protocol handler
671 $url = preg_replace("|^(.*)://|", "", $url);
673 //change full path to current webroot. this is for documents that may have
674 //been moved from a different filesystem and the full path in the database
675 //is not current. this is also for documents that may of been moved to
676 //different patients. Note that the path_depth is used to see how far down
677 //the path to go. For example, originally the path_depth was always 1, which
678 //only allowed things like documents/1/<file>, but now can have more structured
679 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
680 // etc.
681 // NOTE that $from_filename and basename($url) are the same thing
682 $from_all = explode("/", $url);
683 $from_filename = array_pop($from_all);
684 $from_pathname_array = array();
685 for ($i=0; $i<$d->get_path_depth(); $i++) {
686 $from_pathname_array[] = array_pop($from_all);
688 $from_pathname_array = array_reverse($from_pathname_array);
689 $from_pathname = implode("/", $from_pathname_array);
690 if ($couch_docid && $couch_revid) {
691 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
692 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
693 } else {
694 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
697 if (file_exists($temp_url)) {
698 $url = $temp_url;
701 if (!file_exists($url)) {
702 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;
703 } else {
704 if ($original_file) {
705 //normal case when serving the file referenced in database
706 if ($d->get_encrypted() == 1) {
707 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
708 } else {
709 $filetext = file_get_contents($url);
711 if ($disable_exit == true) {
712 return $filetext;
714 header('Content-Description: File Transfer');
715 header('Content-Transfer-Encoding: binary');
716 header('Expires: 0');
717 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
718 header('Pragma: public');
719 if ($doEncryption) {
720 $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);
721 header('Content-Disposition: attachment; filename="' . basename_international("/encrypted_aes_".$d->get_url_file()) . '"');
722 header("Content-Type: application/octet-stream");
723 header("Content-Length: " . strlen($ciphertext));
724 echo $ciphertext;
725 } else {
726 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
727 header("Content-Type: " . $d->get_mimetype());
728 header("Content-Length: " . strlen($filetext));
729 echo $filetext;
731 exit;
732 } else {
733 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
734 //try to convert it if it has not yet been converted
735 $originalUrl = $url;
736 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
737 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
738 if (!is_file($url)) {
739 if ($d->get_encrypted() == 1) {
740 // decrypt the from-file into a temporary file
741 $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');
742 $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], "oer");
743 file_put_contents($from_file_tmp_name, $from_file_unencrypted);
744 // prepare a temporary file for the unencrypted to-file
745 $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], "oer");
746 $to_file_tmp_name = $to_file_tmp . ".jpg";
747 // convert file to jpg
748 exec("convert -density 200 " . escapeshellarg($from_file_tmp_name) . " -append -resize 850 " . escapeshellarg($to_file_tmp_name));
749 // remove unencrypted tmp file
750 unlink($from_file_tmp_name);
751 // make the encrypted to-file if a to-file was created in above convert call
752 if (is_file($to_file_tmp_name)) {
753 $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');
754 file_put_contents($url, $to_file_encrypted);
755 // remove unencrypted tmp files
756 unlink($to_file_tmp);
757 unlink($to_file_tmp_name);
759 } else {
760 // convert file to jpg
761 exec("convert -density 200 " . escapeshellarg($originalUrl) . " -append -resize 850 " . escapeshellarg($url));
764 if (is_file($url)) {
765 if ($d->get_encrypted() == 1) {
766 $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
767 } else {
768 $filetext = file_get_contents($url);
770 } else {
771 $filetext = '';
772 error_log("ERROR: Document '" . errorLogEscape(basename_international($url)) . "' cannot be converted to JPEG. Perhaps ImageMagick is not installed?");
774 if ($disable_exit == true) {
775 return $filetext;
777 header("Pragma: public");
778 header("Expires: 0");
779 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
780 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
781 header("Content-Type: image/jpeg");
782 header("Content-Length: " . strlen($filetext));
783 echo $filetext;
784 exit;
789 function queue_action($patient_id = "")
791 $messages = $this->_tpl_vars['messages'];
792 $queue_files = array();
794 //see if the repository exists and it is a directory else error
795 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
796 $dir = opendir($this->_config['repository']);
797 //read each entry in the directory
798 while (($file = readdir($dir)) !== false) {
799 //concat the filename and path
800 $file = $this->_config['repository'] .$file;
801 $file_info = array();
802 //if the filename is a file get its info and put into a tmp array
803 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
804 $file_info['filename'] = basename_international($file);
805 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
806 $d = $this->Document->document_factory_url("file://" . $file);
807 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
808 $file_info['patient_id'] = $patient_match[1];
809 $file_info['document_id'] = $d->get_id();
810 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . urlencode($d->get_id()) . "&";
812 //merge the tmp array into the larger array
813 $queue_files[] = $file_info;
816 closedir($dir);
817 } else {
818 $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";
822 $this->assign("queue_files", $queue_files);
823 $this->_last_node = null;
825 $menu = new HTML_TreeMenu();
827 //pass an empty array because we don't want the documents for each category showing up in this list box
828 $rnode = $this->_array_recurse($this->tree->tree, array());
829 $menu->addItem($rnode);
830 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
832 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
834 $this->assign("messages", nl2br($messages));
835 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
838 function queue_action_process()
840 if ($_POST['process'] != "true") {
841 return;
844 $messages = $this->_tpl_vars['messages'];
846 //build a category tree so we can have a list of category ids that are valid
847 $ct = new CategoryTree(1);
848 $categories = $ct->_id_name;
850 //see if there were and posted files and assign them
851 $files = null;
852 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
854 //loop through posted files
855 foreach ($files as $doc_id => $file) {
856 //only operate on files checked as active
857 if (!$file['active']) {
858 continue;
861 //run basic validation checks
862 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
863 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
864 continue;
867 //validate that the pod exists
868 $d = new Document($doc_id);
869 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
870 $result = $d->_db->Execute($sql);
872 if (!$result || $result->EOF) {
873 //patient id does not exist
874 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
875 continue;
878 //validate that the category id exists
879 if (!isset($categories[$file['category_id']])) {
880 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
881 continue;
884 //now do the work of moving the file
885 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
887 //see if the patient dir exists in the repository and create if not
888 if (!file_exists($new_path)) {
889 if (!mkdir($new_path, 0700)) {
890 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
891 continue;
895 //fname is the name of the file after it is moved
896 $fname = $file['name'];
898 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
899 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
900 if ($patient_match[1] == $file['patient_id']) {
901 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
904 //filenames should not have funny chars
905 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
907 //see if there is an existing file with the same name and rename as necessary
908 if (file_exists($new_path.$file['name'])) {
909 $messages .= "File with same name already exists at location: " . $new_path . "\n";
910 $fname = basename_international($this->_rename_file($new_path.$file['name']));
911 $messages .= "Current file name was changed to " . $fname ."\n";
914 //now move the file
915 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
916 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
917 $d->url = "file://" .$new_path.$fname;
918 $d->set_foreign_id($file['patient_id']);
919 $d->set_mimetype($mimetype);
920 $d->persist();
921 $d->populate();
923 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
924 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
925 $d->_db->Execute($sql);
927 } else {
928 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
931 $this->assign("messages", $messages);
932 $_POST['process'] = "";
935 function move_action_process($patient_id = "", $document_id)
937 if ($_POST['process'] != "true") {
938 return;
941 $new_category_id = $_POST['new_category_id'];
942 $new_patient_id = $_POST['new_patient_id'];
944 //move to new category
945 if (is_numeric($new_category_id) && is_numeric($document_id)) {
946 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
947 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
948 //echo $sql;
949 $this->tree->_db->Execute($sql);
952 //move to new patient
953 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
954 $d = new Document($document_id);
955 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
956 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
957 $result = $d->_db->Execute($sql);
959 if (!$result || $result->EOF) {
960 //patient id does not exist
961 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
962 } else {
963 $couchsavefailed = !$d->change_patient($new_patient_id);
965 $this->_state = false;
966 if (!$couchsavefailed) {
967 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
968 } else {
969 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
971 $this->assign("messages", $messages);
972 return $this->list_action($patient_id);
974 } elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) { // in this case return the document
975 // to the queue instead of moving it
976 $d = new Document($document_id);
977 $new_path = $this->_config['repository'];
978 $fname = $d->get_url_file();
980 //see if there is an existing file with the same name and rename as necessary
981 if (file_exists($new_path.$d->get_url_file())) {
982 $messages .= "File with same name already exists in the queue.\n";
983 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
984 $messages .= "Current file name was changed to " . $fname ."\n";
987 //now move the file
988 if (rename($d->get_url_filepath(), $new_path.$fname)) {
989 $d->url = "file://" .$new_path.$fname;
990 $d->set_foreign_id("");
991 $d->persist();
992 $d->persist();
993 $d->populate();
995 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
996 $d->_db->Execute($sql);
997 $messages .= "Document returned to queue successfully.\n";
998 } else {
999 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
1002 $this->_state = false;
1003 $this->assign("messages", $messages);
1004 return $this->list_action($patient_id);
1007 $this->_state = false;
1008 $this->assign("messages", $messages);
1009 return $this->view_action($patient_id, $document_id);
1012 function validate_action_process($patient_id = "", $document_id)
1015 $d = new Document($document_id);
1016 if ($d->couch_docid && $d->couch_revid) {
1017 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
1018 $url = $file_path.$d->get_url();
1019 $couch = new CouchDB();
1020 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
1021 $resp = $couch->retrieve_doc($data);
1022 $content = base64_decode($resp->data);
1023 } else {
1024 $url = $d->get_url();
1026 //strip url of protocol handler
1027 $url = preg_replace("|^(.*)://|", "", $url);
1029 //change full path to current webroot. this is for documents that may have
1030 //been moved from a different filesystem and the full path in the database
1031 //is not current. this is also for documents that may of been moved to
1032 //different patients. Note that the path_depth is used to see how far down
1033 //the path to go. For example, originally the path_depth was always 1, which
1034 //only allowed things like documents/1/<file>, but now can have more structured
1035 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
1036 // etc.
1037 // NOTE that $from_filename and basename($url) are the same thing
1038 $from_all = explode("/", $url);
1039 $from_filename = array_pop($from_all);
1040 $from_pathname_array = array();
1041 for ($i=0; $i<$d->get_path_depth(); $i++) {
1042 $from_pathname_array[] = array_pop($from_all);
1044 $from_pathname_array = array_reverse($from_pathname_array);
1045 $from_pathname = implode("/", $from_pathname_array);
1046 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
1047 if (file_exists($temp_url)) {
1048 $url = $temp_url;
1051 if ($_POST['process'] != "true") {
1052 die("process is '" . text($_POST['process']) . "', expected 'true'");
1053 return;
1056 if ($d->get_encrypted() == 1) {
1057 $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');
1058 } else {
1059 $content = file_get_contents($url);
1063 $current_hash = sha1($content);
1064 $messages = xl('Current Hash').": ".$current_hash."<br>";
1065 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
1066 if ($d->get_hash() == '') {
1067 $d->hash = $current_hash;
1068 $d->persist();
1069 $d->populate();
1070 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
1071 } else if ($current_hash != $d->get_hash()) {
1072 $messages .= xl('Hash does not match. Data integrity has been compromised.');
1073 } else {
1074 $messages .= xl('Document passed integrity check.');
1076 $this->_state = false;
1077 $this->assign("messages", $messages);
1078 return $this->view_action($patient_id, $document_id);
1081 // Added by Rod for metadata update.
1083 function update_action_process($patient_id = "", $document_id)
1086 if ($_POST['process'] != "true") {
1087 die("process is '" . $_POST['process'] . "', expected 'true'");
1088 return;
1091 $docdate = $_POST['docdate'];
1092 $docname = $_POST['docname'];
1093 $issue_id = $_POST['issue_id'];
1095 if (is_numeric($document_id)) {
1096 $messages = '';
1097 $d = new Document($document_id);
1098 $file_name = $d->get_url_file();
1099 if ($docname != '' &&
1100 $docname != $file_name ) {
1101 // Ready to rename - check for relocation
1102 $old_url = $this->_check_relocation($d->get_url());
1103 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1104 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
1105 if (rename($old_url, $new_url)) {
1106 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1107 if (file_exists($old_url)) {
1108 unlink($old_url);
1110 $d->url = $new_url;
1111 $d->persist();
1112 $d->populate();
1113 $messages .= xl('Document successfully renamed.')."<br>";
1114 } else {
1115 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1119 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1120 $docdate = "'$docdate'";
1121 } else {
1122 $docdate = "NULL";
1124 if (!is_numeric($issue_id)) {
1125 $issue_id = 0;
1127 $couch_docid = $d->get_couch_docid();
1128 $couch_revid = $d->get_couch_revid();
1129 if ($couch_docid && $couch_revid) {
1130 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1131 "list_id = '$issue_id' " .
1132 "WHERE id = '$document_id'";
1133 $this->tree->_db->Execute($sql);
1134 } else {
1135 $sql = "UPDATE documents SET docdate = $docdate, " .
1136 "list_id = '$issue_id' " .
1137 "WHERE id = '$document_id'";
1138 $this->tree->_db->Execute($sql);
1140 $messages .= xl('Document date and issue updated successfully') . "<br>";
1143 $this->_state = false;
1144 $this->assign("messages", $messages);
1145 return $this->view_action($patient_id, $document_id);
1148 function list_action($patient_id = "")
1150 $this->_last_node = null;
1151 $categories_list = $this->tree->_get_categories_array($patient_id);
1152 //print_r($categories_list);
1154 $menu = new HTML_TreeMenu();
1155 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1156 $menu->addItem($rnode);
1157 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));
1158 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1159 $this->assign("tree_html", $treeMenu->toHTML());
1161 $is_new = isset($_GET['patient_name']) ? 1 : false;
1162 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1163 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1164 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1165 if ($cur_pid == '00') {
1166 $cur_pid = '0';
1167 $is_new = 1;
1169 $this->assign('is_new', $is_new);
1170 $this->assign('place_hld', $place_hld);
1171 $this->assign('cur_pid', $cur_pid);
1172 $this->assign('used_msg', $used_msg);
1173 $this->assign('demo_pid', $_SESSION['pid']);
1175 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1178 /* This is a recursive function to rename a file to something that doesn't already exist.
1179 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1180 * at end) to ensure documents opened correctly by external browser viewers. If the
1181 * counter is at the end of the file, then will use it (to continue to work with older
1182 * files), however all new counters will be placed within filenames.
1184 * Modified to only deal with base file name when renaming, to avoid issues with directory
1185 * names with dots.
1187 function _rename_file($fname, $self = false)
1189 // Allow same routine for new file name check
1190 if (!file_exists($fname)) {
1191 return($fname);
1194 $path = dirname($fname);
1195 $file = basename_international($fname);
1197 $fparts = explode(".", $file);
1198 switch (count($fparts)) {
1199 case 1:
1200 // Has a single node (base file name). Create counter node with value 0
1201 $fparts[1] = '1';
1202 break;
1203 case 2:
1204 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1205 if (is_numeric($fparts[1])) {
1206 $fparts[1] += 1;
1207 } else {
1208 array_push($fparts, $fparts[1]);
1209 $fparts[1] = '1';
1211 break;
1212 default:
1213 // Multiple nodes
1214 $ix_end = count($fparts) - 1;
1215 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1216 // Switch old style to new and check again
1217 $wrk = $fparts[$ix_end - 1];
1218 $fparts[$ix_end - 1] = $fparts[$ix_end];
1219 $fparts[$ix_end] = $wrk;
1220 } else if (is_numeric($fparts[$ix_end - 1])) {
1221 $fparts[$ix_end - 1] += 1;
1222 } else {
1223 array_push($fparts, $fparts[$ix_end]);
1224 $fparts[$ix_end] = '1';
1226 break;
1229 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1231 if (file_exists($fname)) {
1232 return $this->_rename_file($fname, true);
1233 } else {
1234 return($fname);
1238 function &_array_recurse($array, $categories = array())
1240 if (!is_array($array)) {
1241 $array = array();
1243 $node = &$this->_last_node;
1244 $current_node = &$node;
1245 $expandedIcon = 'folder-expanded.gif';
1246 foreach ($array as $id => $ar) {
1247 $icon = 'folder.gif';
1248 if (is_array($ar) || !empty($id)) {
1249 if ($node == null) {
1250 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1251 $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));
1252 $this->_last_node = &$rnode;
1253 $node = &$rnode;
1254 $current_node = &$rnode;
1255 } else {
1256 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1257 $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)));
1258 $current_node = &$this->_last_node;
1261 $this->_array_recurse($ar, $categories);
1262 } else {
1263 if ($id === 0 && !empty($ar)) {
1264 $info = $this->tree->get_node_info($id);
1265 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1266 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1267 } else {
1268 //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
1269 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1270 if ($id !== 0 && is_object($node)) {
1271 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1272 $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)));
1277 // If there are documents in this document category, then add their
1278 // attributes to the current node.
1279 $icon = "file3.png";
1280 if (is_array($categories[$id])) {
1281 foreach ($categories[$id] as $doc) {
1282 $link = $this->_link("view") . "doc_id=" . urlencode($doc['document_id']) . "&";
1283 // If user has no access then there will be no link.
1284 if (!acl_check_aco_spec($doc['aco_spec'])) {
1285 $link = '';
1287 if ($this->tree->get_node_name($id) == "CCR") {
1288 $current_node->addItem(new HTML_TreeNode(array(
1289 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1290 'link' => $link,
1291 'icon' => $icon,
1292 'expandedIcon' => $expandedIcon,
1293 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1294 )));
1295 } elseif ($this->tree->get_node_name($id) == "CCD") {
1296 $current_node->addItem(new HTML_TreeNode(array(
1297 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1298 'link' => $link,
1299 'icon' => $icon,
1300 'expandedIcon' => $expandedIcon,
1301 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . attr_url($doc['document_id']) . "','_blank');")
1302 )));
1303 } else {
1304 $current_node->addItem(new HTML_TreeNode(array(
1305 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1306 'link' => $link,
1307 'icon' => $icon,
1308 'expandedIcon' => $expandedIcon
1309 )));
1314 return $node;
1317 //function for logging the errors in writing file to CouchDB/Hard Disk
1318 function document_upload_download_log($patientid, $content)
1320 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1321 $log_file = 'log.txt';
1322 if (!is_dir($log_path)) {
1323 mkdir($log_path, 0777, true);
1326 $LOG = file_get_contents($log_path.$log_file);
1328 if ($this->cryptoGen->cryptCheckStandard($LOG)) {
1329 $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');
1332 $LOG .= $content;
1334 if (!empty($LOG)) {
1335 if ($GLOBALS['drive_encryption']) {
1336 $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');
1338 file_put_contents($log_path.$log_file, $LOG);
1342 function document_send($email, $body, $attfile, $pname)
1344 if (empty($email)) {
1345 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1346 return;
1349 $desc = "Please check the attached patient document.\n Content:".$body;
1350 $mail = new MyMailer();
1351 $from_name = $GLOBALS["practice_return_email_path"];
1352 $from = $GLOBALS["practice_return_email_path"];
1353 $mail->AddReplyTo($from, $from_name);
1354 $mail->SetFrom($from, $from);
1355 $to = $email ;
1356 $to_name =$email;
1357 $mail->AddAddress($to, $to_name);
1358 $subject = "Patient documents";
1359 $mail->Subject = $subject;
1360 $mail->Body = $desc;
1361 $mail->AddAttachment($attfile);
1362 if ($mail->Send()) {
1363 $retstatus = "email_sent";
1364 } else {
1365 $email_status = $mail->ErrorInfo;
1366 //echo "EMAIL ERROR: ".$email_status;
1367 $retstatus = "email_fail";
1371 //place to hold optional code
1372 //$first_node = array_keys($t->tree);
1373 //$first_node = $first_node[0];
1374 //$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')"));
1376 //$this->_last_node = &$node1;
1378 // Function to tag a document to an encounter.
1379 function tag_action_process($patient_id = "", $document_id)
1381 if ($_POST['process'] != "true") {
1382 die("process is '" . text($_POST['process']) . "', expected 'true'");
1383 return;
1386 // Create Encounter and Tag it.
1387 $event_date = date('Y-m-d H:i:s');
1388 $encounter_id = $_POST['encounter_id'];
1389 $encounter_check = $_POST['encounter_check'];
1390 $visit_category_id = $_POST['visit_category_id'];
1392 if (is_numeric($document_id)) {
1393 $messages = '';
1394 $d = new Document($document_id);
1395 $file_name = $d->get_url_file();
1396 if (!is_numeric($encounter_id)) {
1397 $encounter_id = 0;
1400 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1401 if ($encounter_check) {
1402 $provider_id = $_SESSION['authUserID'] ;
1404 // Get the logged in user's facility
1405 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1406 $username = $facilityRow['username'];
1407 $facility = $facilityRow['facility'];
1408 $facility_id = $facilityRow['facility_id'];
1409 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1410 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1411 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1413 $conn = $GLOBALS['adodb']['db'];
1414 $encounter = $conn->GenID("sequences");
1415 $query = "INSERT INTO form_encounter SET
1416 date = ?,
1417 reason = ?,
1418 facility = ?,
1419 sensitivity = 'normal',
1420 pc_catid = ?,
1421 facility_id = ?,
1422 billing_facility = ?,
1423 provider_id = ?,
1424 pid = ?,
1425 encounter = ?";
1426 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1427 $formID = sqlInsert($query, $bindArray);
1428 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1429 $d->set_encounter_id($encounter);
1430 $this->image_result_indication($d->id, $encounter);
1431 } else {
1432 $d->set_encounter_id($encounter_id);
1433 $this->image_result_indication($d->id, $encounter_id);
1435 $d->set_encounter_check($encounter_check);
1436 $d->persist();
1438 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1441 $this->_state = false;
1442 $this->assign("messages", $messages);
1444 return $this->view_action($patient_id, $document_id);
1447 function image_procedure_action($patient_id = "", $document_id)
1450 $img_procedure_id = $_POST['image_procedure_id'];
1451 $proc_code = $_POST['procedure_code'];
1453 if (is_numeric($document_id)) {
1454 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1455 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1456 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1457 if ($img_report_id == 0) {
1458 $report_date = date('Y-m-d H:i:s');
1459 $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));
1462 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1463 if (empty($img_result)) {
1464 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));
1467 $this->image_result_indication($document_id, 0, $img_procedure_id);
1469 return $this->view_action($patient_id, $document_id);
1472 function clear_procedure_tag_action($patient_id = "", $document_id)
1474 if (is_numeric($document_id)) {
1475 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1477 return $this->view_action($patient_id, $document_id);
1480 function get_mapped_procedure($document_id)
1482 $map = array();
1483 if (is_numeric($document_id)) {
1484 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1485 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1486 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1487 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1488 where pres.document_id = ?", array($document_id));
1490 return $map;
1493 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1495 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1496 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1498 if ($encounter != 0) {
1499 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1500 } else if ($image_procedure_id != 0) {
1501 $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));
1502 } else {
1503 $ep = array('assigned_to' => $_SESSION['authUser']);
1506 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1507 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1508 setGpRelation(1, $doc_id, 6, $noteid);
1511 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1512 * Also usable for documents that may of been moved to different patients.
1514 * @param string $url - Current url string from database.
1515 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1516 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1518 * @return string
1520 function _check_relocation($url, $new_pid = null, $new_name = null)
1522 //strip url of protocol handler
1523 $url = preg_replace("|^(.*)://|", "", $url);
1524 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1525 while (current($fsnodes) != "documents") {
1526 array_shift($fsnodes);
1528 if ($new_pid) {
1529 $fsnodes[1] = $new_pid;
1531 if ($new_name) {
1532 $fsnodes[count($fsnodes)-1] = $new_name;
1534 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1535 // Make sure the url is available after corrections
1536 if ($new_pid || $new_name) {
1537 $url = $this->_rename_file($url);
1539 //Add full path and remaining nodes
1540 return $url;
1543 //clear encounter tag function
1544 function clear_encounter_tag_action($patient_id = "", $document_id)
1546 if (is_numeric($document_id)) {
1547 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1549 return $this->view_action($patient_id, $document_id);