2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once(dirname(__FILE__
) . "/../library/forms.inc");
8 require_once(dirname(__FILE__
) . "/../library/crypto.php");
10 use OpenEMR\Services\FacilityService
;
11 use OpenEMR\Services\PatientService
;
13 class C_Document
extends Controller
18 var $document_categories;
21 var $manual_set_owner=false; // allows manual setting of a document owner/service
25 function __construct($template_mod = "general")
27 parent
::__construct();
28 $this->facilityService
= new FacilityService();
29 $this->patientService
= new PatientService();
30 $this->documents
= array();
31 $this->template_mod
= $template_mod;
32 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . attr($_SERVER['QUERY_STRING']));
33 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
35 //get global config options for this namespace
36 $this->_config
= $GLOBALS['oer_config']['documents'];
38 $this->_args
= array("patient_id" => $_GET['patient_id']);
40 $this->assign("STYLE", $GLOBALS['style']);
41 $t = new CategoryTree(1);
44 $this->Document
= new Document();
47 function upload_action($patient_id, $category_id)
49 $category_name = $this->tree
->get_node_name($category_id);
50 $this->assign("category_id", $category_id);
51 $this->assign("category_name", $category_name);
52 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
53 $this->assign("patient_id", $patient_id);
55 // Added by Rod to support document template download from general_upload.html.
56 // Cloned from similar stuff in manage_document_templates.php.
57 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
58 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
59 if (file_exists($templatedir)) {
60 $dh = opendir($templatedir);
63 $templateslist = array();
64 while (false !== ($sfname = readdir($dh))) {
65 if (substr($sfname, 0, 1) == '.') {
68 $templateslist[$sfname] = $sfname;
71 ksort($templateslist);
72 foreach ($templateslist as $sfname) {
73 $templates_options .= "<option value='" . attr($sfname) .
74 "'>" . text($sfname) . "</option>";
77 $this->assign("TEMPLATES_LIST", $templates_options);
79 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
80 $this->assign("activity", $activity);
81 return $this->list_action($patient_id);
84 //Upload multiple files on single click
85 function upload_action_process()
88 // Collect a manually set owner if this has been set
89 // Used when want to manually assign the owning user/service such as the Direct mechanism
90 $non_HTTP_owner=false;
91 if ($this->manual_set_owner
) {
92 $non_HTTP_owner=$this->manual_set_owner
;
97 if ($GLOBALS['document_storage_method']==0) {
100 if ($GLOBALS['document_storage_method']==1) {
104 if ($_POST['process'] != "true") {
108 $doDecryption = false;
109 $encrypted = $_POST['encrypted'];
110 $passphrase = $_POST['passphrase'];
111 if (!$GLOBALS['hide_document_encryption'] &&
112 $encrypted && $passphrase ) {
113 $doDecryption = true;
116 if (is_numeric($_POST['category_id'])) {
117 $category_id = $_POST['category_id'];
121 if (isset($_GET['patient_id']) && !$couchDB) {
122 $patient_id = $_GET['patient_id'];
123 } else if (is_numeric($_POST['patient_id'])) {
124 $patient_id = $_POST['patient_id'];
127 $sentUploadStatus = array();
128 if (count($_FILES['file']['name']) > 0) {
131 foreach ($_FILES['file']['name'] as $key => $value) {
134 if ($_FILES['file']['error'][$key] > 0 ||
empty($fname) ||
$_FILES['file']['size'][$key] == 0) {
137 $fname = htmlentities("<empty>");
139 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
140 if ($_FILES['file']['size'][$key] == 0) {
141 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
143 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
144 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
146 // Test for a zip of DICOM images
147 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
148 $za = new ZipArchive();
149 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
151 $mimetype = "application/dicom+zip";
152 for ($i = 0; $i < $za->numFiles
; $i++
) {
153 $stat = $za->statIndex($i);
154 $fp = $za->getStream($stat['name']);
156 $head = fread($fp, 256);
158 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
159 $mimetype = "application/zip";
163 // if here -then a DICOM
164 $parts = pathinfo($stat['name']);
165 if (strtolower($parts['extension']) != "dcm") { // require extension for viewer
166 $new_name = $stat['name'] . ".dcm";
167 $za->renameIndex($i, $new_name); // only use index rename!
169 } else { // Rarely here
170 $mimetype = "application/zip";
175 if ($mimetype == "application/dicom+zip") {
176 $_FILES['file']['type'][$key] = $mimetype;
177 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
178 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
182 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
183 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
186 $filetext = $this->decrypt($filetext, $passphrase);
188 if ($_POST['destination'] != '') {
189 $fname = $_POST['destination'];
191 // set mime, test for single DICOM and assign extension if missing.
192 $mimetype = $_FILES['file']['type'][$key];
193 if (strpos($filetext, 'DICM') !== false) {
194 $mimetype = 'application/dicom';
195 $parts = pathinfo($fname);
196 if (!$parts['extension']) {
201 $rc = $d->createDocument(
207 empty($_GET['higher_level_path']) ?
'' : $_GET['higher_level_path'],
208 empty($_POST['path_depth']) ?
1 : $_POST['path_depth'],
210 $_FILES['file']['tmp_name'][$key]
213 $error .= $rc . "\n";
215 $this->assign("upload_success", "true");
217 $sentUploadStatus[] = $d;
218 $this->assign("file", $sentUploadStatus);
221 // Option to run a custom plugin for each file upload.
222 // This was initially created to delete the original source file in a custom setting.
223 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
224 if (file_exists($upload_plugin)) {
225 include_once($upload_plugin);
227 $upload_plugin_pp = 'documentUploadPostProcess';
228 if (function_exists($upload_plugin_pp)) {
229 $tmp = call_user_func($upload_plugin_pp, $value, $d);
234 // Following is just an example of code in such a plugin file.
235 /*****************************************************
236 function documentUploadPostProcess($filename, &$d) {
237 $userid = $_SESSION['authUserID'];
238 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
239 $owner = strtolower($row['username']);
240 $dn = '1_' . ucfirst($owner);
241 $filepath = "/shared_network_directory/$dn/$filename";
242 if (@unlink($filepath)) return '';
243 return "Failed to delete '$filepath'.";
245 *****************************************************/
249 $this->assign("error", nl2br($error));
250 //$this->_state = false;
251 $_POST['process'] = "";
252 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
255 function note_action_process($patient_id)
257 // this function is a dual function that will set up a note associated with a document or send a document via email.
259 if ($_POST['process'] != "true") {
264 $n->set_owner($_SESSION['authUserID']);
265 parent
::populate_object($n);
266 if ($_POST['identifier'] == "no") {
267 // associate a note with a document
269 } elseif ($_POST['identifier'] == "yes") {
270 // send the document via email
271 $d = new Document($_POST['foreign_id']);
272 $url = $d->get_url();
273 $storagemethod = $d->get_storagemethod();
274 $couch_docid = $d->get_couch_docid();
275 $couch_revid = $d->get_couch_revid();
276 if ($couch_docid && $couch_revid) {
277 $couch = new CouchDB();
278 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
279 $resp = $couch->retrieve_doc($data);
280 $content = $resp->data
;
281 if ($content=='' && $GLOBALS['couchdb_log']==1) {
282 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
283 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
284 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
285 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
286 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
287 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
288 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
289 die(xlt("File retrieval from CouchDB failed"));
291 // place it in a temporary file and will remove the file below after emailed
292 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
293 $fh = fopen($temp_couchdb_url, "w");
294 fwrite($fh, base64_decode($content));
296 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
298 $url = preg_replace("|^(.*)://|", "", $url);
299 // Collect filename and path
300 $from_all = explode("/", $url);
301 $from_filename = array_pop($from_all);
302 $from_pathname_array = array();
303 for ($i=0; $i<$d->get_path_depth(); $i++
) {
304 $from_pathname_array[] = array_pop($from_all);
306 $from_pathname_array = array_reverse($from_pathname_array);
307 $from_pathname = implode("/", $from_pathname_array);
308 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
310 if (!file_exists($temp_url)) {
311 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;
314 $pdetails = getPatientData($patient_id);
315 $pname = $pdetails['fname']." ".$pdetails['lname'];
316 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
317 if ($couch_docid && $couch_revid) {
318 // remove the temporary couchdb file
319 unlink($temp_couchdb_url);
322 $this->_state
= false;
323 $_POST['process'] = "";
324 return $this->view_action($patient_id, $n->get_foreign_id());
327 function default_action()
329 return $this->list_action();
332 function view_action($patient_id = "", $doc_id)
334 // Added by Rod to support document delete:
335 global $gacl_object, $phpgacl_location;
338 require_once(dirname(__FILE__
) . "/../library/acl.inc");
339 require_once(dirname(__FILE__
) . "/../library/lists.inc");
341 $d = new Document($doc_id);
342 $notes = $d->get_notes();
344 $this->assign("csrf_token_form", collectCsrfToken());
346 $this->assign("file", $d);
347 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
348 $this->assign("NOTE_ACTION", $this->_link("note"));
349 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
350 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
351 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
352 $this->assign("webroot", $GLOBALS['webroot']);
354 // Added by Rod to support document delete:
356 if (acl_check('patients', 'docs_rm')) {
357 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
358 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
360 $this->assign("delete_string", $delete_string);
361 $this->assign("REFRESH_ACTION", $this->_link("list"));
363 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
364 "document_id=" . $d->get_id() . "&process=true");
366 // Added by Rod to support document date update:
367 $this->assign("DOCDATE", $d->get_docdate());
368 $this->assign("UPDATE_ACTION", $this->_link("update") .
369 "document_id=" . $d->get_id() . "&process=true");
371 // Added by Rod to support document issue update:
372 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
373 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
374 "pid = ? " . // AND enddate IS NULL " .
375 "ORDER BY type, begdate", array($patient_id));
376 while ($irow = sqlFetchArray($ires)) {
377 $desc = $irow['type'];
378 if ($ISSUE_TYPES[$desc]) {
379 $desc = $ISSUE_TYPES[$desc][2];
381 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
382 $sel = ($irow['id'] == $d->get_list_id()) ?
' selected' : '';
383 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
385 $this->assign("ISSUES_LIST", $issues_options);
387 // For tagging to encounter
388 // Populate the dropdown with patient's encounter list
389 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
390 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
391 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
392 "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));
393 if (sqlNumRows($result_docs) > 0) {
394 while ($row_result_docs = sqlFetchArray($result_docs)) {
395 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ?
' selected' : '';
396 $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>";
399 $this->assign("ENC_LIST", $encOptions);
401 //clear encounter tag
402 if ($d->get_encounter_id() != 0) {
403 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
405 $this->assign('clear_encounter_tag', 'javascript:void(0)');
408 //Populate the dropdown with category list
409 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
410 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
411 while ($crow = sqlFetchArray($cres)) {
412 $catid = $crow['pc_catid'];
413 if ($catid < 9 && $catid != 5) {
414 continue; // Applying same logic as in new encounter page.
416 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
418 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
420 $this->assign("notes", $notes);
422 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
423 // Populate the dropdown with image procedure order list
424 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
425 $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));
426 $mapping = $this->get_mapped_procedure($d->get_id());
427 if (sqlNumRows($imgOrders) > 0) {
428 while ($row = sqlFetchArray($imgOrders)) {
430 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
431 $sel_proc = 'selected';
433 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
437 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
439 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
441 $this->_last_node
= null;
443 $menu = new HTML_TreeMenu();
445 //pass an empty array because we don't want the documents for each category showing up in this list box
446 $rnode = $this->_array_recurse($this->tree
->tree
, array());
447 $menu->addItem($rnode);
448 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
450 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
452 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_view.html");
453 $this->assign("activity", $activity);
455 return $this->list_action($patient_id);
458 function encrypt($plaintext, $key)
460 return aes256Encrypt($plaintext, $key, false);
463 function decrypt($crypttext, $key)
465 return aes256Decrypt($crypttext, $key, false);
469 * Retrieve file from hard disk / CouchDB.
470 * In case that file isn't download this function will return thumbnail image (if exist).
471 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
472 * @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.
474 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
476 $encrypted = $_POST['encrypted'];
477 $passphrase = $_POST['passphrase'];
478 $doEncryption = false;
479 if (!$GLOBALS['hide_document_encryption'] &&
480 $encrypted == "true" &&
482 $doEncryption = true;
485 //controller function ruins booleans, so need to manually re-convert to booleans
486 if ($as_file == "true") {
488 } else if ($as_file == "false") {
491 if ($original_file == "true") {
493 } else if ($original_file == "false") {
494 $original_file=false;
496 if ($disable_exit == "true") {
498 } else if ($disable_exit == "false") {
501 if ($show_original == "true") {
503 } else if ($show_original == "false") {
504 $show_original=false;
508 case "patient_picture":
509 $this->patientService
->setPid($patient_id);
510 $document_id = $this->patientService
->getPatientPictureDocumentId();
514 $d = new Document($document_id);
515 $url = $d->get_url();
516 $th_url = $d->get_thumb_url();
518 $storagemethod = $d->get_storagemethod();
519 $couch_docid = $d->get_couch_docid();
520 $couch_revid = $d->get_couch_revid();
522 if ($couch_docid && $couch_revid && $original_file) {
523 $couch = new CouchDB();
524 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
525 $resp = $couch->retrieve_doc($data);
526 //Take thumbnail file when is not null and file is presented online
527 if (!$as_file && !is_null($th_url) && !$show_original) {
528 $content = $resp->th_data
;
530 $content = $resp->data
;
532 if ($content=='' && $GLOBALS['couchdb_log']==1) {
533 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
534 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
535 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
536 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
537 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
538 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
539 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
540 die(xl("File retrieval from CouchDB failed"));
542 if ($disable_exit == true) {
543 return base64_decode($content);
545 header('Content-Description: File Transfer');
546 header('Content-Transfer-Encoding: binary');
547 header('Expires: 0');
548 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
549 header('Pragma: public');
550 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
551 $fh = fopen($tmpcouchpath, "w");
552 fwrite($fh, base64_decode($content));
554 $f = fopen($tmpcouchpath, "r");
556 $filetext = fread($f, filesize($tmpcouchpath));
557 $ciphertext = $this->encrypt($filetext, $passphrase);
558 $tmpfilepath = $GLOBALS['temporary_files_dir'];
559 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
560 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
561 fwrite($tmpfile, $ciphertext);
563 header('Content-Disposition: attachment; filename='.$tmpfilename);
564 header("Content-Type: application/octet-stream");
565 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
568 readfile($tmpfilepath.$tmpfilename);
569 unlink($tmpfilepath.$tmpfilename);
571 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
572 header("Content-Type: " . $d->get_mimetype());
573 header("Content-Length: " . filesize($tmpcouchpath));
578 unlink($tmpcouchpath);
580 exit;//exits only if file download from CouchDB is successfull.
583 //Take thumbnail file when is not null and file is presented online
584 if (!$as_file && !is_null($th_url) && !$show_original) {
588 //strip url of protocol handler
589 $url = preg_replace("|^(.*)://|", "", $url);
591 //change full path to current webroot. this is for documents that may have
592 //been moved from a different filesystem and the full path in the database
593 //is not current. this is also for documents that may of been moved to
594 //different patients. Note that the path_depth is used to see how far down
595 //the path to go. For example, originally the path_depth was always 1, which
596 //only allowed things like documents/1/<file>, but now can have more structured
597 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
599 // NOTE that $from_filename and basename($url) are the same thing
600 $from_all = explode("/", $url);
601 $from_filename = array_pop($from_all);
602 $from_pathname_array = array();
603 for ($i=0; $i<$d->get_path_depth(); $i++
) {
604 $from_pathname_array[] = array_pop($from_all);
606 $from_pathname_array = array_reverse($from_pathname_array);
607 $from_pathname = implode("/", $from_pathname_array);
608 if ($couch_docid && $couch_revid) {
609 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
610 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
612 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
615 if (file_exists($temp_url)) {
620 if (!file_exists($url)) {
621 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;
623 if ($original_file) {
624 //normal case when serving the file referenced in database
625 if ($disable_exit == true) {
626 $f = fopen($url, "r");
627 $filetext = fread($f, filesize($url));
630 header('Content-Description: File Transfer');
631 header('Content-Transfer-Encoding: binary');
632 header('Expires: 0');
633 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
634 header('Pragma: public');
636 $f = fopen($url, "r");
639 $filetext = fread($f, filesize($url));
640 $ciphertext = $this->encrypt($filetext, $passphrase);
641 $tmpfilepath = $GLOBALS['temporary_files_dir'];
642 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
643 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
644 fwrite($tmpfile, $ciphertext);
646 header('Content-Disposition: attachment; filename='.$tmpfilename);
647 header("Content-Type: application/octet-stream");
648 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
651 readfile($tmpfilepath.$tmpfilename);
652 unlink($tmpfilepath.$tmpfilename);
655 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
656 header("Content-Type: " . $d->get_mimetype());
657 header("Content-Length: " . filesize($url));
663 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
664 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
665 if ($couch_docid && $couch_revid) {
666 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
668 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
670 if ($disable_exit == true) {
673 header("Pragma: public");
674 header("Expires: 0");
675 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
676 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
677 header("Content-Type: image/jpeg");
678 header("Content-Length: " . filesize($url));
679 $f = fopen($url, "r");
681 if ($couch_docid && $couch_revid) {
684 $url=str_replace("_converted.jpg", '.pdf', $url);
692 function queue_action($patient_id = "")
694 $messages = $this->_tpl_vars
['messages'];
695 $queue_files = array();
697 //see if the repository exists and it is a directory else error
698 if (file_exists($this->_config
['repository']) && is_dir($this->_config
['repository'])) {
699 $dir = opendir($this->_config
['repository']);
700 //read each entry in the directory
701 while (($file = readdir($dir)) !== false) {
702 //concat the filename and path
703 $file = $this->_config
['repository'] .$file;
704 $file_info = array();
705 //if the filename is a file get its info and put into a tmp array
706 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
707 $file_info['filename'] = basename_international($file);
708 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
709 $d = $this->Document
->document_factory_url("file://" . $file);
710 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
711 $file_info['patient_id'] = $patient_match[1];
712 $file_info['document_id'] = $d->get_id();
713 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
715 //merge the tmp array into the larger array
716 $queue_files[] = $file_info;
721 $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";
725 $this->assign("queue_files", $queue_files);
726 $this->_last_node
= null;
728 $menu = new HTML_TreeMenu();
730 //pass an empty array because we don't want the documents for each category showing up in this list box
731 $rnode = $this->_array_recurse($this->tree
->tree
, array());
732 $menu->addItem($rnode);
733 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
735 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
737 $this->assign("messages", nl2br($messages));
738 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_queue.html");
741 function queue_action_process()
743 if ($_POST['process'] != "true") {
747 $messages = $this->_tpl_vars
['messages'];
749 //build a category tree so we can have a list of category ids that are valid
750 $ct = new CategoryTree(1);
751 $categories = $ct->_id_name
;
753 //see if there were and posted files and assign them
755 is_array($_POST['files']) ?
$files = $_POST['files']: $files = array();
757 //loop through posted files
758 foreach ($files as $doc_id => $file) {
759 //only operate on files checked as active
760 if (!$file['active']) {
764 //run basic validation checks
765 if (!is_numeric($file['patient_id']) ||
!is_numeric($file['category_id']) ||
!is_numeric($doc_id)) {
766 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
770 //validate that the pod exists
771 $d = new Document($doc_id);
772 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
773 $result = $d->_db
->Execute($sql);
775 if (!$result ||
$result->EOF
) {
776 //patient id does not exist
777 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
781 //validate that the category id exists
782 if (!isset($categories[$file['category_id']])) {
783 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
787 //now do the work of moving the file
788 $new_path = $this->_config
['repository'] . $file['patient_id'] ."/";
790 //see if the patient dir exists in the repository and create if not
791 if (!file_exists($new_path)) {
792 if (!mkdir($new_path, 0700)) {
793 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
798 //fname is the name of the file after it is moved
799 $fname = $file['name'];
801 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
802 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
803 if ($patient_match[1] == $file['patient_id']) {
804 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
807 //filenames should not have funny chars
808 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
810 //see if there is an existing file with the same name and rename as necessary
811 if (file_exists($new_path.$file['name'])) {
812 $messages .= "File with same name already exists at location: " . $new_path . "\n";
813 $fname = basename_international($this->_rename_file($new_path.$file['name']));
814 $messages .= "Current file name was changed to " . $fname ."\n";
818 if (rename($this->_config
['repository'].$file['name'], $new_path.$fname)) {
819 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
820 $d->url
= "file://" .$new_path.$fname;
821 $d->set_foreign_id($file['patient_id']);
822 $d->set_mimetype($mimetype);
826 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
827 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
828 $d->_db
->Execute($sql);
831 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
834 $this->assign("messages", $messages);
835 $_POST['process'] = "";
838 function move_action_process($patient_id = "", $document_id)
840 if ($_POST['process'] != "true") {
844 $new_category_id = $_POST['new_category_id'];
845 $new_patient_id = $_POST['new_patient_id'];
847 //move to new category
848 if (is_numeric($new_category_id) && is_numeric($document_id)) {
849 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
850 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
852 $this->tree
->_db
->Execute($sql);
855 //move to new patient
856 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
857 $d = new Document($document_id);
858 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
859 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
860 $result = $d->_db
->Execute($sql);
862 if (!$result ||
$result->EOF
) {
863 //patient id does not exist
864 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
866 $couchsavefailed = !$d->change_patient($new_patient_id);
868 $this->_state
= false;
869 if (!$couchsavefailed) {
870 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
872 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
874 $this->assign("messages", $messages);
875 return $this->list_action($patient_id);
877 } //in this case return the document to the queue instead of moving it
878 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
879 $d = new Document($document_id);
880 $new_path = $this->_config
['repository'];
881 $fname = $d->get_url_file();
883 //see if there is an existing file with the same name and rename as necessary
884 if (file_exists($new_path.$d->get_url_file())) {
885 $messages .= "File with same name already exists in the queue.\n";
886 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
887 $messages .= "Current file name was changed to " . $fname ."\n";
891 if (rename($d->get_url_filepath(), $new_path.$fname)) {
892 $d->url
= "file://" .$new_path.$fname;
893 $d->set_foreign_id("");
898 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db
->qstr($document_id);
899 $d->_db
->Execute($sql);
900 $messages .= "Document returned to queue successfully.\n";
902 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
905 $this->_state
= false;
906 $this->assign("messages", $messages);
907 return $this->list_action($patient_id);
910 $this->_state
= false;
911 $this->assign("messages", $messages);
912 return $this->view_action($patient_id, $document_id);
915 function validate_action_process($patient_id = "", $document_id)
918 $d = new Document($document_id);
919 if ($d->couch_docid
&& $d->couch_revid
) {
920 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
921 $url = $file_path.$d->get_url();
922 $couch = new CouchDB();
923 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid
);
924 $resp = $couch->retrieve_doc($data);
925 $content = $resp->data
;
926 //--------Temporarily writing the file for calculating the hash--------//
927 //-----------Will be removed after calculating the hash value----------//
928 $temp_file = fopen($url, "w");
929 fwrite($temp_file, base64_decode($content));
932 $url = $d->get_url();
934 //strip url of protocol handler
935 $url = preg_replace("|^(.*)://|", "", $url);
937 //change full path to current webroot. this is for documents that may have
938 //been moved from a different filesystem and the full path in the database
939 //is not current. this is also for documents that may of been moved to
940 //different patients. Note that the path_depth is used to see how far down
941 //the path to go. For example, originally the path_depth was always 1, which
942 //only allowed things like documents/1/<file>, but now can have more structured
943 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
945 // NOTE that $from_filename and basename($url) are the same thing
946 $from_all = explode("/", $url);
947 $from_filename = array_pop($from_all);
948 $from_pathname_array = array();
949 for ($i=0; $i<$d->get_path_depth(); $i++
) {
950 $from_pathname_array[] = array_pop($from_all);
952 $from_pathname_array = array_reverse($from_pathname_array);
953 $from_pathname = implode("/", $from_pathname_array);
954 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
955 if (file_exists($temp_url)) {
959 if ($_POST['process'] != "true") {
960 die("process is '" . $_POST['process'] . "', expected 'true'");
964 $d = new Document($document_id);
965 $current_hash = sha1_file($url);
966 $messages = xl('Current Hash').": ".$current_hash."<br>";
967 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
968 if ($d->get_hash() == '') {
969 $d->hash
= $current_hash;
972 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
973 } else if ($current_hash != $d->get_hash()) {
974 $messages .= xl('Hash does not match. Data integrity has been compromised.');
976 $messages .= xl('Document passed integrity check.');
978 $this->_state
= false;
979 $this->assign("messages", $messages);
980 if ($d->couch_docid
&& $d->couch_revid
) {
981 //Removing the temporary file which is used to create the hash
982 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
984 return $this->view_action($patient_id, $document_id);
987 // Added by Rod for metadata update.
989 function update_action_process($patient_id = "", $document_id)
992 if ($_POST['process'] != "true") {
993 die("process is '" . $_POST['process'] . "', expected 'true'");
997 $docdate = $_POST['docdate'];
998 $docname = $_POST['docname'];
999 $issue_id = $_POST['issue_id'];
1001 if (is_numeric($document_id)) {
1003 $d = new Document($document_id);
1004 $file_name = $d->get_url_file();
1005 if ($docname != '' &&
1006 $docname != $file_name ) {
1007 // Ready to rename - check for relocation
1008 $old_url = $this->_check_relocation($d->get_url());
1009 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1010 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
1011 if (rename($old_url, $new_url)) {
1012 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1013 if (file_exists($old_url)) {
1019 $messages .= xl('Document successfully renamed.')."<br>";
1021 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1025 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1026 $docdate = "'$docdate'";
1030 if (!is_numeric($issue_id)) {
1033 $couch_docid = $d->get_couch_docid();
1034 $couch_revid = $d->get_couch_revid();
1035 if ($couch_docid && $couch_revid) {
1036 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1037 "list_id = '$issue_id' " .
1038 "WHERE id = '$document_id'";
1039 $this->tree
->_db
->Execute($sql);
1041 $sql = "UPDATE documents SET docdate = $docdate, " .
1042 "list_id = '$issue_id' " .
1043 "WHERE id = '$document_id'";
1044 $this->tree
->_db
->Execute($sql);
1046 $messages .= xl('Document date and issue updated successfully') . "<br>";
1049 $this->_state
= false;
1050 $this->assign("messages", $messages);
1051 return $this->view_action($patient_id, $document_id);
1054 function list_action($patient_id = "")
1056 $this->_last_node
= null;
1057 $categories_list = $this->tree
->_get_categories_array($patient_id);
1058 //print_r($categories_list);
1060 $menu = new HTML_TreeMenu();
1061 $rnode = $this->_array_recurse($this->tree
->tree
, $categories_list);
1062 $menu->addItem($rnode);
1063 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1064 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1065 $this->assign("tree_html", $treeMenu->toHTML());
1067 $is_new = isset($_GET['patient_name']) ?
1 : false;
1068 $place_hld = isset($_GET['patient_name']) ?
filter_input(INPUT_GET
, 'patient_name') : xl("Patient search or select.");
1069 $cur_pid = isset($_GET['patient_id']) ?
filter_input(INPUT_GET
, 'patient_id') : '';
1070 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1071 if ($cur_pid == '00') {
1075 $this->assign('is_new', $is_new);
1076 $this->assign('place_hld', $place_hld);
1077 $this->assign('cur_pid', $cur_pid);
1078 $this->assign('used_msg', $used_msg);
1079 $this->assign('demo_pid', $_SESSION['pid']);
1081 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
1084 /* This is a recursive function to rename a file to something that doesn't already exist.
1085 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1086 * at end) to ensure documents opened correctly by external browser viewers. If the
1087 * counter is at the end of the file, then will use it (to continue to work with older
1088 * files), however all new counters will be placed within filenames.
1090 * Modified to only deal with base file name when renaming, to avoid issues with directory
1093 function _rename_file($fname, $self = false)
1095 // Allow same routine for new file name check
1096 if (!file_exists($fname)) {
1100 $path = dirname($fname);
1101 $file = basename_international($fname);
1103 $fparts = explode(".", $file);
1104 switch (count($fparts)) {
1106 // Has a single node (base file name). Create counter node with value 0
1110 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1111 if (is_numeric($fparts[1])) {
1114 array_push($fparts, $fparts[1]);
1120 $ix_end = count($fparts) - 1;
1121 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1122 // Switch old style to new and check again
1123 $wrk = $fparts[$ix_end - 1];
1124 $fparts[$ix_end - 1] = $fparts[$ix_end];
1125 $fparts[$ix_end] = $wrk;
1126 } else if (is_numeric($fparts[$ix_end - 1])) {
1127 $fparts[$ix_end - 1] +
= 1;
1129 array_push($fparts, $fparts[$ix_end]);
1130 $fparts[$ix_end] = '1';
1135 $fname = $path.DIRECTORY_SEPARATOR
.join(".", $fparts);
1137 if (file_exists($fname)) {
1138 return $this->_rename_file($fname, true);
1144 function &_array_recurse($array, $categories = array())
1146 if (!is_array($array)) {
1149 $node = &$this->_last_node
;
1150 $current_node = &$node;
1151 $expandedIcon = 'folder-expanded.gif';
1152 foreach ($array as $id => $ar) {
1153 $icon = 'folder.gif';
1154 if (is_array($ar) ||
!empty($id)) {
1155 if ($node == null) {
1156 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1157 $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));
1158 $this->_last_node
= &$rnode;
1160 $current_node = &$rnode;
1162 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1163 $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)));
1164 $current_node = &$this->_last_node
;
1167 $this->_array_recurse($ar, $categories);
1169 if ($id === 0 && !empty($ar)) {
1170 $info = $this->tree
->get_node_info($id);
1171 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1172 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1174 //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
1175 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1176 if ($id !== 0 && is_object($node)) {
1177 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1178 $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)));
1183 // If there are documents in this document category, then add their
1184 // attributes to the current node.
1185 $icon = "file3.png";
1186 if (is_array($categories[$id])) {
1187 foreach ($categories[$id] as $doc) {
1188 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1189 // If user has no access then there will be no link.
1190 if (!acl_check_aco_spec($doc['aco_spec'])) {
1193 if ($this->tree
->get_node_name($id) == "CCR") {
1194 $current_node->addItem(new HTML_TreeNode(array(
1195 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1198 'expandedIcon' => $expandedIcon,
1199 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1201 } elseif ($this->tree
->get_node_name($id) == "CCD") {
1202 $current_node->addItem(new HTML_TreeNode(array(
1203 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1206 'expandedIcon' => $expandedIcon,
1207 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1210 $current_node->addItem(new HTML_TreeNode(array(
1211 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1214 'expandedIcon' => $expandedIcon
1223 //function for logging the errors in writing file to CouchDB/Hard Disk
1224 function document_upload_download_log($patientid, $content)
1226 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1227 $log_file = 'log.txt';
1228 if (!is_dir($log_path)) {
1229 mkdir($log_path, 0777, true);
1231 $LOG = fopen($log_path.$log_file, 'a');
1232 fwrite($LOG, $content);
1236 function document_send($email, $body, $attfile, $pname)
1238 if (empty($email)) {
1239 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1243 $desc = "Please check the attached patient document.\n Content:".$body;
1244 $mail = new MyMailer();
1245 $from_name = $GLOBALS["practice_return_email_path"];
1246 $from = $GLOBALS["practice_return_email_path"];
1247 $mail->AddReplyTo($from, $from_name);
1248 $mail->SetFrom($from, $from);
1251 $mail->AddAddress($to, $to_name);
1252 $subject = "Patient documents";
1253 $mail->Subject
= $subject;
1254 $mail->Body
= $desc;
1255 $mail->AddAttachment($attfile);
1256 if ($mail->Send()) {
1257 $retstatus = "email_sent";
1259 $email_status = $mail->ErrorInfo
;
1260 //echo "EMAIL ERROR: ".$email_status;
1261 $retstatus = "email_fail";
1265 //place to hold optional code
1266 //$first_node = array_keys($t->tree);
1267 //$first_node = $first_node[0];
1268 //$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')"));
1270 //$this->_last_node = &$node1;
1272 // Function to tag a document to an encounter.
1273 function tag_action_process($patient_id = "", $document_id)
1275 if ($_POST['process'] != "true") {
1276 die("process is '" . text($_POST['process']) . "', expected 'true'");
1280 // Create Encounter and Tag it.
1281 $event_date = date('Y-m-d H:i:s');
1282 $encounter_id = $_POST['encounter_id'];
1283 $encounter_check = $_POST['encounter_check'];
1284 $visit_category_id = $_POST['visit_category_id'];
1286 if (is_numeric($document_id)) {
1288 $d = new Document($document_id);
1289 $file_name = $d->get_url_file();
1290 if (!is_numeric($encounter_id)) {
1294 $encounter_check = ( $encounter_check == 'on') ?
1 : 0;
1295 if ($encounter_check) {
1296 $provider_id = $_SESSION['authUserID'] ;
1298 // Get the logged in user's facility
1299 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1300 $username = $facilityRow['username'];
1301 $facility = $facilityRow['facility'];
1302 $facility_id = $facilityRow['facility_id'];
1303 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1304 $billingFacility = $this->facilityService
->getPrimaryBusinessEntity();
1305 $billingFacilityID = ( $billingFacility['id'] ) ?
$billingFacility['id'] : $facility_id;
1307 $conn = $GLOBALS['adodb']['db'];
1308 $encounter = $conn->GenID("sequences");
1309 $query = "INSERT INTO form_encounter SET
1313 sensitivity = 'normal',
1316 billing_facility = ?,
1320 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1321 $formID = sqlInsert($query, $bindArray);
1322 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1323 $d->set_encounter_id($encounter);
1324 $this->image_result_indication($d->id
, $encounter);
1326 $d->set_encounter_id($encounter_id);
1327 $this->image_result_indication($d->id
, $encounter_id);
1329 $d->set_encounter_check($encounter_check);
1332 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1335 $this->_state
= false;
1336 $this->assign("messages", $messages);
1338 return $this->view_action($patient_id, $document_id);
1341 function image_procedure_action($patient_id = "", $document_id)
1344 $img_procedure_id = $_POST['image_procedure_id'];
1345 $proc_code = $_POST['procedure_code'];
1347 if (is_numeric($document_id)) {
1348 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1349 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1350 $img_report_id = !empty($img_report['procedure_report_id']) ?
$img_report['procedure_report_id'] : 0;
1351 if ($img_report_id == 0) {
1352 $report_date = date('Y-m-d H:i:s');
1353 $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));
1356 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1357 if (empty($img_result)) {
1358 sqlInsert("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));
1361 $this->image_result_indication($document_id, 0, $img_procedure_id);
1363 return $this->view_action($patient_id, $document_id);
1366 function clear_procedure_tag_action($patient_id = "", $document_id)
1368 if (is_numeric($document_id)) {
1369 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1371 return $this->view_action($patient_id, $document_id);
1374 function get_mapped_procedure($document_id)
1377 if (is_numeric($document_id)) {
1378 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1379 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1380 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1381 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1382 where pres.document_id = ?", array($document_id));
1387 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1389 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1390 $narration = isset($doc_notes['note']) ?
'With Narration': 'Without Narration';
1392 if ($encounter != 0) {
1393 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1394 } else if ($image_procedure_id != 0) {
1395 $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));
1397 $ep = array('assigned_to' => $_SESSION['authUser']);
1400 $encounter_provider = isset($ep['assigned_to']) ?
$ep['assigned_to'] : $_SESSION['authUser'];
1401 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1402 setGpRelation(1, $doc_id, 6, $noteid);
1405 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1406 * Also usable for documents that may of been moved to different patients.
1408 * @param string $url - Current url string from database.
1409 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1410 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1414 function _check_relocation($url, $new_pid = null, $new_name = null)
1416 //strip url of protocol handler
1417 $url = preg_replace("|^(.*)://|", "", $url);
1418 $fsnodes = explode(DIRECTORY_SEPARATOR
, $url);
1419 while (current($fsnodes) != "documents") {
1420 array_shift($fsnodes);
1423 $fsnodes[1] = $new_pid;
1426 $fsnodes[count($fsnodes)-1] = $new_name;
1428 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR
.implode(DIRECTORY_SEPARATOR
, $fsnodes);
1429 // Make sure the url is available after corrections
1430 if ($new_pid ||
$new_name) {
1431 $url = $this->_rename_file($url);
1433 //Add full path and remaining nodes
1437 //clear encounter tag function
1438 function clear_encounter_tag_action($patient_id = "", $document_id)
1440 if (is_numeric($document_id)) {
1441 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1443 return $this->view_action($patient_id, $document_id);