Fix encounter report view permission to follow sensitivity setting (#704 #707)
[openemr.git] / controllers / C_Document.class.php
blobdead09d9b348788830b315cd1f02735169a7b934
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 class C_Document extends Controller {
11 var $template_mod;
12 var $documents;
13 var $document_categories;
14 var $tree;
15 var $_config;
16 var $manual_set_owner=false; // allows manual setting of a document owner/service
17 var $facilityService;
19 function __construct($template_mod = "general") {
20 parent::__construct();
21 $this->facilityService = new \services\FacilityService();
22 $this->documents = array();
23 $this->template_mod = $template_mod;
24 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
25 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
27 //get global config options for this namespace
28 $this->_config = $GLOBALS['oer_config']['documents'];
30 $this->_args = array("patient_id" => $_GET['patient_id']);
32 $this->assign("STYLE", $GLOBALS['style']);
33 $t = new CategoryTree(1);
34 //print_r($t->tree);
35 $this->tree = $t;
36 $this->Document = new Document();
39 function upload_action($patient_id,$category_id) {
40 $category_name = $this->tree->get_node_name($category_id);
41 $this->assign("category_id", $category_id);
42 $this->assign("category_name", $category_name);
43 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
44 $this->assign("patient_id", $patient_id);
46 // Added by Rod to support document template download from general_upload.html.
47 // Cloned from similar stuff in manage_document_templates.php.
48 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
49 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
50 if (file_exists($templatedir)) {
51 $dh = opendir($templatedir);
53 if ($dh) {
54 $templateslist = array();
55 while (false !== ($sfname = readdir($dh))) {
56 if (substr($sfname, 0, 1) == '.') continue;
57 $templateslist[$sfname] = $sfname;
59 closedir($dh);
60 ksort($templateslist);
61 foreach ($templateslist as $sfname) {
62 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
63 "'>" . htmlspecialchars($sfname) . "</option>";
66 $this->assign("TEMPLATES_LIST", $templates_options);
68 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
69 $this->assign("activity", $activity);
70 return $this->list_action($patient_id);
73 //Upload multiple files on single click
74 function upload_action_process() {
76 // Collect a manually set owner if this has been set
77 // Used when want to manually assign the owning user/service such as the Direct mechanism
78 $non_HTTP_owner=false;
79 if ($this->manual_set_owner) {
80 $non_HTTP_owner=$this->manual_set_owner;
83 $couchDB = false;
84 $harddisk = false;
85 if($GLOBALS['document_storage_method']==0){
86 $harddisk = true;
88 if($GLOBALS['document_storage_method']==1){
89 $couchDB = true;
92 if ($_POST['process'] != "true")
93 return;
95 $doDecryption = false;
96 $encrypted = $_POST['encrypted'];
97 $passphrase = $_POST['passphrase'];
98 if ( !$GLOBALS['hide_document_encryption'] &&
99 $encrypted && $passphrase ) {
100 $doDecryption = true;
103 if (is_numeric($_POST['category_id'])) {
104 $category_id = $_POST['category_id'];
107 $patient_id = 0;
108 if (isset($_GET['patient_id']) && !$couchDB) {
109 $patient_id = $_GET['patient_id'];
111 else if (is_numeric($_POST['patient_id'])) {
112 $patient_id = $_POST['patient_id'];
115 $sentUploadStatus = array();
116 if( count($_FILES['file']['name']) > 0){
117 $upl_inc = 0;
119 foreach($_FILES['file']['name'] as $key => $value){
120 $fname = $value;
121 $err = "";
122 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
123 $fname = $value;
124 if (empty($fname)) {
125 $fname = htmlentities("<empty>");
127 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
128 if ($_FILES['file']['size'][$key] == 0) {
129 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
131 }elseif($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])){
132 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
133 }else{
134 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
135 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
136 fclose($tmpfile);
137 if ($doDecryption) {
138 $filetext = $this->decrypt($filetext, $passphrase);
140 if ( $_POST['destination'] != '' ) {
141 $fname = $_POST['destination'];
143 $d = new Document();
144 $rc = $d->createDocument($patient_id, $category_id, $fname,
145 $_FILES['file']['type'][$key], $filetext,
146 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
147 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
148 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
149 if ($rc) {
150 $error .= $rc . "\n";
152 else {
153 $this->assign("upload_success", "true");
155 $sentUploadStatus[] = $d;
156 $this->assign("file", $sentUploadStatus);
159 // Option to run a custom plugin for each file upload.
160 // This was initially created to delete the original source file in a custom setting.
161 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
162 if (file_exists($upload_plugin)) {
163 include_once($upload_plugin);
165 $upload_plugin_pp = 'documentUploadPostProcess';
166 if (function_exists($upload_plugin_pp)) {
167 $tmp = call_user_func($upload_plugin_pp, $value, $d);
168 if ($tmp) {
169 $error = $tmp;
172 // Following is just an example of code in such a plugin file.
173 /*****************************************************
174 function documentUploadPostProcess($filename, &$d) {
175 $userid = $_SESSION['authUserID'];
176 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
177 $owner = strtolower($row['username']);
178 $dn = '1_' . ucfirst($owner);
179 $filepath = "/shared_network_directory/$dn/$filename";
180 if (@unlink($filepath)) return '';
181 return "Failed to delete '$filepath'.";
183 *****************************************************/
188 $this->assign("error", nl2br($error));
189 //$this->_state = false;
190 $_POST['process'] = "";
191 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
194 function note_action_process($patient_id) {
195 // this function is a dual function that will set up a note associated with a document or send a document via email.
197 if ($_POST['process'] != "true")
198 return;
200 $n = new Note();
201 $n->set_owner($_SESSION['authUserID']);
202 parent::populate_object($n);
203 if ($_POST['identifier'] == "no"){
204 // associate a note with a document
205 $n->persist();
206 }elseif ($_POST['identifier'] == "yes"){
207 // send the document via email
208 $d = new Document($_POST['foreign_id']);
209 $url = $d->get_url();
210 $storagemethod = $d->get_storagemethod();
211 $couch_docid = $d->get_couch_docid();
212 $couch_revid = $d->get_couch_revid();
213 if($couch_docid && $couch_revid){
214 $couch = new CouchDB();
215 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
216 $resp = $couch->retrieve_doc($data);
217 $content = $resp->data;
218 if($content=='' && $GLOBALS['couchdb_log']==1){
219 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
220 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
221 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
222 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
223 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
224 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
225 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
226 die(xlt("File retrieval from CouchDB failed"));
228 // place it in a temporary file and will remove the file below after emailed
229 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
230 $fh = fopen($temp_couchdb_url,"w");
231 fwrite($fh,base64_decode($content));
232 fclose($fh);
233 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
234 } else {
235 $url = preg_replace("|^(.*)://|","",$url);
236 // Collect filename and path
237 $from_all = explode("/",$url);
238 $from_filename = array_pop($from_all);
239 $from_pathname_array = array();
240 for ($i=0;$i<$d->get_path_depth();$i++) {
241 $from_pathname_array[] = array_pop($from_all);
243 $from_pathname_array = array_reverse($from_pathname_array);
244 $from_pathname = implode("/",$from_pathname_array);
245 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
247 if (!file_exists($temp_url)) {
248 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;
250 $url = $temp_url;
251 $body_notes = attr($_POST['note']);
252 $pdetails = getPatientData($patient_id);
253 $pname = $pdetails['fname']." ".$pdetails['lname'];
254 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
255 if ($couch_docid && $couch_revid) {
256 // remove the temporary couchdb file
257 unlink($temp_couchdb_url);
260 $this->_state = false;
261 $_POST['process'] = "";
262 return $this->view_action($patient_id,$n->get_foreign_id());
265 function default_action() {
266 return $this->list_action();
269 function view_action($patient_id="",$doc_id) {
270 // Added by Rod to support document delete:
271 global $gacl_object, $phpgacl_location;
272 global $ISSUE_TYPES;
274 require_once(dirname(__FILE__) . "/../library/acl.inc");
275 require_once(dirname(__FILE__) . "/../library/lists.inc");
277 $d = new Document($doc_id);
278 $n = new Note();
280 $notes = $n->notes_factory($doc_id);
282 $this->assign("file", $d);
283 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
284 $this->assign("NOTE_ACTION",$this->_link("note"));
285 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
286 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
288 // Added by Rod to support document delete:
289 $delete_string = '';
290 if (acl_check('admin', 'super')) {
291 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
292 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
294 $this->assign("delete_string", $delete_string);
295 $this->assign("REFRESH_ACTION",$this->_link("list"));
297 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
298 "document_id=" . $d->get_id() . "&process=true");
300 // Added by Rod to support document date update:
301 $this->assign("DOCDATE", $d->get_docdate());
302 $this->assign("UPDATE_ACTION",$this->_link("update") .
303 "document_id=" . $d->get_id() . "&process=true");
305 // Added by Rod to support document issue update:
306 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
307 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
308 "pid = ? " . // AND enddate IS NULL " .
309 "ORDER BY type, begdate", array($patient_id) );
310 while ($irow = sqlFetchArray($ires)) {
311 $desc = $irow['type'];
312 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
313 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
314 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
315 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
317 $this->assign("ISSUES_LIST", $issues_options);
319 // For tagging to encounter
320 // Populate the dropdown with patient's encounter list
321 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
322 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
323 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
324 "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));
325 if ( sqlNumRows($result_docs) > 0)
326 while($row_result_docs = sqlFetchArray($result_docs)) {
327 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
328 $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>";
330 $this->assign("ENC_LIST", $encOptions);
332 //Populate the dropdown with category list
333 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
334 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
335 while ($crow = sqlFetchArray($cres)) {
336 $catid = $crow['pc_catid'];
337 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
338 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
340 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
342 $this->assign("notes",$notes);
344 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
345 // Populate the dropdown with image procedure order list
346 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
347 $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));
348 $mapping = $this->get_mapped_procedure($d->get_id());
349 if(sqlNumRows($imgOrders) > 0){
350 while($row = sqlFetchArray($imgOrders)) {
351 $sel_proc = '';
352 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
353 $sel_proc = 'selected';
354 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
358 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
360 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
362 $this->_last_node = null;
364 $menu = new HTML_TreeMenu();
366 //pass an empty array because we don't want the documents for each category showing up in this list box
367 $rnode = $this->_array_recurse($this->tree->tree,array());
368 $menu->addItem($rnode);
369 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
371 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
373 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
374 $this->assign("activity", $activity);
376 return $this->list_action($patient_id);
379 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
381 $td = mcrypt_module_open( $cypher, '', $mode, '');
382 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
383 mcrypt_generic_init( $td, $key, $iv );
384 $crypttext = mcrypt_generic( $td, $plaintext );
385 mcrypt_generic_deinit( $td );
386 return $iv.$crypttext;
389 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
391 $plaintext = '';
392 $td = mcrypt_module_open( $cypher, '', $mode, '' );
393 $ivsize = mcrypt_enc_get_iv_size( $td) ;
394 $iv = substr( $crypttext, 0, $ivsize );
395 $crypttext = substr( $crypttext, $ivsize );
396 if( $iv )
398 mcrypt_generic_init( $td, $key, $iv );
399 $plaintext = mdecrypt_generic( $td, $crypttext );
401 return $plaintext;
405 * Retrieve file from hard disk / CouchDB.
406 * In case that file isn't download this function will return thumbnail image (if exist).
407 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
408 * */
409 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false) {
411 $encrypted = $_POST['encrypted'];
412 $passphrase = $_POST['passphrase'];
413 $doEncryption = false;
414 if ( !$GLOBALS['hide_document_encryption'] &&
415 $encrypted == "true" &&
416 $passphrase ) {
417 $doEncryption = true;
420 //controller function ruins booleans, so need to manually re-convert to booleans
421 if ($as_file == "true") {
422 $as_file=true;
424 else if ($as_file == "false") {
425 $as_file=false;
427 if ($original_file == "true") {
428 $original_file=true;
430 else if ($original_file == "false") {
431 $original_file=false;
433 if ($disable_exit == "true") {
434 $disable_exit=true;
436 else if ($disable_exit == "false") {
437 $disable_exit=false;
439 if ($show_original == "true") {
440 $show_original=true;
442 else if ($show_original == "false") {
443 $show_original=false;
446 $d = new Document($document_id);
447 $url = $d->get_url();
448 $th_url = $d->get_thumb_url();
450 $storagemethod = $d->get_storagemethod();
451 $couch_docid = $d->get_couch_docid();
452 $couch_revid = $d->get_couch_revid();
454 if($couch_docid && $couch_revid && $original_file){
455 $couch = new CouchDB();
456 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
457 $resp = $couch->retrieve_doc($data);
458 //Take thumbnail file when is not null and file is presented online
459 if (!$as_file && !is_null($th_url) && !$show_original) {
460 $content = $resp->th_data;
461 } else {
462 $content = $resp->data;
464 if($content=='' && $GLOBALS['couchdb_log']==1){
465 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
466 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
467 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
468 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
469 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
470 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
471 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
472 die(xl("File retrieval from CouchDB failed"));
474 if($disable_exit == true) {
475 return base64_decode($content);
477 header('Content-Description: File Transfer');
478 header('Content-Transfer-Encoding: binary');
479 header('Expires: 0');
480 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
481 header('Pragma: public');
482 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
483 $fh = fopen($tmpcouchpath,"w");
484 fwrite($fh,base64_decode($content));
485 fclose($fh);
486 $f = fopen($tmpcouchpath,"r");
487 if ( $doEncryption ) {
488 $filetext = fread( $f, filesize($tmpcouchpath) );
489 $ciphertext = $this->encrypt( $filetext, $passphrase );
490 $tmpfilepath = $GLOBALS['temporary_files_dir'];
491 $tmpfilename = "/encrypted_".$d->get_url_file();
492 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
493 fwrite( $tmpfile, $ciphertext );
494 fclose( $tmpfile );
495 header('Content-Disposition: attachment; filename='.$tmpfilename );
496 header("Content-Type: application/octet-stream" );
497 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
498 ob_clean();
499 flush();
500 readfile( $tmpfilepath.$tmpfilename );
501 unlink( $tmpfilepath.$tmpfilename );
502 } else {
503 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
504 header("Content-Type: " . $d->get_mimetype());
505 header("Content-Length: " . filesize($tmpcouchpath));
506 fpassthru($f);
508 fclose($f);
509 if($content!='')
510 unlink($tmpcouchpath);
511 exit;//exits only if file download from CouchDB is successfull.
514 //Take thumbnail file when is not null and file is presented online
515 if(!$as_file && !is_null($th_url) && !$show_original) {
516 $url = $th_url;
519 //strip url of protocol handler
520 $url = preg_replace("|^(.*)://|","",$url);
522 //change full path to current webroot. this is for documents that may have
523 //been moved from a different filesystem and the full path in the database
524 //is not current. this is also for documents that may of been moved to
525 //different patients. Note that the path_depth is used to see how far down
526 //the path to go. For example, originally the path_depth was always 1, which
527 //only allowed things like documents/1/<file>, but now can have more structured
528 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
529 // etc.
530 // NOTE that $from_filename and basename($url) are the same thing
531 $from_all = explode("/",$url);
532 $from_filename = array_pop($from_all);
533 $from_pathname_array = array();
534 for ($i=0;$i<$d->get_path_depth();$i++) {
535 $from_pathname_array[] = array_pop($from_all);
537 $from_pathname_array = array_reverse($from_pathname_array);
538 $from_pathname = implode("/",$from_pathname_array);
539 if($couch_docid && $couch_revid){
540 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
541 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
544 else{
545 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
548 if (file_exists($temp_url)) {
549 $url = $temp_url;
553 if (!file_exists($url)) {
554 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;
557 else {
558 if ($original_file) {
559 //normal case when serving the file referenced in database
560 if($disable_exit == true) {
561 $f = fopen($url,"r");
562 $filetext = fread( $f, filesize($url) );
563 return $filetext;
565 header('Content-Description: File Transfer');
566 header('Content-Transfer-Encoding: binary');
567 header('Expires: 0');
568 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
569 header('Pragma: public');
570 $f = fopen($url,"r");
571 if ( $doEncryption ) {
572 $filetext = fread( $f, filesize($url) );
573 $ciphertext = $this->encrypt( $filetext, $passphrase );
574 $tmpfilepath = $GLOBALS['temporary_files_dir'];
575 $tmpfilename = "/encrypted_".$d->get_url_file();
576 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
577 fwrite( $tmpfile, $ciphertext );
578 fclose( $tmpfile );
579 header('Content-Disposition: attachment; filename='.$tmpfilename );
580 header("Content-Type: application/octet-stream" );
581 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
582 ob_clean();
583 flush();
584 readfile( $tmpfilepath.$tmpfilename );
585 unlink( $tmpfilepath.$tmpfilename );
586 } else {
587 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
588 header("Content-Type: " . $d->get_mimetype());
589 header("Content-Length: " . filesize($url));
590 fpassthru($f);
592 exit;
594 else {
595 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
596 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
597 if($couch_docid && $couch_revid){
598 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
600 else{
601 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
603 if($disable_exit == true) {
604 return ;
606 header("Pragma: public");
607 header("Expires: 0");
608 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
609 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
610 header("Content-Type: image/jpeg");
611 header("Content-Length: " . filesize($url));
612 $f = fopen($url,"r");
613 fpassthru($f);
614 if($couch_docid && $couch_revid){
615 fclose($f);
616 unlink($url);
617 $url=str_replace("_converted.jpg",'.pdf',$url);
618 unlink($url);
620 exit;
625 function queue_action($patient_id="") {
626 $messages = $this->_tpl_vars['messages'];
627 $queue_files = array();
629 //see if the repository exists and it is a directory else error
630 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
631 $dir = opendir($this->_config['repository']);
632 //read each entry in the directory
633 while (($file = readdir($dir)) !== false) {
634 //concat the filename and path
635 $file = $this->_config['repository'] .$file;
636 $file_info = array();
637 //if the filename is a file get its info and put into a tmp array
638 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
639 $file_info['filename'] = basename_international($file);
640 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
641 $d = $this->Document->document_factory_url("file://" . $file);
642 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
643 $file_info['patient_id'] = $patient_match[1];
644 $file_info['document_id'] = $d->get_id();
645 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
647 //merge the tmp array into the larger array
648 $queue_files[] = $file_info;
651 closedir($dir);
653 else {
654 $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";
658 $this->assign("queue_files",$queue_files);
659 $this->_last_node = null;
661 $menu = new HTML_TreeMenu();
663 //pass an empty array because we don't want the documents for each category showing up in this list box
664 $rnode = $this->_array_recurse($this->tree->tree,array());
665 $menu->addItem($rnode);
666 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
668 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
670 $this->assign("messages",nl2br($messages));
671 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
674 function queue_action_process() {
675 if ($_POST['process'] != "true")
676 return;
678 $messages = $this->_tpl_vars['messages'];
680 //build a category tree so we can have a list of category ids that are valid
681 $ct = new CategoryTree(1);
682 $categories = $ct->_id_name;
684 //see if there were and posted files and assign them
685 $files = null;
686 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
688 //loop through posted files
689 foreach($files as $doc_id=> $file) {
690 //only operate on files checked as active
691 if (!$file['active']) continue;
693 //run basic validation checks
694 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
695 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
696 continue;
699 //validate that the pod exists
700 $d = new Document($doc_id);
701 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
702 $result = $d->_db->Execute($sql);
704 if (!$result || $result->EOF) {
705 //patient id does not exist
706 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
707 continue;
710 //validate that the category id exists
711 if (!isset($categories[$file['category_id']])) {
712 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
713 continue;
716 //now do the work of moving the file
717 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
719 //see if the patient dir exists in the repository and create if not
720 if (!file_exists($new_path)) {
721 if (!mkdir($new_path,0700)) {
722 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
723 continue;
727 //fname is the name of the file after it is moved
728 $fname = $file['name'];
730 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
731 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
732 if ($patient_match[1] == $file['patient_id']) {
733 $fname = preg_replace("/^([0-9]+)_/","",$fname);
736 //filenames should not have funny chars
737 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
739 //see if there is an existing file with the same name and rename as necessary
740 if (file_exists($new_path.$file['name'])) {
741 $messages .= "File with same name already exists at location: " . $new_path . "\n";
742 $fname = basename_international($this->_rename_file($new_path.$file['name']));
743 $messages .= "Current file name was changed to " . $fname ."\n";
746 //now move the file
747 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
748 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
749 $d->url = "file://" .$new_path.$fname;
750 $d->set_foreign_id($file['patient_id']);
751 $d->set_mimetype($mimetype);
752 $d->persist();
753 $d->populate();
755 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
756 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
757 $d->_db->Execute($sql);
760 else {
761 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
764 $this->assign("messages",$messages);
765 $_POST['process'] = "";
768 function move_action_process($patient_id="",$document_id) {
769 if ($_POST['process'] != "true")
770 return;
772 $new_category_id = $_POST['new_category_id'];
773 $new_patient_id = $_POST['new_patient_id'];
775 //move to new category
776 if (is_numeric($new_category_id) && is_numeric($document_id)) {
777 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
778 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
779 //echo $sql;
780 $this->tree->_db->Execute($sql);
783 //move to new patient
784 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
785 $d = new Document($document_id);
786 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
787 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
788 $result = $d->_db->Execute($sql);
790 if (!$result || $result->EOF) {
791 //patient id does not exist
792 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
794 else {
795 $couchsavefailed = !$d->change_patient($new_patient_id);
797 $this->_state = false;
798 if(!$couchsavefailed){
800 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
802 else{
804 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
806 $this->assign("messages",$messages);
807 return $this->list_action($patient_id);
810 //in this case return the document to the queue instead of moving it
811 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
812 $d = new Document($document_id);
813 $new_path = $this->_config['repository'];
814 $fname = $d->get_url_file();
816 //see if there is an existing file with the same name and rename as necessary
817 if (file_exists($new_path.$d->get_url_file())) {
818 $messages .= "File with same name already exists in the queue.\n";
819 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
820 $messages .= "Current file name was changed to " . $fname ."\n";
823 //now move the file
824 if (rename($d->get_url_filepath(),$new_path.$fname)) {
825 $d->url = "file://" .$new_path.$fname;
826 $d->set_foreign_id("");
827 $d->persist();
828 $d->persist();
829 $d->populate();
831 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
832 $d->_db->Execute($sql);
833 $messages .= "Document returned to queue successfully.\n";
836 else {
837 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
840 $this->_state = false;
841 $this->assign("messages",$messages);
842 return $this->list_action($patient_id);
845 $this->_state = false;
846 $this->assign("messages",$messages);
847 return $this->view_action($patient_id,$document_id);
850 function validate_action_process($patient_id="", $document_id) {
852 $d = new Document($document_id);
853 if($d->couch_docid && $d->couch_revid){
854 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
855 $url = $file_path.$d->get_url();
856 $couch = new CouchDB();
857 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
858 $resp = $couch->retrieve_doc($data);
859 $content = $resp->data;
860 //--------Temporarily writing the file for calculating the hash--------//
861 //-----------Will be removed after calculating the hash value----------//
862 $temp_file = fopen($url,"w");
863 fwrite($temp_file,base64_decode($content));
864 fclose($temp_file);
866 else{
867 $url = $d->get_url();
869 //strip url of protocol handler
870 $url = preg_replace("|^(.*)://|","",$url);
872 //change full path to current webroot. this is for documents that may have
873 //been moved from a different filesystem and the full path in the database
874 //is not current. this is also for documents that may of been moved to
875 //different patients. Note that the path_depth is used to see how far down
876 //the path to go. For example, originally the path_depth was always 1, which
877 //only allowed things like documents/1/<file>, but now can have more structured
878 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
879 // etc.
880 // NOTE that $from_filename and basename($url) are the same thing
881 $from_all = explode("/",$url);
882 $from_filename = array_pop($from_all);
883 $from_pathname_array = array();
884 for ($i=0;$i<$d->get_path_depth();$i++) {
885 $from_pathname_array[] = array_pop($from_all);
887 $from_pathname_array = array_reverse($from_pathname_array);
888 $from_pathname = implode("/",$from_pathname_array);
889 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
890 if (file_exists($temp_url)) {
891 $url = $temp_url;
894 if ($_POST['process'] != "true") {
895 die("process is '" . $_POST['process'] . "', expected 'true'");
896 return;
899 $d = new Document( $document_id );
900 $current_hash = sha1_file( $url );
901 $messages = xl('Current Hash').": ".$current_hash."<br>";
902 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
903 if ( $d->get_hash() == '' ) {
904 $d->hash = $current_hash;
905 $d->persist();
906 $d->populate();
907 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
908 } else if ( $current_hash != $d->get_hash() ) {
909 $messages .= xl('Hash does not match. Data integrity has been compromised.');
910 } else {
911 $messages .= xl('Document passed integrity check.');
913 $this->_state = false;
914 $this->assign("messages", $messages);
915 if($d->couch_docid && $d->couch_revid){
916 //Removing the temporary file which is used to create the hash
917 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
919 return $this->view_action($patient_id, $document_id);
922 // Added by Rod for metadata update.
924 function update_action_process($patient_id="", $document_id) {
926 if ($_POST['process'] != "true") {
927 die("process is '" . $_POST['process'] . "', expected 'true'");
928 return;
931 $docdate = $_POST['docdate'];
932 $docname = $_POST['docname'];
933 $issue_id = $_POST['issue_id'];
935 if (is_numeric($document_id)) {
936 $messages = '';
937 $d = new Document( $document_id );
938 $file_name = $d->get_url_file();
939 if ( $docname != '' &&
940 $docname != $file_name ) {
941 // Ready to rename - check for relocation
942 $old_url = $this->_check_relocation($d->get_url());
943 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
944 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
945 if ( rename( $old_url, $new_url ) ) {
946 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
947 if ( file_exists( $old_url ) ) {
948 unlink( $old_url );
950 $d->url = $new_url;
951 $d->persist();
952 $d->populate();
953 $messages .= xl('Document successfully renamed.')."<br>";
954 } else {
955 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
959 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
960 $docdate = "'$docdate'";
961 } else {
962 $docdate = "NULL";
964 if (!is_numeric($issue_id)) {
965 $issue_id = 0;
967 $couch_docid = $d->get_couch_docid();
968 $couch_revid = $d->get_couch_revid();
969 if($couch_docid && $couch_revid ){
970 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
971 "list_id = '$issue_id' " .
972 "WHERE id = '$document_id'";
973 $this->tree->_db->Execute($sql);
976 else{
977 $sql = "UPDATE documents SET docdate = $docdate, " .
978 "list_id = '$issue_id' " .
979 "WHERE id = '$document_id'";
980 $this->tree->_db->Execute($sql);
982 $messages .= xl('Document date and issue updated successfully') . "<br>";
985 $this->_state = false;
986 $this->assign("messages", $messages);
987 return $this->view_action($patient_id, $document_id);
990 function list_action($patient_id = "") {
991 $this->_last_node = null;
992 $categories_list = $this->tree->_get_categories_array($patient_id);
993 //print_r($categories_list);
995 $menu = new HTML_TreeMenu();
996 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
997 $menu->addItem($rnode);
998 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
999 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1001 $this->assign("tree_html",$treeMenu->toHTML());
1003 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1006 /* This is a recursive function to rename a file to something that doesn't already exist.
1007 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1008 * at end) to ensure documents opened correctly by external browser viewers. If the
1009 * counter is at the end of the file, then will use it (to continue to work with older
1010 * files), however all new counters will be placed within filenames.
1012 * Modified to only deal with base file name when renaming, to avoid issues with directory
1013 * names with dots.
1015 function _rename_file($fname, $self=FALSE) {
1016 // Allow same routine for new file name check
1017 if (!file_exists($fname)) return($fname);
1019 $path = dirname($fname);
1020 $file = basename_international($fname);
1022 $fparts = explode(".",$file);
1023 switch (count($fparts)) {
1024 case 1:
1025 // Has a single node (base file name). Create counter node with value 0
1026 $fparts[1] = '1';
1027 break;
1028 case 2:
1029 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1030 if (is_numeric($fparts[1])) {
1031 $fparts[1] += 1;
1032 } else {
1033 array_push($fparts, $fparts[1]);
1034 $fparts[1] = '1';
1036 break;
1037 default:
1038 // Multiple nodes
1039 $ix_end = count($fparts) - 1;
1040 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1041 // Switch old style to new and check again
1042 $wrk = $fparts[$ix_end - 1];
1043 $fparts[$ix_end - 1] = $fparts[$ix_end];
1044 $fparts[$ix_end] = $wrk;
1045 } else if (is_numeric($fparts[$ix_end - 1])) {
1046 $fparts[$ix_end - 1] += 1;
1047 } else {
1048 array_push($fparts, $fparts[$ix_end]);
1049 $fparts[$ix_end] = '1';
1051 break;
1054 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1056 if (file_exists($fname)) {
1057 return $this->_rename_file($fname, TRUE);
1058 } else {
1059 return($fname);
1063 function &_array_recurse($array,$categories = array()) {
1064 if (!is_array($array)) {
1065 $array = array();
1067 $node = &$this->_last_node;
1068 $current_node = &$node;
1069 $expandedIcon = 'folder-expanded.gif';
1070 foreach($array as $id => $ar) {
1071 $icon = 'folder.gif';
1072 if (is_array($ar) || !empty($id)) {
1073 if ($node == null) {
1074 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1075 $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));
1076 $this->_last_node = &$rnode;
1077 $node = &$rnode;
1078 $current_node = &$rnode;
1080 else {
1081 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1082 $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)));
1083 $current_node = &$this->_last_node;
1086 $this->_array_recurse($ar,$categories);
1088 else {
1089 if ($id === 0 && !empty($ar)) {
1090 $info = $this->tree->get_node_info($id);
1091 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1092 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1094 else {
1095 //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
1096 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1097 if ($id !== 0 && is_object($node)) {
1098 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1099 $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)));
1105 // If there are documents in this document category, then add their
1106 // attributes to the current node.
1107 $icon = "file3.png";
1108 if (is_array($categories[$id])) {
1109 foreach ($categories[$id] as $doc) {
1110 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1111 // If user has no access then there will be no link.
1112 if (!acl_check_aco_spec($doc['aco_spec'])) $link = '';
1113 if($this->tree->get_node_name($id) == "CCR"){
1114 $current_node->addItem(new HTML_TreeNode(array(
1115 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1116 'link' => $link,
1117 'icon' => $icon,
1118 'expandedIcon' => $expandedIcon,
1119 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1120 )));
1121 }elseif($this->tree->get_node_name($id) == "CCD"){
1122 $current_node->addItem(new HTML_TreeNode(array(
1123 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1124 'link' => $link,
1125 'icon' => $icon,
1126 'expandedIcon' => $expandedIcon,
1127 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1128 )));
1129 }else{
1130 $current_node->addItem(new HTML_TreeNode(array(
1131 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1132 'link' => $link,
1133 'icon' => $icon,
1134 'expandedIcon' => $expandedIcon
1135 )));
1141 return $node;
1144 //function for logging the errors in writing file to CouchDB/Hard Disk
1145 function document_upload_download_log($patientid,$content){
1146 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1147 $log_file = 'log.txt';
1148 if(!is_dir($log_path))
1149 mkdir($log_path,0777,true);
1150 $LOG = fopen($log_path.$log_file,'a');
1151 fwrite($LOG,$content);
1152 fclose($LOG);
1155 function document_send($email,$body,$attfile,$pname) {
1156 if (empty($email)) {
1157 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1158 return;
1161 $desc = "Please check the attached patient document.\n Content:".attr($body);
1162 $mail = new MyMailer();
1163 $from_name = $GLOBALS["practice_return_email_path"];
1164 $from = $GLOBALS["practice_return_email_path"];
1165 $mail->AddReplyTo($from,$from_name);
1166 $mail->SetFrom($from,$from );
1167 $to = $email ; $to_name =$email;
1168 $mail->AddAddress($to, $to_name);
1169 $subject = "Patient documents";
1170 $mail->Subject = $subject;
1171 $mail->Body = $desc;
1172 $mail->AddAttachment($attfile);
1173 if ($mail->Send()) {
1174 $retstatus = "email_sent";
1175 } else {
1176 $email_status = $mail->ErrorInfo;
1177 //echo "EMAIL ERROR: ".$email_status;
1178 $retstatus = "email_fail";
1182 //place to hold optional code
1183 //$first_node = array_keys($t->tree);
1184 //$first_node = $first_node[0];
1185 //$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')"));
1187 //$this->_last_node = &$node1;
1189 // Function to tag a document to an encounter.
1190 function tag_action_process($patient_id="", $document_id) {
1191 if ($_POST['process'] != "true") {
1192 die("process is '" . text($_POST['process']) . "', expected 'true'");
1193 return;
1196 // Create Encounter and Tag it.
1197 $event_date = date('Y-m-d H:i:s');
1198 $encounter_id = $_POST['encounter_id'];
1199 $encounter_check = $_POST['encounter_check'];
1200 $visit_category_id = $_POST['visit_category_id'];
1202 if (is_numeric($document_id)) {
1203 $messages = '';
1204 $d = new Document( $document_id );
1205 $file_name = $d->get_url_file();
1206 if (!is_numeric($encounter_id)) {
1207 $encounter_id = 0;
1210 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1211 if ($encounter_check) {
1212 $provider_id = $_SESSION['authUserID'] ;
1214 // Get the logged in user's facility
1215 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1216 $username = $facilityRow['username'];
1217 $facility = $facilityRow['facility'];
1218 $facility_id = $facilityRow['facility_id'];
1219 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1220 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1221 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1223 $conn = $GLOBALS['adodb']['db'];
1224 $encounter = $conn->GenID("sequences");
1225 $query = "INSERT INTO form_encounter SET
1226 date = ?,
1227 reason = ?,
1228 facility = ?,
1229 sensitivity = 'normal',
1230 pc_catid = ?,
1231 facility_id = ?,
1232 billing_facility = ?,
1233 provider_id = ?,
1234 pid = ?,
1235 encounter = ?";
1236 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1237 $formID = sqlInsert($query,$bindArray);
1238 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1239 $d->set_encounter_id($encounter);
1240 $this->image_result_indication($d->id, $encounter);
1242 } else {
1243 $d->set_encounter_id($encounter_id);
1244 $this->image_result_indication($d->id, $encounter_id);
1246 $d->set_encounter_check($encounter_check);
1247 $d->persist();
1249 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1252 $this->_state = false;
1253 $this->assign("messages", $messages);
1255 return $this->view_action($patient_id, $document_id);
1258 function image_procedure_action($patient_id="",$document_id){
1260 $img_procedure_id = $_POST['image_procedure_id'];
1261 $proc_code = $_POST['procedure_code'];
1263 if(is_numeric($document_id)){
1265 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1266 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1267 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1268 if($img_report_id == 0){
1269 $report_date = date('Y-m-d H:i:s');
1270 $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));
1273 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1274 if(empty($img_result)){
1275 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));
1278 $this->image_result_indication($document_id, 0,$img_procedure_id);
1280 return $this->view_action($patient_id, $document_id);
1283 function clear_procedure_tag_action($patient_id="",$document_id){
1284 if(is_numeric($document_id)){
1285 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1287 return $this->view_action($patient_id, $document_id);
1290 function get_mapped_procedure($document_id){
1291 $map = array();
1292 if(is_numeric($document_id)){
1293 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1294 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1295 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1296 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1297 where pres.document_id = ?",array($document_id));
1299 return $map;
1302 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0){
1303 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1304 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1306 if($encounter != 0) {
1307 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1309 else if($image_procedure_id != 0){
1310 $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));
1312 else{
1313 $ep = array('assigned_to' => $_SESSION['authUser']);
1316 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1317 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1318 setGpRelation(1, $doc_id, 6, $noteid);
1321 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1322 * Also usable for documents that may of been moved to different patients.
1324 * @param string $url - Current url string from database.
1325 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1326 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1328 * @return string
1330 function _check_relocation($url, $new_pid = null, $new_name = null) {
1331 //strip url of protocol handler
1332 $url = preg_replace("|^(.*)://|","",$url);
1333 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1334 while (current($fsnodes) != "documents") {
1335 array_shift($fsnodes);
1337 if ($new_pid) {
1338 $fsnodes[1] = $new_pid;
1340 if ($new_name) {
1341 $fsnodes[count($fsnodes)-1] = $new_name;
1343 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1344 // Make sure the url is available after corrections
1345 if ($new_pid || $new_name) {
1346 $url = $this->_rename_file($url);
1348 //Add full path and remaining nodes
1349 return $url;