cleanup referral report
[openemr.git] / controllers / C_Document.class.php
blob684797d15824c211550417f49f118ff0c9de0317
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");
9 use OpenEMR\Services\FacilityService;
10 use OpenEMR\Services\PatientService;
12 class C_Document extends Controller
15 var $template_mod;
16 var $documents;
17 var $document_categories;
18 var $tree;
19 var $_config;
20 var $manual_set_owner=false; // allows manual setting of a document owner/service
21 var $facilityService;
22 var $patientService;
24 function __construct($template_mod = "general")
26 parent::__construct();
27 $this->facilityService = new FacilityService();
28 $this->patientService = new PatientService();
29 $this->documents = array();
30 $this->template_mod = $template_mod;
31 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . attr($_SERVER['QUERY_STRING']));
32 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
34 //get global config options for this namespace
35 $this->_config = $GLOBALS['oer_config']['documents'];
37 $this->_args = array("patient_id" => $_GET['patient_id']);
39 $this->assign("STYLE", $GLOBALS['style']);
40 $t = new CategoryTree(1);
41 //print_r($t->tree);
42 $this->tree = $t;
43 $this->Document = new Document();
46 function upload_action($patient_id, $category_id)
48 $category_name = $this->tree->get_node_name($category_id);
49 $this->assign("category_id", $category_id);
50 $this->assign("category_name", $category_name);
51 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
52 $this->assign("patient_id", $patient_id);
54 // Added by Rod to support document template download from general_upload.html.
55 // Cloned from similar stuff in manage_document_templates.php.
56 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
57 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
58 if (file_exists($templatedir)) {
59 $dh = opendir($templatedir);
61 if ($dh) {
62 $templateslist = array();
63 while (false !== ($sfname = readdir($dh))) {
64 if (substr($sfname, 0, 1) == '.') {
65 continue;
67 $templateslist[$sfname] = $sfname;
69 closedir($dh);
70 ksort($templateslist);
71 foreach ($templateslist as $sfname) {
72 $templates_options .= "<option value='" . attr($sfname) .
73 "'>" . text($sfname) . "</option>";
76 $this->assign("TEMPLATES_LIST", $templates_options);
78 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
79 $this->assign("activity", $activity);
80 return $this->list_action($patient_id);
83 //Upload multiple files on single click
84 function upload_action_process()
87 // Collect a manually set owner if this has been set
88 // Used when want to manually assign the owning user/service such as the Direct mechanism
89 $non_HTTP_owner=false;
90 if ($this->manual_set_owner) {
91 $non_HTTP_owner=$this->manual_set_owner;
94 $couchDB = false;
95 $harddisk = false;
96 if ($GLOBALS['document_storage_method']==0) {
97 $harddisk = true;
99 if ($GLOBALS['document_storage_method']==1) {
100 $couchDB = true;
103 if ($_POST['process'] != "true") {
104 return;
107 $doDecryption = false;
108 $encrypted = $_POST['encrypted'];
109 $passphrase = $_POST['passphrase'];
110 if (!$GLOBALS['hide_document_encryption'] &&
111 $encrypted && $passphrase ) {
112 $doDecryption = true;
115 if (is_numeric($_POST['category_id'])) {
116 $category_id = $_POST['category_id'];
119 $patient_id = 0;
120 if (isset($_GET['patient_id']) && !$couchDB) {
121 $patient_id = $_GET['patient_id'];
122 } else if (is_numeric($_POST['patient_id'])) {
123 $patient_id = $_POST['patient_id'];
126 $sentUploadStatus = array();
127 if (count($_FILES['file']['name']) > 0) {
128 $upl_inc = 0;
130 foreach ($_FILES['file']['name'] as $key => $value) {
131 $fname = $value;
132 $err = "";
133 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
134 $fname = $value;
135 if (empty($fname)) {
136 $fname = htmlentities("<empty>");
138 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
139 if ($_FILES['file']['size'][$key] == 0) {
140 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
142 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
143 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
144 } else {
145 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
146 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
147 fclose($tmpfile);
148 if ($doDecryption) {
149 $filetext = $this->decrypt($filetext, $passphrase);
151 if ($_POST['destination'] != '') {
152 $fname = $_POST['destination'];
154 $d = new Document();
155 $rc = $d->createDocument(
156 $patient_id,
157 $category_id,
158 $fname,
159 $_FILES['file']['type'][$key],
160 $filetext,
161 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
162 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
163 $non_HTTP_owner,
164 $_FILES['file']['tmp_name'][$key]
166 if ($rc) {
167 $error .= $rc . "\n";
168 } else {
169 $this->assign("upload_success", "true");
171 $sentUploadStatus[] = $d;
172 $this->assign("file", $sentUploadStatus);
175 // Option to run a custom plugin for each file upload.
176 // This was initially created to delete the original source file in a custom setting.
177 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
178 if (file_exists($upload_plugin)) {
179 include_once($upload_plugin);
181 $upload_plugin_pp = 'documentUploadPostProcess';
182 if (function_exists($upload_plugin_pp)) {
183 $tmp = call_user_func($upload_plugin_pp, $value, $d);
184 if ($tmp) {
185 $error = $tmp;
188 // Following is just an example of code in such a plugin file.
189 /*****************************************************
190 function documentUploadPostProcess($filename, &$d) {
191 $userid = $_SESSION['authUserID'];
192 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
193 $owner = strtolower($row['username']);
194 $dn = '1_' . ucfirst($owner);
195 $filepath = "/shared_network_directory/$dn/$filename";
196 if (@unlink($filepath)) return '';
197 return "Failed to delete '$filepath'.";
199 *****************************************************/
203 $this->assign("error", nl2br($error));
204 //$this->_state = false;
205 $_POST['process'] = "";
206 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
209 function note_action_process($patient_id)
211 // this function is a dual function that will set up a note associated with a document or send a document via email.
213 if ($_POST['process'] != "true") {
214 return;
217 $n = new Note();
218 $n->set_owner($_SESSION['authUserID']);
219 parent::populate_object($n);
220 if ($_POST['identifier'] == "no") {
221 // associate a note with a document
222 $n->persist();
223 } elseif ($_POST['identifier'] == "yes") {
224 // send the document via email
225 $d = new Document($_POST['foreign_id']);
226 $url = $d->get_url();
227 $storagemethod = $d->get_storagemethod();
228 $couch_docid = $d->get_couch_docid();
229 $couch_revid = $d->get_couch_revid();
230 if ($couch_docid && $couch_revid) {
231 $couch = new CouchDB();
232 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
233 $resp = $couch->retrieve_doc($data);
234 $content = $resp->data;
235 if ($content=='' && $GLOBALS['couchdb_log']==1) {
236 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
237 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
238 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
239 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
240 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
241 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
242 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
243 die(xlt("File retrieval from CouchDB failed"));
245 // place it in a temporary file and will remove the file below after emailed
246 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
247 $fh = fopen($temp_couchdb_url, "w");
248 fwrite($fh, base64_decode($content));
249 fclose($fh);
250 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
251 } else {
252 $url = preg_replace("|^(.*)://|", "", $url);
253 // Collect filename and path
254 $from_all = explode("/", $url);
255 $from_filename = array_pop($from_all);
256 $from_pathname_array = array();
257 for ($i=0; $i<$d->get_path_depth(); $i++) {
258 $from_pathname_array[] = array_pop($from_all);
260 $from_pathname_array = array_reverse($from_pathname_array);
261 $from_pathname = implode("/", $from_pathname_array);
262 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
264 if (!file_exists($temp_url)) {
265 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;
267 $url = $temp_url;
268 $body_notes = attr($_POST['note']);
269 $pdetails = getPatientData($patient_id);
270 $pname = $pdetails['fname']." ".$pdetails['lname'];
271 $this->document_send($_POST['provide_email'], $body_notes, $url, $pname);
272 if ($couch_docid && $couch_revid) {
273 // remove the temporary couchdb file
274 unlink($temp_couchdb_url);
277 $this->_state = false;
278 $_POST['process'] = "";
279 return $this->view_action($patient_id, $n->get_foreign_id());
282 function default_action()
284 return $this->list_action();
287 function view_action($patient_id = "", $doc_id)
289 // Added by Rod to support document delete:
290 global $gacl_object, $phpgacl_location;
291 global $ISSUE_TYPES;
293 require_once(dirname(__FILE__) . "/../library/acl.inc");
294 require_once(dirname(__FILE__) . "/../library/lists.inc");
296 $d = new Document($doc_id);
297 $notes = $d->get_notes();
299 $this->assign("file", $d);
300 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
301 $this->assign("NOTE_ACTION", $this->_link("note"));
302 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
303 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
305 // Added by Rod to support document delete:
306 $delete_string = '';
307 if (acl_check('admin', 'super')) {
308 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
309 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
311 $this->assign("delete_string", $delete_string);
312 $this->assign("REFRESH_ACTION", $this->_link("list"));
314 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
315 "document_id=" . $d->get_id() . "&process=true");
317 // Added by Rod to support document date update:
318 $this->assign("DOCDATE", $d->get_docdate());
319 $this->assign("UPDATE_ACTION", $this->_link("update") .
320 "document_id=" . $d->get_id() . "&process=true");
322 // Added by Rod to support document issue update:
323 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
324 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
325 "pid = ? " . // AND enddate IS NULL " .
326 "ORDER BY type, begdate", array($patient_id));
327 while ($irow = sqlFetchArray($ires)) {
328 $desc = $irow['type'];
329 if ($ISSUE_TYPES[$desc]) {
330 $desc = $ISSUE_TYPES[$desc][2];
332 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
333 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
334 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
336 $this->assign("ISSUES_LIST", $issues_options);
338 // For tagging to encounter
339 // Populate the dropdown with patient's encounter list
340 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
341 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
342 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
343 "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));
344 if (sqlNumRows($result_docs) > 0) {
345 while ($row_result_docs = sqlFetchArray($result_docs)) {
346 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
347 $encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>". oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date']))) . "-" . text(xl_appt_category($row_result_docs['pc_catname'])) . "</option>";
350 $this->assign("ENC_LIST", $encOptions);
352 //clear encounter tag
353 if ($d->get_encounter_id() != 0) {
354 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
355 } else {
356 $this->assign('clear_encounter_tag', 'javascript:void(0)');
359 //Populate the dropdown with category list
360 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
361 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
362 while ($crow = sqlFetchArray($cres)) {
363 $catid = $crow['pc_catid'];
364 if ($catid < 9 && $catid != 5) {
365 continue; // Applying same logic as in new encounter page.
367 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
369 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
371 $this->assign("notes", $notes);
373 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
374 // Populate the dropdown with image procedure order list
375 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
376 $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));
377 $mapping = $this->get_mapped_procedure($d->get_id());
378 if (sqlNumRows($imgOrders) > 0) {
379 while ($row = sqlFetchArray($imgOrders)) {
380 $sel_proc = '';
381 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
382 $sel_proc = 'selected';
384 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
388 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
390 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
392 $this->_last_node = null;
394 $menu = new HTML_TreeMenu();
396 //pass an empty array because we don't want the documents for each category showing up in this list box
397 $rnode = $this->_array_recurse($this->tree->tree, array());
398 $menu->addItem($rnode);
399 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
401 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
403 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
404 $this->assign("activity", $activity);
406 return $this->list_action($patient_id);
409 function encrypt($plaintext, $key, $cypher = 'tripledes', $mode = 'cfb')
411 $td = mcrypt_module_open($cypher, '', $mode, '');
412 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
413 mcrypt_generic_init($td, $key, $iv);
414 $crypttext = mcrypt_generic($td, $plaintext);
415 mcrypt_generic_deinit($td);
416 return $iv.$crypttext;
419 function decrypt($crypttext, $key, $cypher = 'tripledes', $mode = 'cfb')
421 $plaintext = '';
422 $td = mcrypt_module_open($cypher, '', $mode, '');
423 $ivsize = mcrypt_enc_get_iv_size($td) ;
424 $iv = substr($crypttext, 0, $ivsize);
425 $crypttext = substr($crypttext, $ivsize);
426 if ($iv) {
427 mcrypt_generic_init($td, $key, $iv);
428 $plaintext = mdecrypt_generic($td, $crypttext);
430 return $plaintext;
434 * Retrieve file from hard disk / CouchDB.
435 * In case that file isn't download this function will return thumbnail image (if exist).
436 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
437 * @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.
438 * */
439 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
441 $encrypted = $_POST['encrypted'];
442 $passphrase = $_POST['passphrase'];
443 $doEncryption = false;
444 if (!$GLOBALS['hide_document_encryption'] &&
445 $encrypted == "true" &&
446 $passphrase ) {
447 $doEncryption = true;
450 //controller function ruins booleans, so need to manually re-convert to booleans
451 if ($as_file == "true") {
452 $as_file=true;
453 } else if ($as_file == "false") {
454 $as_file=false;
456 if ($original_file == "true") {
457 $original_file=true;
458 } else if ($original_file == "false") {
459 $original_file=false;
461 if ($disable_exit == "true") {
462 $disable_exit=true;
463 } else if ($disable_exit == "false") {
464 $disable_exit=false;
466 if ($show_original == "true") {
467 $show_original=true;
468 } else if ($show_original == "false") {
469 $show_original=false;
472 switch ($context) {
473 case "patient_picture":
474 $this->patientService->setPid($patient_id);
475 $document_id = $this->patientService->getPatientPictureDocumentId();
476 break;
479 $d = new Document($document_id);
480 $url = $d->get_url();
481 $th_url = $d->get_thumb_url();
483 $storagemethod = $d->get_storagemethod();
484 $couch_docid = $d->get_couch_docid();
485 $couch_revid = $d->get_couch_revid();
487 if ($couch_docid && $couch_revid && $original_file) {
488 $couch = new CouchDB();
489 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
490 $resp = $couch->retrieve_doc($data);
491 //Take thumbnail file when is not null and file is presented online
492 if (!$as_file && !is_null($th_url) && !$show_original) {
493 $content = $resp->th_data;
494 } else {
495 $content = $resp->data;
497 if ($content=='' && $GLOBALS['couchdb_log']==1) {
498 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
499 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
500 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
501 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
502 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
503 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
504 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
505 die(xl("File retrieval from CouchDB failed"));
507 if ($disable_exit == true) {
508 return base64_decode($content);
510 header('Content-Description: File Transfer');
511 header('Content-Transfer-Encoding: binary');
512 header('Expires: 0');
513 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
514 header('Pragma: public');
515 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
516 $fh = fopen($tmpcouchpath, "w");
517 fwrite($fh, base64_decode($content));
518 fclose($fh);
519 $f = fopen($tmpcouchpath, "r");
520 if ($doEncryption) {
521 $filetext = fread($f, filesize($tmpcouchpath));
522 $ciphertext = $this->encrypt($filetext, $passphrase);
523 $tmpfilepath = $GLOBALS['temporary_files_dir'];
524 $tmpfilename = "/encrypted_".$d->get_url_file();
525 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
526 fwrite($tmpfile, $ciphertext);
527 fclose($tmpfile);
528 header('Content-Disposition: attachment; filename='.$tmpfilename);
529 header("Content-Type: application/octet-stream");
530 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
531 ob_clean();
532 flush();
533 readfile($tmpfilepath.$tmpfilename);
534 unlink($tmpfilepath.$tmpfilename);
535 } else {
536 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
537 header("Content-Type: " . $d->get_mimetype());
538 header("Content-Length: " . filesize($tmpcouchpath));
539 fpassthru($f);
541 fclose($f);
542 if ($content!='') {
543 unlink($tmpcouchpath);
545 exit;//exits only if file download from CouchDB is successfull.
548 //Take thumbnail file when is not null and file is presented online
549 if (!$as_file && !is_null($th_url) && !$show_original) {
550 $url = $th_url;
553 //strip url of protocol handler
554 $url = preg_replace("|^(.*)://|", "", $url);
556 //change full path to current webroot. this is for documents that may have
557 //been moved from a different filesystem and the full path in the database
558 //is not current. this is also for documents that may of been moved to
559 //different patients. Note that the path_depth is used to see how far down
560 //the path to go. For example, originally the path_depth was always 1, which
561 //only allowed things like documents/1/<file>, but now can have more structured
562 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
563 // etc.
564 // NOTE that $from_filename and basename($url) are the same thing
565 $from_all = explode("/", $url);
566 $from_filename = array_pop($from_all);
567 $from_pathname_array = array();
568 for ($i=0; $i<$d->get_path_depth(); $i++) {
569 $from_pathname_array[] = array_pop($from_all);
571 $from_pathname_array = array_reverse($from_pathname_array);
572 $from_pathname = implode("/", $from_pathname_array);
573 if ($couch_docid && $couch_revid) {
574 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
575 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
576 } else {
577 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
580 if (file_exists($temp_url)) {
581 $url = $temp_url;
585 if (!file_exists($url)) {
586 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;
587 } else {
588 if ($original_file) {
589 //normal case when serving the file referenced in database
590 if ($disable_exit == true) {
591 $f = fopen($url, "r");
592 $filetext = fread($f, filesize($url));
593 return $filetext;
595 header('Content-Description: File Transfer');
596 header('Content-Transfer-Encoding: binary');
597 header('Expires: 0');
598 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
599 header('Pragma: public');
600 $f = fopen($url, "r");
601 if ($doEncryption) {
602 $filetext = fread($f, filesize($url));
603 $ciphertext = $this->encrypt($filetext, $passphrase);
604 $tmpfilepath = $GLOBALS['temporary_files_dir'];
605 $tmpfilename = "/encrypted_".$d->get_url_file();
606 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
607 fwrite($tmpfile, $ciphertext);
608 fclose($tmpfile);
609 header('Content-Disposition: attachment; filename='.$tmpfilename);
610 header("Content-Type: application/octet-stream");
611 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
612 ob_clean();
613 flush();
614 readfile($tmpfilepath.$tmpfilename);
615 unlink($tmpfilepath.$tmpfilename);
616 } else {
617 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
618 header("Content-Type: " . $d->get_mimetype());
619 header("Content-Length: " . filesize($url));
620 fpassthru($f);
622 exit;
623 } else {
624 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
625 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
626 if ($couch_docid && $couch_revid) {
627 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
628 } else {
629 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
631 if ($disable_exit == true) {
632 return ;
634 header("Pragma: public");
635 header("Expires: 0");
636 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
637 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
638 header("Content-Type: image/jpeg");
639 header("Content-Length: " . filesize($url));
640 $f = fopen($url, "r");
641 fpassthru($f);
642 if ($couch_docid && $couch_revid) {
643 fclose($f);
644 unlink($url);
645 $url=str_replace("_converted.jpg", '.pdf', $url);
646 unlink($url);
648 exit;
653 function queue_action($patient_id = "")
655 $messages = $this->_tpl_vars['messages'];
656 $queue_files = array();
658 //see if the repository exists and it is a directory else error
659 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
660 $dir = opendir($this->_config['repository']);
661 //read each entry in the directory
662 while (($file = readdir($dir)) !== false) {
663 //concat the filename and path
664 $file = $this->_config['repository'] .$file;
665 $file_info = array();
666 //if the filename is a file get its info and put into a tmp array
667 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
668 $file_info['filename'] = basename_international($file);
669 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
670 $d = $this->Document->document_factory_url("file://" . $file);
671 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
672 $file_info['patient_id'] = $patient_match[1];
673 $file_info['document_id'] = $d->get_id();
674 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
676 //merge the tmp array into the larger array
677 $queue_files[] = $file_info;
680 closedir($dir);
681 } else {
682 $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";
686 $this->assign("queue_files", $queue_files);
687 $this->_last_node = null;
689 $menu = new HTML_TreeMenu();
691 //pass an empty array because we don't want the documents for each category showing up in this list box
692 $rnode = $this->_array_recurse($this->tree->tree, array());
693 $menu->addItem($rnode);
694 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
696 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
698 $this->assign("messages", nl2br($messages));
699 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
702 function queue_action_process()
704 if ($_POST['process'] != "true") {
705 return;
708 $messages = $this->_tpl_vars['messages'];
710 //build a category tree so we can have a list of category ids that are valid
711 $ct = new CategoryTree(1);
712 $categories = $ct->_id_name;
714 //see if there were and posted files and assign them
715 $files = null;
716 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
718 //loop through posted files
719 foreach ($files as $doc_id => $file) {
720 //only operate on files checked as active
721 if (!$file['active']) {
722 continue;
725 //run basic validation checks
726 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
727 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
728 continue;
731 //validate that the pod exists
732 $d = new Document($doc_id);
733 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
734 $result = $d->_db->Execute($sql);
736 if (!$result || $result->EOF) {
737 //patient id does not exist
738 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
739 continue;
742 //validate that the category id exists
743 if (!isset($categories[$file['category_id']])) {
744 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
745 continue;
748 //now do the work of moving the file
749 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
751 //see if the patient dir exists in the repository and create if not
752 if (!file_exists($new_path)) {
753 if (!mkdir($new_path, 0700)) {
754 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
755 continue;
759 //fname is the name of the file after it is moved
760 $fname = $file['name'];
762 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
763 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
764 if ($patient_match[1] == $file['patient_id']) {
765 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
768 //filenames should not have funny chars
769 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
771 //see if there is an existing file with the same name and rename as necessary
772 if (file_exists($new_path.$file['name'])) {
773 $messages .= "File with same name already exists at location: " . $new_path . "\n";
774 $fname = basename_international($this->_rename_file($new_path.$file['name']));
775 $messages .= "Current file name was changed to " . $fname ."\n";
778 //now move the file
779 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
780 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
781 $d->url = "file://" .$new_path.$fname;
782 $d->set_foreign_id($file['patient_id']);
783 $d->set_mimetype($mimetype);
784 $d->persist();
785 $d->populate();
787 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
788 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
789 $d->_db->Execute($sql);
791 } else {
792 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
795 $this->assign("messages", $messages);
796 $_POST['process'] = "";
799 function move_action_process($patient_id = "", $document_id)
801 if ($_POST['process'] != "true") {
802 return;
805 $new_category_id = $_POST['new_category_id'];
806 $new_patient_id = $_POST['new_patient_id'];
808 //move to new category
809 if (is_numeric($new_category_id) && is_numeric($document_id)) {
810 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
811 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
812 //echo $sql;
813 $this->tree->_db->Execute($sql);
816 //move to new patient
817 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
818 $d = new Document($document_id);
819 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
820 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
821 $result = $d->_db->Execute($sql);
823 if (!$result || $result->EOF) {
824 //patient id does not exist
825 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
826 } else {
827 $couchsavefailed = !$d->change_patient($new_patient_id);
829 $this->_state = false;
830 if (!$couchsavefailed) {
831 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
832 } else {
833 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
835 $this->assign("messages", $messages);
836 return $this->list_action($patient_id);
838 } //in this case return the document to the queue instead of moving it
839 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
840 $d = new Document($document_id);
841 $new_path = $this->_config['repository'];
842 $fname = $d->get_url_file();
844 //see if there is an existing file with the same name and rename as necessary
845 if (file_exists($new_path.$d->get_url_file())) {
846 $messages .= "File with same name already exists in the queue.\n";
847 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
848 $messages .= "Current file name was changed to " . $fname ."\n";
851 //now move the file
852 if (rename($d->get_url_filepath(), $new_path.$fname)) {
853 $d->url = "file://" .$new_path.$fname;
854 $d->set_foreign_id("");
855 $d->persist();
856 $d->persist();
857 $d->populate();
859 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
860 $d->_db->Execute($sql);
861 $messages .= "Document returned to queue successfully.\n";
862 } else {
863 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
866 $this->_state = false;
867 $this->assign("messages", $messages);
868 return $this->list_action($patient_id);
871 $this->_state = false;
872 $this->assign("messages", $messages);
873 return $this->view_action($patient_id, $document_id);
876 function validate_action_process($patient_id = "", $document_id)
879 $d = new Document($document_id);
880 if ($d->couch_docid && $d->couch_revid) {
881 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
882 $url = $file_path.$d->get_url();
883 $couch = new CouchDB();
884 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
885 $resp = $couch->retrieve_doc($data);
886 $content = $resp->data;
887 //--------Temporarily writing the file for calculating the hash--------//
888 //-----------Will be removed after calculating the hash value----------//
889 $temp_file = fopen($url, "w");
890 fwrite($temp_file, base64_decode($content));
891 fclose($temp_file);
892 } else {
893 $url = $d->get_url();
895 //strip url of protocol handler
896 $url = preg_replace("|^(.*)://|", "", $url);
898 //change full path to current webroot. this is for documents that may have
899 //been moved from a different filesystem and the full path in the database
900 //is not current. this is also for documents that may of been moved to
901 //different patients. Note that the path_depth is used to see how far down
902 //the path to go. For example, originally the path_depth was always 1, which
903 //only allowed things like documents/1/<file>, but now can have more structured
904 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
905 // etc.
906 // NOTE that $from_filename and basename($url) are the same thing
907 $from_all = explode("/", $url);
908 $from_filename = array_pop($from_all);
909 $from_pathname_array = array();
910 for ($i=0; $i<$d->get_path_depth(); $i++) {
911 $from_pathname_array[] = array_pop($from_all);
913 $from_pathname_array = array_reverse($from_pathname_array);
914 $from_pathname = implode("/", $from_pathname_array);
915 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
916 if (file_exists($temp_url)) {
917 $url = $temp_url;
920 if ($_POST['process'] != "true") {
921 die("process is '" . $_POST['process'] . "', expected 'true'");
922 return;
925 $d = new Document($document_id);
926 $current_hash = sha1_file($url);
927 $messages = xl('Current Hash').": ".$current_hash."<br>";
928 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
929 if ($d->get_hash() == '') {
930 $d->hash = $current_hash;
931 $d->persist();
932 $d->populate();
933 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
934 } else if ($current_hash != $d->get_hash()) {
935 $messages .= xl('Hash does not match. Data integrity has been compromised.');
936 } else {
937 $messages .= xl('Document passed integrity check.');
939 $this->_state = false;
940 $this->assign("messages", $messages);
941 if ($d->couch_docid && $d->couch_revid) {
942 //Removing the temporary file which is used to create the hash
943 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
945 return $this->view_action($patient_id, $document_id);
948 // Added by Rod for metadata update.
950 function update_action_process($patient_id = "", $document_id)
953 if ($_POST['process'] != "true") {
954 die("process is '" . $_POST['process'] . "', expected 'true'");
955 return;
958 $docdate = $_POST['docdate'];
959 $docname = $_POST['docname'];
960 $issue_id = $_POST['issue_id'];
962 if (is_numeric($document_id)) {
963 $messages = '';
964 $d = new Document($document_id);
965 $file_name = $d->get_url_file();
966 if ($docname != '' &&
967 $docname != $file_name ) {
968 // Ready to rename - check for relocation
969 $old_url = $this->_check_relocation($d->get_url());
970 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
971 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
972 if (rename($old_url, $new_url)) {
973 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
974 if (file_exists($old_url)) {
975 unlink($old_url);
977 $d->url = $new_url;
978 $d->persist();
979 $d->populate();
980 $messages .= xl('Document successfully renamed.')."<br>";
981 } else {
982 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
986 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
987 $docdate = "'$docdate'";
988 } else {
989 $docdate = "NULL";
991 if (!is_numeric($issue_id)) {
992 $issue_id = 0;
994 $couch_docid = $d->get_couch_docid();
995 $couch_revid = $d->get_couch_revid();
996 if ($couch_docid && $couch_revid) {
997 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
998 "list_id = '$issue_id' " .
999 "WHERE id = '$document_id'";
1000 $this->tree->_db->Execute($sql);
1001 } else {
1002 $sql = "UPDATE documents SET docdate = $docdate, " .
1003 "list_id = '$issue_id' " .
1004 "WHERE id = '$document_id'";
1005 $this->tree->_db->Execute($sql);
1007 $messages .= xl('Document date and issue updated successfully') . "<br>";
1010 $this->_state = false;
1011 $this->assign("messages", $messages);
1012 return $this->view_action($patient_id, $document_id);
1015 function list_action($patient_id = "")
1017 $this->_last_node = null;
1018 $categories_list = $this->tree->_get_categories_array($patient_id);
1019 //print_r($categories_list);
1021 $menu = new HTML_TreeMenu();
1022 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1023 $menu->addItem($rnode);
1024 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1025 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1026 $this->assign("tree_html", $treeMenu->toHTML());
1028 $is_new = isset($_GET['patient_name']) ? 1 : false;
1029 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1030 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1031 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1032 if ($cur_pid == '00') {
1033 $cur_pid = '0';
1034 $is_new = 1;
1036 $this->assign('is_new', $is_new);
1037 $this->assign('place_hld', $place_hld);
1038 $this->assign('cur_pid', $cur_pid);
1039 $this->assign('used_msg', $used_msg);
1040 $this->assign('demo_pid', $_SESSION['pid']);
1042 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1045 /* This is a recursive function to rename a file to something that doesn't already exist.
1046 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1047 * at end) to ensure documents opened correctly by external browser viewers. If the
1048 * counter is at the end of the file, then will use it (to continue to work with older
1049 * files), however all new counters will be placed within filenames.
1051 * Modified to only deal with base file name when renaming, to avoid issues with directory
1052 * names with dots.
1054 function _rename_file($fname, $self = false)
1056 // Allow same routine for new file name check
1057 if (!file_exists($fname)) {
1058 return($fname);
1061 $path = dirname($fname);
1062 $file = basename_international($fname);
1064 $fparts = explode(".", $file);
1065 switch (count($fparts)) {
1066 case 1:
1067 // Has a single node (base file name). Create counter node with value 0
1068 $fparts[1] = '1';
1069 break;
1070 case 2:
1071 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1072 if (is_numeric($fparts[1])) {
1073 $fparts[1] += 1;
1074 } else {
1075 array_push($fparts, $fparts[1]);
1076 $fparts[1] = '1';
1078 break;
1079 default:
1080 // Multiple nodes
1081 $ix_end = count($fparts) - 1;
1082 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1083 // Switch old style to new and check again
1084 $wrk = $fparts[$ix_end - 1];
1085 $fparts[$ix_end - 1] = $fparts[$ix_end];
1086 $fparts[$ix_end] = $wrk;
1087 } else if (is_numeric($fparts[$ix_end - 1])) {
1088 $fparts[$ix_end - 1] += 1;
1089 } else {
1090 array_push($fparts, $fparts[$ix_end]);
1091 $fparts[$ix_end] = '1';
1093 break;
1096 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1098 if (file_exists($fname)) {
1099 return $this->_rename_file($fname, true);
1100 } else {
1101 return($fname);
1105 function &_array_recurse($array, $categories = array())
1107 if (!is_array($array)) {
1108 $array = array();
1110 $node = &$this->_last_node;
1111 $current_node = &$node;
1112 $expandedIcon = 'folder-expanded.gif';
1113 foreach ($array as $id => $ar) {
1114 $icon = 'folder.gif';
1115 if (is_array($ar) || !empty($id)) {
1116 if ($node == null) {
1117 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1118 $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));
1119 $this->_last_node = &$rnode;
1120 $node = &$rnode;
1121 $current_node = &$rnode;
1122 } else {
1123 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1124 $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)));
1125 $current_node = &$this->_last_node;
1128 $this->_array_recurse($ar, $categories);
1129 } else {
1130 if ($id === 0 && !empty($ar)) {
1131 $info = $this->tree->get_node_info($id);
1132 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1133 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1134 } else {
1135 //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
1136 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1137 if ($id !== 0 && is_object($node)) {
1138 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1139 $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)));
1144 // If there are documents in this document category, then add their
1145 // attributes to the current node.
1146 $icon = "file3.png";
1147 if (is_array($categories[$id])) {
1148 foreach ($categories[$id] as $doc) {
1149 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1150 // If user has no access then there will be no link.
1151 if (!acl_check_aco_spec($doc['aco_spec'])) {
1152 $link = '';
1154 if ($this->tree->get_node_name($id) == "CCR") {
1155 $current_node->addItem(new HTML_TreeNode(array(
1156 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1157 'link' => $link,
1158 'icon' => $icon,
1159 'expandedIcon' => $expandedIcon,
1160 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1161 )));
1162 } elseif ($this->tree->get_node_name($id) == "CCD") {
1163 $current_node->addItem(new HTML_TreeNode(array(
1164 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1165 'link' => $link,
1166 'icon' => $icon,
1167 'expandedIcon' => $expandedIcon,
1168 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1169 )));
1170 } else {
1171 $current_node->addItem(new HTML_TreeNode(array(
1172 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1173 'link' => $link,
1174 'icon' => $icon,
1175 'expandedIcon' => $expandedIcon
1176 )));
1181 return $node;
1184 //function for logging the errors in writing file to CouchDB/Hard Disk
1185 function document_upload_download_log($patientid, $content)
1187 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1188 $log_file = 'log.txt';
1189 if (!is_dir($log_path)) {
1190 mkdir($log_path, 0777, true);
1192 $LOG = fopen($log_path.$log_file, 'a');
1193 fwrite($LOG, $content);
1194 fclose($LOG);
1197 function document_send($email, $body, $attfile, $pname)
1199 if (empty($email)) {
1200 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1201 return;
1204 $desc = "Please check the attached patient document.\n Content:".attr($body);
1205 $mail = new MyMailer();
1206 $from_name = $GLOBALS["practice_return_email_path"];
1207 $from = $GLOBALS["practice_return_email_path"];
1208 $mail->AddReplyTo($from, $from_name);
1209 $mail->SetFrom($from, $from);
1210 $to = $email ;
1211 $to_name =$email;
1212 $mail->AddAddress($to, $to_name);
1213 $subject = "Patient documents";
1214 $mail->Subject = $subject;
1215 $mail->Body = $desc;
1216 $mail->AddAttachment($attfile);
1217 if ($mail->Send()) {
1218 $retstatus = "email_sent";
1219 } else {
1220 $email_status = $mail->ErrorInfo;
1221 //echo "EMAIL ERROR: ".$email_status;
1222 $retstatus = "email_fail";
1226 //place to hold optional code
1227 //$first_node = array_keys($t->tree);
1228 //$first_node = $first_node[0];
1229 //$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')"));
1231 //$this->_last_node = &$node1;
1233 // Function to tag a document to an encounter.
1234 function tag_action_process($patient_id = "", $document_id)
1236 if ($_POST['process'] != "true") {
1237 die("process is '" . text($_POST['process']) . "', expected 'true'");
1238 return;
1241 // Create Encounter and Tag it.
1242 $event_date = date('Y-m-d H:i:s');
1243 $encounter_id = $_POST['encounter_id'];
1244 $encounter_check = $_POST['encounter_check'];
1245 $visit_category_id = $_POST['visit_category_id'];
1247 if (is_numeric($document_id)) {
1248 $messages = '';
1249 $d = new Document($document_id);
1250 $file_name = $d->get_url_file();
1251 if (!is_numeric($encounter_id)) {
1252 $encounter_id = 0;
1255 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1256 if ($encounter_check) {
1257 $provider_id = $_SESSION['authUserID'] ;
1259 // Get the logged in user's facility
1260 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1261 $username = $facilityRow['username'];
1262 $facility = $facilityRow['facility'];
1263 $facility_id = $facilityRow['facility_id'];
1264 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1265 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1266 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1268 $conn = $GLOBALS['adodb']['db'];
1269 $encounter = $conn->GenID("sequences");
1270 $query = "INSERT INTO form_encounter SET
1271 date = ?,
1272 reason = ?,
1273 facility = ?,
1274 sensitivity = 'normal',
1275 pc_catid = ?,
1276 facility_id = ?,
1277 billing_facility = ?,
1278 provider_id = ?,
1279 pid = ?,
1280 encounter = ?";
1281 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1282 $formID = sqlInsert($query, $bindArray);
1283 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1284 $d->set_encounter_id($encounter);
1285 $this->image_result_indication($d->id, $encounter);
1286 } else {
1287 $d->set_encounter_id($encounter_id);
1288 $this->image_result_indication($d->id, $encounter_id);
1290 $d->set_encounter_check($encounter_check);
1291 $d->persist();
1293 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1296 $this->_state = false;
1297 $this->assign("messages", $messages);
1299 return $this->view_action($patient_id, $document_id);
1302 function image_procedure_action($patient_id = "", $document_id)
1305 $img_procedure_id = $_POST['image_procedure_id'];
1306 $proc_code = $_POST['procedure_code'];
1308 if (is_numeric($document_id)) {
1309 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1310 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1311 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1312 if ($img_report_id == 0) {
1313 $report_date = date('Y-m-d H:i:s');
1314 $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));
1317 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1318 if (empty($img_result)) {
1319 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));
1322 $this->image_result_indication($document_id, 0, $img_procedure_id);
1324 return $this->view_action($patient_id, $document_id);
1327 function clear_procedure_tag_action($patient_id = "", $document_id)
1329 if (is_numeric($document_id)) {
1330 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1332 return $this->view_action($patient_id, $document_id);
1335 function get_mapped_procedure($document_id)
1337 $map = array();
1338 if (is_numeric($document_id)) {
1339 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1340 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1341 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1342 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1343 where pres.document_id = ?", array($document_id));
1345 return $map;
1348 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1350 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1351 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1353 if ($encounter != 0) {
1354 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1355 } else if ($image_procedure_id != 0) {
1356 $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));
1357 } else {
1358 $ep = array('assigned_to' => $_SESSION['authUser']);
1361 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1362 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1363 setGpRelation(1, $doc_id, 6, $noteid);
1366 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1367 * Also usable for documents that may of been moved to different patients.
1369 * @param string $url - Current url string from database.
1370 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1371 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1373 * @return string
1375 function _check_relocation($url, $new_pid = null, $new_name = null)
1377 //strip url of protocol handler
1378 $url = preg_replace("|^(.*)://|", "", $url);
1379 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1380 while (current($fsnodes) != "documents") {
1381 array_shift($fsnodes);
1383 if ($new_pid) {
1384 $fsnodes[1] = $new_pid;
1386 if ($new_name) {
1387 $fsnodes[count($fsnodes)-1] = $new_name;
1389 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1390 // Make sure the url is available after corrections
1391 if ($new_pid || $new_name) {
1392 $url = $this->_rename_file($url);
1394 //Add full path and remaining nodes
1395 return $url;
1398 //clear encounter tag function
1399 function clear_encounter_tag_action($patient_id = "", $document_id)
1401 if (is_numeric($document_id)) {
1402 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1404 return $this->view_action($patient_id, $document_id);