csrf ongoing work (#1803)
[openemr.git] / controllers / C_Document.class.php
blob2626ba36bc8bd3f5a005cb25b75c357829114126
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("csrf_token_form", $_SESSION['csrf_token']);
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:
355 $delete_string = '';
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());
404 } else {
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)) {
429 $sel_proc = '';
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.
473 * */
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" &&
481 $passphrase ) {
482 $doEncryption = true;
485 //controller function ruins booleans, so need to manually re-convert to booleans
486 if ($as_file == "true") {
487 $as_file=true;
488 } else if ($as_file == "false") {
489 $as_file=false;
491 if ($original_file == "true") {
492 $original_file=true;
493 } else if ($original_file == "false") {
494 $original_file=false;
496 if ($disable_exit == "true") {
497 $disable_exit=true;
498 } else if ($disable_exit == "false") {
499 $disable_exit=false;
501 if ($show_original == "true") {
502 $show_original=true;
503 } else if ($show_original == "false") {
504 $show_original=false;
507 switch ($context) {
508 case "patient_picture":
509 $this->patientService->setPid($patient_id);
510 $document_id = $this->patientService->getPatientPictureDocumentId();
511 break;
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;
529 } else {
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));
553 fclose($fh);
554 $f = fopen($tmpcouchpath, "r");
555 if ($doEncryption) {
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);
562 fclose($tmpfile);
563 header('Content-Disposition: attachment; filename='.$tmpfilename);
564 header("Content-Type: application/octet-stream");
565 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
566 ob_clean();
567 flush();
568 readfile($tmpfilepath.$tmpfilename);
569 unlink($tmpfilepath.$tmpfilename);
570 } else {
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));
574 fpassthru($f);
576 fclose($f);
577 if ($content!='') {
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) {
585 $url = $th_url;
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>
598 // etc.
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;
611 } else {
612 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
615 if (file_exists($temp_url)) {
616 $url = $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;
622 } else {
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));
628 return $filetext;
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');
635 $f = fopen($url, "r");
636 if ($doEncryption) {
637 $filetext = fread($f, filesize($url));
638 $ciphertext = $this->encrypt($filetext, $passphrase);
639 $tmpfilepath = $GLOBALS['temporary_files_dir'];
640 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
641 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
642 fwrite($tmpfile, $ciphertext);
643 fclose($tmpfile);
644 header('Content-Disposition: attachment; filename='.$tmpfilename);
645 header("Content-Type: application/octet-stream");
646 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
647 ob_clean();
648 flush();
649 readfile($tmpfilepath.$tmpfilename);
650 unlink($tmpfilepath.$tmpfilename);
651 } else {
652 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
653 header("Content-Type: " . $d->get_mimetype());
654 header("Content-Length: " . filesize($url));
655 fpassthru($f);
657 exit;
658 } else {
659 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
660 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
661 if ($couch_docid && $couch_revid) {
662 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
663 } else {
664 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
666 if ($disable_exit == true) {
667 return ;
669 header("Pragma: public");
670 header("Expires: 0");
671 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
672 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
673 header("Content-Type: image/jpeg");
674 header("Content-Length: " . filesize($url));
675 $f = fopen($url, "r");
676 fpassthru($f);
677 if ($couch_docid && $couch_revid) {
678 fclose($f);
679 unlink($url);
680 $url=str_replace("_converted.jpg", '.pdf', $url);
681 unlink($url);
683 exit;
688 function queue_action($patient_id = "")
690 $messages = $this->_tpl_vars['messages'];
691 $queue_files = array();
693 //see if the repository exists and it is a directory else error
694 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
695 $dir = opendir($this->_config['repository']);
696 //read each entry in the directory
697 while (($file = readdir($dir)) !== false) {
698 //concat the filename and path
699 $file = $this->_config['repository'] .$file;
700 $file_info = array();
701 //if the filename is a file get its info and put into a tmp array
702 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
703 $file_info['filename'] = basename_international($file);
704 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
705 $d = $this->Document->document_factory_url("file://" . $file);
706 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
707 $file_info['patient_id'] = $patient_match[1];
708 $file_info['document_id'] = $d->get_id();
709 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
711 //merge the tmp array into the larger array
712 $queue_files[] = $file_info;
715 closedir($dir);
716 } else {
717 $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";
721 $this->assign("queue_files", $queue_files);
722 $this->_last_node = null;
724 $menu = new HTML_TreeMenu();
726 //pass an empty array because we don't want the documents for each category showing up in this list box
727 $rnode = $this->_array_recurse($this->tree->tree, array());
728 $menu->addItem($rnode);
729 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
731 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
733 $this->assign("messages", nl2br($messages));
734 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
737 function queue_action_process()
739 if ($_POST['process'] != "true") {
740 return;
743 $messages = $this->_tpl_vars['messages'];
745 //build a category tree so we can have a list of category ids that are valid
746 $ct = new CategoryTree(1);
747 $categories = $ct->_id_name;
749 //see if there were and posted files and assign them
750 $files = null;
751 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
753 //loop through posted files
754 foreach ($files as $doc_id => $file) {
755 //only operate on files checked as active
756 if (!$file['active']) {
757 continue;
760 //run basic validation checks
761 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
762 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
763 continue;
766 //validate that the pod exists
767 $d = new Document($doc_id);
768 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
769 $result = $d->_db->Execute($sql);
771 if (!$result || $result->EOF) {
772 //patient id does not exist
773 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
774 continue;
777 //validate that the category id exists
778 if (!isset($categories[$file['category_id']])) {
779 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
780 continue;
783 //now do the work of moving the file
784 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
786 //see if the patient dir exists in the repository and create if not
787 if (!file_exists($new_path)) {
788 if (!mkdir($new_path, 0700)) {
789 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
790 continue;
794 //fname is the name of the file after it is moved
795 $fname = $file['name'];
797 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
798 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
799 if ($patient_match[1] == $file['patient_id']) {
800 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
803 //filenames should not have funny chars
804 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
806 //see if there is an existing file with the same name and rename as necessary
807 if (file_exists($new_path.$file['name'])) {
808 $messages .= "File with same name already exists at location: " . $new_path . "\n";
809 $fname = basename_international($this->_rename_file($new_path.$file['name']));
810 $messages .= "Current file name was changed to " . $fname ."\n";
813 //now move the file
814 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
815 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
816 $d->url = "file://" .$new_path.$fname;
817 $d->set_foreign_id($file['patient_id']);
818 $d->set_mimetype($mimetype);
819 $d->persist();
820 $d->populate();
822 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
823 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
824 $d->_db->Execute($sql);
826 } else {
827 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
830 $this->assign("messages", $messages);
831 $_POST['process'] = "";
834 function move_action_process($patient_id = "", $document_id)
836 if ($_POST['process'] != "true") {
837 return;
840 $new_category_id = $_POST['new_category_id'];
841 $new_patient_id = $_POST['new_patient_id'];
843 //move to new category
844 if (is_numeric($new_category_id) && is_numeric($document_id)) {
845 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
846 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
847 //echo $sql;
848 $this->tree->_db->Execute($sql);
851 //move to new patient
852 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
853 $d = new Document($document_id);
854 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
855 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
856 $result = $d->_db->Execute($sql);
858 if (!$result || $result->EOF) {
859 //patient id does not exist
860 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
861 } else {
862 $couchsavefailed = !$d->change_patient($new_patient_id);
864 $this->_state = false;
865 if (!$couchsavefailed) {
866 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
867 } else {
868 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
870 $this->assign("messages", $messages);
871 return $this->list_action($patient_id);
873 } //in this case return the document to the queue instead of moving it
874 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
875 $d = new Document($document_id);
876 $new_path = $this->_config['repository'];
877 $fname = $d->get_url_file();
879 //see if there is an existing file with the same name and rename as necessary
880 if (file_exists($new_path.$d->get_url_file())) {
881 $messages .= "File with same name already exists in the queue.\n";
882 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
883 $messages .= "Current file name was changed to " . $fname ."\n";
886 //now move the file
887 if (rename($d->get_url_filepath(), $new_path.$fname)) {
888 $d->url = "file://" .$new_path.$fname;
889 $d->set_foreign_id("");
890 $d->persist();
891 $d->persist();
892 $d->populate();
894 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
895 $d->_db->Execute($sql);
896 $messages .= "Document returned to queue successfully.\n";
897 } else {
898 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
901 $this->_state = false;
902 $this->assign("messages", $messages);
903 return $this->list_action($patient_id);
906 $this->_state = false;
907 $this->assign("messages", $messages);
908 return $this->view_action($patient_id, $document_id);
911 function validate_action_process($patient_id = "", $document_id)
914 $d = new Document($document_id);
915 if ($d->couch_docid && $d->couch_revid) {
916 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
917 $url = $file_path.$d->get_url();
918 $couch = new CouchDB();
919 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
920 $resp = $couch->retrieve_doc($data);
921 $content = $resp->data;
922 //--------Temporarily writing the file for calculating the hash--------//
923 //-----------Will be removed after calculating the hash value----------//
924 $temp_file = fopen($url, "w");
925 fwrite($temp_file, base64_decode($content));
926 fclose($temp_file);
927 } else {
928 $url = $d->get_url();
930 //strip url of protocol handler
931 $url = preg_replace("|^(.*)://|", "", $url);
933 //change full path to current webroot. this is for documents that may have
934 //been moved from a different filesystem and the full path in the database
935 //is not current. this is also for documents that may of been moved to
936 //different patients. Note that the path_depth is used to see how far down
937 //the path to go. For example, originally the path_depth was always 1, which
938 //only allowed things like documents/1/<file>, but now can have more structured
939 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
940 // etc.
941 // NOTE that $from_filename and basename($url) are the same thing
942 $from_all = explode("/", $url);
943 $from_filename = array_pop($from_all);
944 $from_pathname_array = array();
945 for ($i=0; $i<$d->get_path_depth(); $i++) {
946 $from_pathname_array[] = array_pop($from_all);
948 $from_pathname_array = array_reverse($from_pathname_array);
949 $from_pathname = implode("/", $from_pathname_array);
950 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
951 if (file_exists($temp_url)) {
952 $url = $temp_url;
955 if ($_POST['process'] != "true") {
956 die("process is '" . $_POST['process'] . "', expected 'true'");
957 return;
960 $d = new Document($document_id);
961 $current_hash = sha1_file($url);
962 $messages = xl('Current Hash').": ".$current_hash."<br>";
963 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
964 if ($d->get_hash() == '') {
965 $d->hash = $current_hash;
966 $d->persist();
967 $d->populate();
968 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
969 } else if ($current_hash != $d->get_hash()) {
970 $messages .= xl('Hash does not match. Data integrity has been compromised.');
971 } else {
972 $messages .= xl('Document passed integrity check.');
974 $this->_state = false;
975 $this->assign("messages", $messages);
976 if ($d->couch_docid && $d->couch_revid) {
977 //Removing the temporary file which is used to create the hash
978 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
980 return $this->view_action($patient_id, $document_id);
983 // Added by Rod for metadata update.
985 function update_action_process($patient_id = "", $document_id)
988 if ($_POST['process'] != "true") {
989 die("process is '" . $_POST['process'] . "', expected 'true'");
990 return;
993 $docdate = $_POST['docdate'];
994 $docname = $_POST['docname'];
995 $issue_id = $_POST['issue_id'];
997 if (is_numeric($document_id)) {
998 $messages = '';
999 $d = new Document($document_id);
1000 $file_name = $d->get_url_file();
1001 if ($docname != '' &&
1002 $docname != $file_name ) {
1003 // Ready to rename - check for relocation
1004 $old_url = $this->_check_relocation($d->get_url());
1005 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1006 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
1007 if (rename($old_url, $new_url)) {
1008 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1009 if (file_exists($old_url)) {
1010 unlink($old_url);
1012 $d->url = $new_url;
1013 $d->persist();
1014 $d->populate();
1015 $messages .= xl('Document successfully renamed.')."<br>";
1016 } else {
1017 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1021 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1022 $docdate = "'$docdate'";
1023 } else {
1024 $docdate = "NULL";
1026 if (!is_numeric($issue_id)) {
1027 $issue_id = 0;
1029 $couch_docid = $d->get_couch_docid();
1030 $couch_revid = $d->get_couch_revid();
1031 if ($couch_docid && $couch_revid) {
1032 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1033 "list_id = '$issue_id' " .
1034 "WHERE id = '$document_id'";
1035 $this->tree->_db->Execute($sql);
1036 } else {
1037 $sql = "UPDATE documents SET docdate = $docdate, " .
1038 "list_id = '$issue_id' " .
1039 "WHERE id = '$document_id'";
1040 $this->tree->_db->Execute($sql);
1042 $messages .= xl('Document date and issue updated successfully') . "<br>";
1045 $this->_state = false;
1046 $this->assign("messages", $messages);
1047 return $this->view_action($patient_id, $document_id);
1050 function list_action($patient_id = "")
1052 $this->_last_node = null;
1053 $categories_list = $this->tree->_get_categories_array($patient_id);
1054 //print_r($categories_list);
1056 $menu = new HTML_TreeMenu();
1057 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1058 $menu->addItem($rnode);
1059 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1060 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1061 $this->assign("tree_html", $treeMenu->toHTML());
1063 $is_new = isset($_GET['patient_name']) ? 1 : false;
1064 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1065 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1066 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1067 if ($cur_pid == '00') {
1068 $cur_pid = '0';
1069 $is_new = 1;
1071 $this->assign('is_new', $is_new);
1072 $this->assign('place_hld', $place_hld);
1073 $this->assign('cur_pid', $cur_pid);
1074 $this->assign('used_msg', $used_msg);
1075 $this->assign('demo_pid', $_SESSION['pid']);
1077 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1080 /* This is a recursive function to rename a file to something that doesn't already exist.
1081 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1082 * at end) to ensure documents opened correctly by external browser viewers. If the
1083 * counter is at the end of the file, then will use it (to continue to work with older
1084 * files), however all new counters will be placed within filenames.
1086 * Modified to only deal with base file name when renaming, to avoid issues with directory
1087 * names with dots.
1089 function _rename_file($fname, $self = false)
1091 // Allow same routine for new file name check
1092 if (!file_exists($fname)) {
1093 return($fname);
1096 $path = dirname($fname);
1097 $file = basename_international($fname);
1099 $fparts = explode(".", $file);
1100 switch (count($fparts)) {
1101 case 1:
1102 // Has a single node (base file name). Create counter node with value 0
1103 $fparts[1] = '1';
1104 break;
1105 case 2:
1106 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1107 if (is_numeric($fparts[1])) {
1108 $fparts[1] += 1;
1109 } else {
1110 array_push($fparts, $fparts[1]);
1111 $fparts[1] = '1';
1113 break;
1114 default:
1115 // Multiple nodes
1116 $ix_end = count($fparts) - 1;
1117 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1118 // Switch old style to new and check again
1119 $wrk = $fparts[$ix_end - 1];
1120 $fparts[$ix_end - 1] = $fparts[$ix_end];
1121 $fparts[$ix_end] = $wrk;
1122 } else if (is_numeric($fparts[$ix_end - 1])) {
1123 $fparts[$ix_end - 1] += 1;
1124 } else {
1125 array_push($fparts, $fparts[$ix_end]);
1126 $fparts[$ix_end] = '1';
1128 break;
1131 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1133 if (file_exists($fname)) {
1134 return $this->_rename_file($fname, true);
1135 } else {
1136 return($fname);
1140 function &_array_recurse($array, $categories = array())
1142 if (!is_array($array)) {
1143 $array = array();
1145 $node = &$this->_last_node;
1146 $current_node = &$node;
1147 $expandedIcon = 'folder-expanded.gif';
1148 foreach ($array as $id => $ar) {
1149 $icon = 'folder.gif';
1150 if (is_array($ar) || !empty($id)) {
1151 if ($node == null) {
1152 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1153 $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));
1154 $this->_last_node = &$rnode;
1155 $node = &$rnode;
1156 $current_node = &$rnode;
1157 } else {
1158 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1159 $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)));
1160 $current_node = &$this->_last_node;
1163 $this->_array_recurse($ar, $categories);
1164 } else {
1165 if ($id === 0 && !empty($ar)) {
1166 $info = $this->tree->get_node_info($id);
1167 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1168 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1169 } else {
1170 //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
1171 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1172 if ($id !== 0 && is_object($node)) {
1173 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1174 $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)));
1179 // If there are documents in this document category, then add their
1180 // attributes to the current node.
1181 $icon = "file3.png";
1182 if (is_array($categories[$id])) {
1183 foreach ($categories[$id] as $doc) {
1184 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1185 // If user has no access then there will be no link.
1186 if (!acl_check_aco_spec($doc['aco_spec'])) {
1187 $link = '';
1189 if ($this->tree->get_node_name($id) == "CCR") {
1190 $current_node->addItem(new HTML_TreeNode(array(
1191 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1192 'link' => $link,
1193 'icon' => $icon,
1194 'expandedIcon' => $expandedIcon,
1195 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1196 )));
1197 } elseif ($this->tree->get_node_name($id) == "CCD") {
1198 $current_node->addItem(new HTML_TreeNode(array(
1199 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1200 'link' => $link,
1201 'icon' => $icon,
1202 'expandedIcon' => $expandedIcon,
1203 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1204 )));
1205 } else {
1206 $current_node->addItem(new HTML_TreeNode(array(
1207 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1208 'link' => $link,
1209 'icon' => $icon,
1210 'expandedIcon' => $expandedIcon
1211 )));
1216 return $node;
1219 //function for logging the errors in writing file to CouchDB/Hard Disk
1220 function document_upload_download_log($patientid, $content)
1222 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1223 $log_file = 'log.txt';
1224 if (!is_dir($log_path)) {
1225 mkdir($log_path, 0777, true);
1227 $LOG = fopen($log_path.$log_file, 'a');
1228 fwrite($LOG, $content);
1229 fclose($LOG);
1232 function document_send($email, $body, $attfile, $pname)
1234 if (empty($email)) {
1235 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1236 return;
1239 $desc = "Please check the attached patient document.\n Content:".$body;
1240 $mail = new MyMailer();
1241 $from_name = $GLOBALS["practice_return_email_path"];
1242 $from = $GLOBALS["practice_return_email_path"];
1243 $mail->AddReplyTo($from, $from_name);
1244 $mail->SetFrom($from, $from);
1245 $to = $email ;
1246 $to_name =$email;
1247 $mail->AddAddress($to, $to_name);
1248 $subject = "Patient documents";
1249 $mail->Subject = $subject;
1250 $mail->Body = $desc;
1251 $mail->AddAttachment($attfile);
1252 if ($mail->Send()) {
1253 $retstatus = "email_sent";
1254 } else {
1255 $email_status = $mail->ErrorInfo;
1256 //echo "EMAIL ERROR: ".$email_status;
1257 $retstatus = "email_fail";
1261 //place to hold optional code
1262 //$first_node = array_keys($t->tree);
1263 //$first_node = $first_node[0];
1264 //$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')"));
1266 //$this->_last_node = &$node1;
1268 // Function to tag a document to an encounter.
1269 function tag_action_process($patient_id = "", $document_id)
1271 if ($_POST['process'] != "true") {
1272 die("process is '" . text($_POST['process']) . "', expected 'true'");
1273 return;
1276 // Create Encounter and Tag it.
1277 $event_date = date('Y-m-d H:i:s');
1278 $encounter_id = $_POST['encounter_id'];
1279 $encounter_check = $_POST['encounter_check'];
1280 $visit_category_id = $_POST['visit_category_id'];
1282 if (is_numeric($document_id)) {
1283 $messages = '';
1284 $d = new Document($document_id);
1285 $file_name = $d->get_url_file();
1286 if (!is_numeric($encounter_id)) {
1287 $encounter_id = 0;
1290 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1291 if ($encounter_check) {
1292 $provider_id = $_SESSION['authUserID'] ;
1294 // Get the logged in user's facility
1295 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1296 $username = $facilityRow['username'];
1297 $facility = $facilityRow['facility'];
1298 $facility_id = $facilityRow['facility_id'];
1299 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1300 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1301 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1303 $conn = $GLOBALS['adodb']['db'];
1304 $encounter = $conn->GenID("sequences");
1305 $query = "INSERT INTO form_encounter SET
1306 date = ?,
1307 reason = ?,
1308 facility = ?,
1309 sensitivity = 'normal',
1310 pc_catid = ?,
1311 facility_id = ?,
1312 billing_facility = ?,
1313 provider_id = ?,
1314 pid = ?,
1315 encounter = ?";
1316 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1317 $formID = sqlInsert($query, $bindArray);
1318 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1319 $d->set_encounter_id($encounter);
1320 $this->image_result_indication($d->id, $encounter);
1321 } else {
1322 $d->set_encounter_id($encounter_id);
1323 $this->image_result_indication($d->id, $encounter_id);
1325 $d->set_encounter_check($encounter_check);
1326 $d->persist();
1328 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1331 $this->_state = false;
1332 $this->assign("messages", $messages);
1334 return $this->view_action($patient_id, $document_id);
1337 function image_procedure_action($patient_id = "", $document_id)
1340 $img_procedure_id = $_POST['image_procedure_id'];
1341 $proc_code = $_POST['procedure_code'];
1343 if (is_numeric($document_id)) {
1344 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1345 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1346 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1347 if ($img_report_id == 0) {
1348 $report_date = date('Y-m-d H:i:s');
1349 $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));
1352 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1353 if (empty($img_result)) {
1354 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));
1357 $this->image_result_indication($document_id, 0, $img_procedure_id);
1359 return $this->view_action($patient_id, $document_id);
1362 function clear_procedure_tag_action($patient_id = "", $document_id)
1364 if (is_numeric($document_id)) {
1365 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1367 return $this->view_action($patient_id, $document_id);
1370 function get_mapped_procedure($document_id)
1372 $map = array();
1373 if (is_numeric($document_id)) {
1374 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1375 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1376 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1377 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1378 where pres.document_id = ?", array($document_id));
1380 return $map;
1383 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1385 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1386 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1388 if ($encounter != 0) {
1389 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1390 } else if ($image_procedure_id != 0) {
1391 $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));
1392 } else {
1393 $ep = array('assigned_to' => $_SESSION['authUser']);
1396 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1397 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1398 setGpRelation(1, $doc_id, 6, $noteid);
1401 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1402 * Also usable for documents that may of been moved to different patients.
1404 * @param string $url - Current url string from database.
1405 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1406 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1408 * @return string
1410 function _check_relocation($url, $new_pid = null, $new_name = null)
1412 //strip url of protocol handler
1413 $url = preg_replace("|^(.*)://|", "", $url);
1414 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1415 while (current($fsnodes) != "documents") {
1416 array_shift($fsnodes);
1418 if ($new_pid) {
1419 $fsnodes[1] = $new_pid;
1421 if ($new_name) {
1422 $fsnodes[count($fsnodes)-1] = $new_name;
1424 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1425 // Make sure the url is available after corrections
1426 if ($new_pid || $new_name) {
1427 $url = $this->_rename_file($url);
1429 //Add full path and remaining nodes
1430 return $url;
1433 //clear encounter tag function
1434 function clear_encounter_tag_action($patient_id = "", $document_id)
1436 if (is_numeric($document_id)) {
1437 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1439 return $this->view_action($patient_id, $document_id);