Compact css tweak
[openemr.git] / controllers / C_Document.class.php
blob29ebd79a6369e06ca6230d24f46c329ec0aca998
1 <?php
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
16 var $template_mod;
17 var $documents;
18 var $document_categories;
19 var $tree;
20 var $_config;
21 var $manual_set_owner=false; // allows manual setting of a document owner/service
22 var $facilityService;
23 var $patientService;
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);
42 //print_r($t->tree);
43 $this->tree = $t;
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);
62 if ($dh) {
63 $templateslist = array();
64 while (false !== ($sfname = readdir($dh))) {
65 if (substr($sfname, 0, 1) == '.') {
66 continue;
68 $templateslist[$sfname] = $sfname;
70 closedir($dh);
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;
95 $couchDB = false;
96 $harddisk = false;
97 if ($GLOBALS['document_storage_method']==0) {
98 $harddisk = true;
100 if ($GLOBALS['document_storage_method']==1) {
101 $couchDB = true;
104 if ($_POST['process'] != "true") {
105 return;
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'];
120 $patient_id = 0;
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) {
129 $upl_inc = 0;
131 foreach ($_FILES['file']['name'] as $key => $value) {
132 $fname = $value;
133 $error = "";
134 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
135 $fname = $value;
136 if (empty($fname)) {
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";
145 } else {
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]);
150 if ($handler) {
151 $mimetype = "application/dicom+zip";
152 for ($i = 0; $i < $za->numFiles; $i++) {
153 $stat = $za->statIndex($i);
154 $fp = $za->getStream($stat['name']);
155 if ($fp) {
156 $head = fread($fp, 256);
157 fclose($fp);
158 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
159 $mimetype = "application/zip";
160 break;
162 unset($head);
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";
171 break;
174 $za->close();
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]);
184 fclose($tmpfile);
185 if ($doDecryption) {
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']) {
197 $fname .= '.dcm';
200 $d = new Document();
201 $rc = $d->createDocument(
202 $patient_id,
203 $category_id,
204 $fname,
205 $mimetype,
206 $filetext,
207 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
208 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
209 $non_HTTP_owner,
210 $_FILES['file']['tmp_name'][$key]
212 if ($rc) {
213 $error .= $rc . "\n";
214 } else {
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);
230 if ($tmp) {
231 $error = $tmp;
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") {
260 return;
263 $n = new Note();
264 $n->set_owner($_SESSION['authUserID']);
265 parent::populate_object($n);
266 if ($_POST['identifier'] == "no") {
267 // associate a note with a document
268 $n->persist();
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));
295 fclose($fh);
296 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
297 } else {
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;
313 $url = $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;
336 global $ISSUE_TYPES;
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("file", $d);
345 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
346 $this->assign("NOTE_ACTION", $this->_link("note"));
347 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
348 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
349 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
350 $this->assign("webroot", $GLOBALS['webroot']);
352 // Added by Rod to support document delete:
353 $delete_string = '';
354 if (acl_check('patients', 'docs_rm')) {
355 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
356 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
358 $this->assign("delete_string", $delete_string);
359 $this->assign("REFRESH_ACTION", $this->_link("list"));
361 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
362 "document_id=" . $d->get_id() . "&process=true");
364 // Added by Rod to support document date update:
365 $this->assign("DOCDATE", $d->get_docdate());
366 $this->assign("UPDATE_ACTION", $this->_link("update") .
367 "document_id=" . $d->get_id() . "&process=true");
369 // Added by Rod to support document issue update:
370 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
371 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
372 "pid = ? " . // AND enddate IS NULL " .
373 "ORDER BY type, begdate", array($patient_id));
374 while ($irow = sqlFetchArray($ires)) {
375 $desc = $irow['type'];
376 if ($ISSUE_TYPES[$desc]) {
377 $desc = $ISSUE_TYPES[$desc][2];
379 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
380 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
381 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
383 $this->assign("ISSUES_LIST", $issues_options);
385 // For tagging to encounter
386 // Populate the dropdown with patient's encounter list
387 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
388 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
389 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
390 "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));
391 if (sqlNumRows($result_docs) > 0) {
392 while ($row_result_docs = sqlFetchArray($result_docs)) {
393 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
394 $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>";
397 $this->assign("ENC_LIST", $encOptions);
399 //clear encounter tag
400 if ($d->get_encounter_id() != 0) {
401 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
402 } else {
403 $this->assign('clear_encounter_tag', 'javascript:void(0)');
406 //Populate the dropdown with category list
407 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
408 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
409 while ($crow = sqlFetchArray($cres)) {
410 $catid = $crow['pc_catid'];
411 if ($catid < 9 && $catid != 5) {
412 continue; // Applying same logic as in new encounter page.
414 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
416 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
418 $this->assign("notes", $notes);
420 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
421 // Populate the dropdown with image procedure order list
422 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
423 $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));
424 $mapping = $this->get_mapped_procedure($d->get_id());
425 if (sqlNumRows($imgOrders) > 0) {
426 while ($row = sqlFetchArray($imgOrders)) {
427 $sel_proc = '';
428 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
429 $sel_proc = 'selected';
431 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
435 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
437 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
439 $this->_last_node = null;
441 $menu = new HTML_TreeMenu();
443 //pass an empty array because we don't want the documents for each category showing up in this list box
444 $rnode = $this->_array_recurse($this->tree->tree, array());
445 $menu->addItem($rnode);
446 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
448 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
450 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
451 $this->assign("activity", $activity);
453 return $this->list_action($patient_id);
456 function encrypt($plaintext, $key)
458 return aes256Encrypt($plaintext, $key, false);
461 function decrypt($crypttext, $key)
463 return aes256Decrypt($crypttext, $key, false);
467 * Retrieve file from hard disk / CouchDB.
468 * In case that file isn't download this function will return thumbnail image (if exist).
469 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
470 * @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.
471 * */
472 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
474 $encrypted = $_POST['encrypted'];
475 $passphrase = $_POST['passphrase'];
476 $doEncryption = false;
477 if (!$GLOBALS['hide_document_encryption'] &&
478 $encrypted == "true" &&
479 $passphrase ) {
480 $doEncryption = true;
483 //controller function ruins booleans, so need to manually re-convert to booleans
484 if ($as_file == "true") {
485 $as_file=true;
486 } else if ($as_file == "false") {
487 $as_file=false;
489 if ($original_file == "true") {
490 $original_file=true;
491 } else if ($original_file == "false") {
492 $original_file=false;
494 if ($disable_exit == "true") {
495 $disable_exit=true;
496 } else if ($disable_exit == "false") {
497 $disable_exit=false;
499 if ($show_original == "true") {
500 $show_original=true;
501 } else if ($show_original == "false") {
502 $show_original=false;
505 switch ($context) {
506 case "patient_picture":
507 $this->patientService->setPid($patient_id);
508 $document_id = $this->patientService->getPatientPictureDocumentId();
509 break;
512 $d = new Document($document_id);
513 $url = $d->get_url();
514 $th_url = $d->get_thumb_url();
516 $storagemethod = $d->get_storagemethod();
517 $couch_docid = $d->get_couch_docid();
518 $couch_revid = $d->get_couch_revid();
520 if ($couch_docid && $couch_revid && $original_file) {
521 $couch = new CouchDB();
522 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
523 $resp = $couch->retrieve_doc($data);
524 //Take thumbnail file when is not null and file is presented online
525 if (!$as_file && !is_null($th_url) && !$show_original) {
526 $content = $resp->th_data;
527 } else {
528 $content = $resp->data;
530 if ($content=='' && $GLOBALS['couchdb_log']==1) {
531 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
532 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
533 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
534 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
535 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
536 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
537 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
538 die(xl("File retrieval from CouchDB failed"));
540 if ($disable_exit == true) {
541 return base64_decode($content);
543 header('Content-Description: File Transfer');
544 header('Content-Transfer-Encoding: binary');
545 header('Expires: 0');
546 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
547 header('Pragma: public');
548 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
549 $fh = fopen($tmpcouchpath, "w");
550 fwrite($fh, base64_decode($content));
551 fclose($fh);
552 $f = fopen($tmpcouchpath, "r");
553 if ($doEncryption) {
554 $filetext = fread($f, filesize($tmpcouchpath));
555 $ciphertext = $this->encrypt($filetext, $passphrase);
556 $tmpfilepath = $GLOBALS['temporary_files_dir'];
557 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
558 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
559 fwrite($tmpfile, $ciphertext);
560 fclose($tmpfile);
561 header('Content-Disposition: attachment; filename='.$tmpfilename);
562 header("Content-Type: application/octet-stream");
563 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
564 ob_clean();
565 flush();
566 readfile($tmpfilepath.$tmpfilename);
567 unlink($tmpfilepath.$tmpfilename);
568 } else {
569 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
570 header("Content-Type: " . $d->get_mimetype());
571 header("Content-Length: " . filesize($tmpcouchpath));
572 fpassthru($f);
574 fclose($f);
575 if ($content!='') {
576 unlink($tmpcouchpath);
578 exit;//exits only if file download from CouchDB is successfull.
581 //Take thumbnail file when is not null and file is presented online
582 if (!$as_file && !is_null($th_url) && !$show_original) {
583 $url = $th_url;
586 //strip url of protocol handler
587 $url = preg_replace("|^(.*)://|", "", $url);
589 //change full path to current webroot. this is for documents that may have
590 //been moved from a different filesystem and the full path in the database
591 //is not current. this is also for documents that may of been moved to
592 //different patients. Note that the path_depth is used to see how far down
593 //the path to go. For example, originally the path_depth was always 1, which
594 //only allowed things like documents/1/<file>, but now can have more structured
595 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
596 // etc.
597 // NOTE that $from_filename and basename($url) are the same thing
598 $from_all = explode("/", $url);
599 $from_filename = array_pop($from_all);
600 $from_pathname_array = array();
601 for ($i=0; $i<$d->get_path_depth(); $i++) {
602 $from_pathname_array[] = array_pop($from_all);
604 $from_pathname_array = array_reverse($from_pathname_array);
605 $from_pathname = implode("/", $from_pathname_array);
606 if ($couch_docid && $couch_revid) {
607 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
608 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
609 } else {
610 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
613 if (file_exists($temp_url)) {
614 $url = $temp_url;
618 if (!file_exists($url)) {
619 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;
620 } else {
621 if ($original_file) {
622 //normal case when serving the file referenced in database
623 if ($disable_exit == true) {
624 $f = fopen($url, "r");
625 $filetext = fread($f, filesize($url));
626 return $filetext;
628 header('Content-Description: File Transfer');
629 header('Content-Transfer-Encoding: binary');
630 header('Expires: 0');
631 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
632 header('Pragma: public');
633 $f = fopen($url, "r");
634 if ($doEncryption) {
635 $filetext = fread($f, filesize($url));
636 $ciphertext = $this->encrypt($filetext, $passphrase);
637 $tmpfilepath = $GLOBALS['temporary_files_dir'];
638 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
639 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
640 fwrite($tmpfile, $ciphertext);
641 fclose($tmpfile);
642 header('Content-Disposition: attachment; filename='.$tmpfilename);
643 header("Content-Type: application/octet-stream");
644 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
645 ob_clean();
646 flush();
647 readfile($tmpfilepath.$tmpfilename);
648 unlink($tmpfilepath.$tmpfilename);
649 } else {
650 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
651 header("Content-Type: " . $d->get_mimetype());
652 header("Content-Length: " . filesize($url));
653 fpassthru($f);
655 exit;
656 } else {
657 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
658 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
659 if ($couch_docid && $couch_revid) {
660 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
661 } else {
662 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
664 if ($disable_exit == true) {
665 return ;
667 header("Pragma: public");
668 header("Expires: 0");
669 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
670 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
671 header("Content-Type: image/jpeg");
672 header("Content-Length: " . filesize($url));
673 $f = fopen($url, "r");
674 fpassthru($f);
675 if ($couch_docid && $couch_revid) {
676 fclose($f);
677 unlink($url);
678 $url=str_replace("_converted.jpg", '.pdf', $url);
679 unlink($url);
681 exit;
686 function queue_action($patient_id = "")
688 $messages = $this->_tpl_vars['messages'];
689 $queue_files = array();
691 //see if the repository exists and it is a directory else error
692 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
693 $dir = opendir($this->_config['repository']);
694 //read each entry in the directory
695 while (($file = readdir($dir)) !== false) {
696 //concat the filename and path
697 $file = $this->_config['repository'] .$file;
698 $file_info = array();
699 //if the filename is a file get its info and put into a tmp array
700 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
701 $file_info['filename'] = basename_international($file);
702 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
703 $d = $this->Document->document_factory_url("file://" . $file);
704 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
705 $file_info['patient_id'] = $patient_match[1];
706 $file_info['document_id'] = $d->get_id();
707 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
709 //merge the tmp array into the larger array
710 $queue_files[] = $file_info;
713 closedir($dir);
714 } else {
715 $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";
719 $this->assign("queue_files", $queue_files);
720 $this->_last_node = null;
722 $menu = new HTML_TreeMenu();
724 //pass an empty array because we don't want the documents for each category showing up in this list box
725 $rnode = $this->_array_recurse($this->tree->tree, array());
726 $menu->addItem($rnode);
727 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
729 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
731 $this->assign("messages", nl2br($messages));
732 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
735 function queue_action_process()
737 if ($_POST['process'] != "true") {
738 return;
741 $messages = $this->_tpl_vars['messages'];
743 //build a category tree so we can have a list of category ids that are valid
744 $ct = new CategoryTree(1);
745 $categories = $ct->_id_name;
747 //see if there were and posted files and assign them
748 $files = null;
749 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
751 //loop through posted files
752 foreach ($files as $doc_id => $file) {
753 //only operate on files checked as active
754 if (!$file['active']) {
755 continue;
758 //run basic validation checks
759 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
760 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
761 continue;
764 //validate that the pod exists
765 $d = new Document($doc_id);
766 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
767 $result = $d->_db->Execute($sql);
769 if (!$result || $result->EOF) {
770 //patient id does not exist
771 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
772 continue;
775 //validate that the category id exists
776 if (!isset($categories[$file['category_id']])) {
777 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
778 continue;
781 //now do the work of moving the file
782 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
784 //see if the patient dir exists in the repository and create if not
785 if (!file_exists($new_path)) {
786 if (!mkdir($new_path, 0700)) {
787 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
788 continue;
792 //fname is the name of the file after it is moved
793 $fname = $file['name'];
795 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
796 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
797 if ($patient_match[1] == $file['patient_id']) {
798 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
801 //filenames should not have funny chars
802 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
804 //see if there is an existing file with the same name and rename as necessary
805 if (file_exists($new_path.$file['name'])) {
806 $messages .= "File with same name already exists at location: " . $new_path . "\n";
807 $fname = basename_international($this->_rename_file($new_path.$file['name']));
808 $messages .= "Current file name was changed to " . $fname ."\n";
811 //now move the file
812 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
813 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
814 $d->url = "file://" .$new_path.$fname;
815 $d->set_foreign_id($file['patient_id']);
816 $d->set_mimetype($mimetype);
817 $d->persist();
818 $d->populate();
820 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
821 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
822 $d->_db->Execute($sql);
824 } else {
825 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
828 $this->assign("messages", $messages);
829 $_POST['process'] = "";
832 function move_action_process($patient_id = "", $document_id)
834 if ($_POST['process'] != "true") {
835 return;
838 $new_category_id = $_POST['new_category_id'];
839 $new_patient_id = $_POST['new_patient_id'];
841 //move to new category
842 if (is_numeric($new_category_id) && is_numeric($document_id)) {
843 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
844 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
845 //echo $sql;
846 $this->tree->_db->Execute($sql);
849 //move to new patient
850 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
851 $d = new Document($document_id);
852 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
853 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
854 $result = $d->_db->Execute($sql);
856 if (!$result || $result->EOF) {
857 //patient id does not exist
858 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
859 } else {
860 $couchsavefailed = !$d->change_patient($new_patient_id);
862 $this->_state = false;
863 if (!$couchsavefailed) {
864 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
865 } else {
866 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
868 $this->assign("messages", $messages);
869 return $this->list_action($patient_id);
871 } //in this case return the document to the queue instead of moving it
872 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
873 $d = new Document($document_id);
874 $new_path = $this->_config['repository'];
875 $fname = $d->get_url_file();
877 //see if there is an existing file with the same name and rename as necessary
878 if (file_exists($new_path.$d->get_url_file())) {
879 $messages .= "File with same name already exists in the queue.\n";
880 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
881 $messages .= "Current file name was changed to " . $fname ."\n";
884 //now move the file
885 if (rename($d->get_url_filepath(), $new_path.$fname)) {
886 $d->url = "file://" .$new_path.$fname;
887 $d->set_foreign_id("");
888 $d->persist();
889 $d->persist();
890 $d->populate();
892 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
893 $d->_db->Execute($sql);
894 $messages .= "Document returned to queue successfully.\n";
895 } else {
896 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
899 $this->_state = false;
900 $this->assign("messages", $messages);
901 return $this->list_action($patient_id);
904 $this->_state = false;
905 $this->assign("messages", $messages);
906 return $this->view_action($patient_id, $document_id);
909 function validate_action_process($patient_id = "", $document_id)
912 $d = new Document($document_id);
913 if ($d->couch_docid && $d->couch_revid) {
914 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
915 $url = $file_path.$d->get_url();
916 $couch = new CouchDB();
917 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
918 $resp = $couch->retrieve_doc($data);
919 $content = $resp->data;
920 //--------Temporarily writing the file for calculating the hash--------//
921 //-----------Will be removed after calculating the hash value----------//
922 $temp_file = fopen($url, "w");
923 fwrite($temp_file, base64_decode($content));
924 fclose($temp_file);
925 } else {
926 $url = $d->get_url();
928 //strip url of protocol handler
929 $url = preg_replace("|^(.*)://|", "", $url);
931 //change full path to current webroot. this is for documents that may have
932 //been moved from a different filesystem and the full path in the database
933 //is not current. this is also for documents that may of been moved to
934 //different patients. Note that the path_depth is used to see how far down
935 //the path to go. For example, originally the path_depth was always 1, which
936 //only allowed things like documents/1/<file>, but now can have more structured
937 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
938 // etc.
939 // NOTE that $from_filename and basename($url) are the same thing
940 $from_all = explode("/", $url);
941 $from_filename = array_pop($from_all);
942 $from_pathname_array = array();
943 for ($i=0; $i<$d->get_path_depth(); $i++) {
944 $from_pathname_array[] = array_pop($from_all);
946 $from_pathname_array = array_reverse($from_pathname_array);
947 $from_pathname = implode("/", $from_pathname_array);
948 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
949 if (file_exists($temp_url)) {
950 $url = $temp_url;
953 if ($_POST['process'] != "true") {
954 die("process is '" . $_POST['process'] . "', expected 'true'");
955 return;
958 $d = new Document($document_id);
959 $current_hash = sha1_file($url);
960 $messages = xl('Current Hash').": ".$current_hash."<br>";
961 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
962 if ($d->get_hash() == '') {
963 $d->hash = $current_hash;
964 $d->persist();
965 $d->populate();
966 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
967 } else if ($current_hash != $d->get_hash()) {
968 $messages .= xl('Hash does not match. Data integrity has been compromised.');
969 } else {
970 $messages .= xl('Document passed integrity check.');
972 $this->_state = false;
973 $this->assign("messages", $messages);
974 if ($d->couch_docid && $d->couch_revid) {
975 //Removing the temporary file which is used to create the hash
976 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
978 return $this->view_action($patient_id, $document_id);
981 // Added by Rod for metadata update.
983 function update_action_process($patient_id = "", $document_id)
986 if ($_POST['process'] != "true") {
987 die("process is '" . $_POST['process'] . "', expected 'true'");
988 return;
991 $docdate = $_POST['docdate'];
992 $docname = $_POST['docname'];
993 $issue_id = $_POST['issue_id'];
995 if (is_numeric($document_id)) {
996 $messages = '';
997 $d = new Document($document_id);
998 $file_name = $d->get_url_file();
999 if ($docname != '' &&
1000 $docname != $file_name ) {
1001 // Ready to rename - check for relocation
1002 $old_url = $this->_check_relocation($d->get_url());
1003 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1004 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
1005 if (rename($old_url, $new_url)) {
1006 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1007 if (file_exists($old_url)) {
1008 unlink($old_url);
1010 $d->url = $new_url;
1011 $d->persist();
1012 $d->populate();
1013 $messages .= xl('Document successfully renamed.')."<br>";
1014 } else {
1015 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1019 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1020 $docdate = "'$docdate'";
1021 } else {
1022 $docdate = "NULL";
1024 if (!is_numeric($issue_id)) {
1025 $issue_id = 0;
1027 $couch_docid = $d->get_couch_docid();
1028 $couch_revid = $d->get_couch_revid();
1029 if ($couch_docid && $couch_revid) {
1030 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1031 "list_id = '$issue_id' " .
1032 "WHERE id = '$document_id'";
1033 $this->tree->_db->Execute($sql);
1034 } else {
1035 $sql = "UPDATE documents SET docdate = $docdate, " .
1036 "list_id = '$issue_id' " .
1037 "WHERE id = '$document_id'";
1038 $this->tree->_db->Execute($sql);
1040 $messages .= xl('Document date and issue updated successfully') . "<br>";
1043 $this->_state = false;
1044 $this->assign("messages", $messages);
1045 return $this->view_action($patient_id, $document_id);
1048 function list_action($patient_id = "")
1050 $this->_last_node = null;
1051 $categories_list = $this->tree->_get_categories_array($patient_id);
1052 //print_r($categories_list);
1054 $menu = new HTML_TreeMenu();
1055 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1056 $menu->addItem($rnode);
1057 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1058 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1059 $this->assign("tree_html", $treeMenu->toHTML());
1061 $is_new = isset($_GET['patient_name']) ? 1 : false;
1062 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1063 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1064 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1065 if ($cur_pid == '00') {
1066 $cur_pid = '0';
1067 $is_new = 1;
1069 $this->assign('is_new', $is_new);
1070 $this->assign('place_hld', $place_hld);
1071 $this->assign('cur_pid', $cur_pid);
1072 $this->assign('used_msg', $used_msg);
1073 $this->assign('demo_pid', $_SESSION['pid']);
1075 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1078 /* This is a recursive function to rename a file to something that doesn't already exist.
1079 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1080 * at end) to ensure documents opened correctly by external browser viewers. If the
1081 * counter is at the end of the file, then will use it (to continue to work with older
1082 * files), however all new counters will be placed within filenames.
1084 * Modified to only deal with base file name when renaming, to avoid issues with directory
1085 * names with dots.
1087 function _rename_file($fname, $self = false)
1089 // Allow same routine for new file name check
1090 if (!file_exists($fname)) {
1091 return($fname);
1094 $path = dirname($fname);
1095 $file = basename_international($fname);
1097 $fparts = explode(".", $file);
1098 switch (count($fparts)) {
1099 case 1:
1100 // Has a single node (base file name). Create counter node with value 0
1101 $fparts[1] = '1';
1102 break;
1103 case 2:
1104 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1105 if (is_numeric($fparts[1])) {
1106 $fparts[1] += 1;
1107 } else {
1108 array_push($fparts, $fparts[1]);
1109 $fparts[1] = '1';
1111 break;
1112 default:
1113 // Multiple nodes
1114 $ix_end = count($fparts) - 1;
1115 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1116 // Switch old style to new and check again
1117 $wrk = $fparts[$ix_end - 1];
1118 $fparts[$ix_end - 1] = $fparts[$ix_end];
1119 $fparts[$ix_end] = $wrk;
1120 } else if (is_numeric($fparts[$ix_end - 1])) {
1121 $fparts[$ix_end - 1] += 1;
1122 } else {
1123 array_push($fparts, $fparts[$ix_end]);
1124 $fparts[$ix_end] = '1';
1126 break;
1129 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1131 if (file_exists($fname)) {
1132 return $this->_rename_file($fname, true);
1133 } else {
1134 return($fname);
1138 function &_array_recurse($array, $categories = array())
1140 if (!is_array($array)) {
1141 $array = array();
1143 $node = &$this->_last_node;
1144 $current_node = &$node;
1145 $expandedIcon = 'folder-expanded.gif';
1146 foreach ($array as $id => $ar) {
1147 $icon = 'folder.gif';
1148 if (is_array($ar) || !empty($id)) {
1149 if ($node == null) {
1150 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1151 $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));
1152 $this->_last_node = &$rnode;
1153 $node = &$rnode;
1154 $current_node = &$rnode;
1155 } else {
1156 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1157 $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)));
1158 $current_node = &$this->_last_node;
1161 $this->_array_recurse($ar, $categories);
1162 } else {
1163 if ($id === 0 && !empty($ar)) {
1164 $info = $this->tree->get_node_info($id);
1165 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1166 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1167 } else {
1168 //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
1169 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1170 if ($id !== 0 && is_object($node)) {
1171 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1172 $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)));
1177 // If there are documents in this document category, then add their
1178 // attributes to the current node.
1179 $icon = "file3.png";
1180 if (is_array($categories[$id])) {
1181 foreach ($categories[$id] as $doc) {
1182 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1183 // If user has no access then there will be no link.
1184 if (!acl_check_aco_spec($doc['aco_spec'])) {
1185 $link = '';
1187 if ($this->tree->get_node_name($id) == "CCR") {
1188 $current_node->addItem(new HTML_TreeNode(array(
1189 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1190 'link' => $link,
1191 'icon' => $icon,
1192 'expandedIcon' => $expandedIcon,
1193 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1194 )));
1195 } elseif ($this->tree->get_node_name($id) == "CCD") {
1196 $current_node->addItem(new HTML_TreeNode(array(
1197 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1198 'link' => $link,
1199 'icon' => $icon,
1200 'expandedIcon' => $expandedIcon,
1201 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1202 )));
1203 } else {
1204 $current_node->addItem(new HTML_TreeNode(array(
1205 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1206 'link' => $link,
1207 'icon' => $icon,
1208 'expandedIcon' => $expandedIcon
1209 )));
1214 return $node;
1217 //function for logging the errors in writing file to CouchDB/Hard Disk
1218 function document_upload_download_log($patientid, $content)
1220 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1221 $log_file = 'log.txt';
1222 if (!is_dir($log_path)) {
1223 mkdir($log_path, 0777, true);
1225 $LOG = fopen($log_path.$log_file, 'a');
1226 fwrite($LOG, $content);
1227 fclose($LOG);
1230 function document_send($email, $body, $attfile, $pname)
1232 if (empty($email)) {
1233 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1234 return;
1237 $desc = "Please check the attached patient document.\n Content:".$body;
1238 $mail = new MyMailer();
1239 $from_name = $GLOBALS["practice_return_email_path"];
1240 $from = $GLOBALS["practice_return_email_path"];
1241 $mail->AddReplyTo($from, $from_name);
1242 $mail->SetFrom($from, $from);
1243 $to = $email ;
1244 $to_name =$email;
1245 $mail->AddAddress($to, $to_name);
1246 $subject = "Patient documents";
1247 $mail->Subject = $subject;
1248 $mail->Body = $desc;
1249 $mail->AddAttachment($attfile);
1250 if ($mail->Send()) {
1251 $retstatus = "email_sent";
1252 } else {
1253 $email_status = $mail->ErrorInfo;
1254 //echo "EMAIL ERROR: ".$email_status;
1255 $retstatus = "email_fail";
1259 //place to hold optional code
1260 //$first_node = array_keys($t->tree);
1261 //$first_node = $first_node[0];
1262 //$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')"));
1264 //$this->_last_node = &$node1;
1266 // Function to tag a document to an encounter.
1267 function tag_action_process($patient_id = "", $document_id)
1269 if ($_POST['process'] != "true") {
1270 die("process is '" . text($_POST['process']) . "', expected 'true'");
1271 return;
1274 // Create Encounter and Tag it.
1275 $event_date = date('Y-m-d H:i:s');
1276 $encounter_id = $_POST['encounter_id'];
1277 $encounter_check = $_POST['encounter_check'];
1278 $visit_category_id = $_POST['visit_category_id'];
1280 if (is_numeric($document_id)) {
1281 $messages = '';
1282 $d = new Document($document_id);
1283 $file_name = $d->get_url_file();
1284 if (!is_numeric($encounter_id)) {
1285 $encounter_id = 0;
1288 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1289 if ($encounter_check) {
1290 $provider_id = $_SESSION['authUserID'] ;
1292 // Get the logged in user's facility
1293 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1294 $username = $facilityRow['username'];
1295 $facility = $facilityRow['facility'];
1296 $facility_id = $facilityRow['facility_id'];
1297 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1298 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1299 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1301 $conn = $GLOBALS['adodb']['db'];
1302 $encounter = $conn->GenID("sequences");
1303 $query = "INSERT INTO form_encounter SET
1304 date = ?,
1305 reason = ?,
1306 facility = ?,
1307 sensitivity = 'normal',
1308 pc_catid = ?,
1309 facility_id = ?,
1310 billing_facility = ?,
1311 provider_id = ?,
1312 pid = ?,
1313 encounter = ?";
1314 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1315 $formID = sqlInsert($query, $bindArray);
1316 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1317 $d->set_encounter_id($encounter);
1318 $this->image_result_indication($d->id, $encounter);
1319 } else {
1320 $d->set_encounter_id($encounter_id);
1321 $this->image_result_indication($d->id, $encounter_id);
1323 $d->set_encounter_check($encounter_check);
1324 $d->persist();
1326 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1329 $this->_state = false;
1330 $this->assign("messages", $messages);
1332 return $this->view_action($patient_id, $document_id);
1335 function image_procedure_action($patient_id = "", $document_id)
1338 $img_procedure_id = $_POST['image_procedure_id'];
1339 $proc_code = $_POST['procedure_code'];
1341 if (is_numeric($document_id)) {
1342 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1343 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1344 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1345 if ($img_report_id == 0) {
1346 $report_date = date('Y-m-d H:i:s');
1347 $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));
1350 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1351 if (empty($img_result)) {
1352 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));
1355 $this->image_result_indication($document_id, 0, $img_procedure_id);
1357 return $this->view_action($patient_id, $document_id);
1360 function clear_procedure_tag_action($patient_id = "", $document_id)
1362 if (is_numeric($document_id)) {
1363 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1365 return $this->view_action($patient_id, $document_id);
1368 function get_mapped_procedure($document_id)
1370 $map = array();
1371 if (is_numeric($document_id)) {
1372 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1373 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1374 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1375 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1376 where pres.document_id = ?", array($document_id));
1378 return $map;
1381 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1383 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1384 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1386 if ($encounter != 0) {
1387 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1388 } else if ($image_procedure_id != 0) {
1389 $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));
1390 } else {
1391 $ep = array('assigned_to' => $_SESSION['authUser']);
1394 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1395 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1396 setGpRelation(1, $doc_id, 6, $noteid);
1399 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1400 * Also usable for documents that may of been moved to different patients.
1402 * @param string $url - Current url string from database.
1403 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1404 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1406 * @return string
1408 function _check_relocation($url, $new_pid = null, $new_name = null)
1410 //strip url of protocol handler
1411 $url = preg_replace("|^(.*)://|", "", $url);
1412 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1413 while (current($fsnodes) != "documents") {
1414 array_shift($fsnodes);
1416 if ($new_pid) {
1417 $fsnodes[1] = $new_pid;
1419 if ($new_name) {
1420 $fsnodes[count($fsnodes)-1] = $new_name;
1422 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1423 // Make sure the url is available after corrections
1424 if ($new_pid || $new_name) {
1425 $url = $this->_rename_file($url);
1427 //Add full path and remaining nodes
1428 return $url;
1431 //clear encounter tag function
1432 function clear_encounter_tag_action($patient_id = "", $document_id)
1434 if (is_numeric($document_id)) {
1435 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1437 return $this->view_action($patient_id, $document_id);