Centralized formatting.inc.php include
[openemr.git] / controllers / C_Document.class.php
blobd62ff6b08b966e6206f49bcc74bc5dc9015827f6
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
18 function __construct($template_mod = "general") {
19 parent::__construct();
20 $this->documents = array();
21 $this->template_mod = $template_mod;
22 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
23 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
25 //get global config options for this namespace
26 $this->_config = $GLOBALS['oer_config']['documents'];
28 $this->_args = array("patient_id" => $_GET['patient_id']);
30 $this->assign("STYLE", $GLOBALS['style']);
31 $t = new CategoryTree(1);
32 //print_r($t->tree);
33 $this->tree = $t;
34 $this->Document = new Document();
37 function upload_action($patient_id,$category_id) {
38 $category_name = $this->tree->get_node_name($category_id);
39 $this->assign("category_id", $category_id);
40 $this->assign("category_name", $category_name);
41 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
42 $this->assign("patient_id", $patient_id);
44 // Added by Rod to support document template download from general_upload.html.
45 // Cloned from similar stuff in manage_document_templates.php.
46 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
47 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
48 if (file_exists($templatedir)) {
49 $dh = opendir($templatedir);
51 if ($dh) {
52 $templateslist = array();
53 while (false !== ($sfname = readdir($dh))) {
54 if (substr($sfname, 0, 1) == '.') continue;
55 $templateslist[$sfname] = $sfname;
57 closedir($dh);
58 ksort($templateslist);
59 foreach ($templateslist as $sfname) {
60 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
61 "'>" . htmlspecialchars($sfname) . "</option>";
64 $this->assign("TEMPLATES_LIST", $templates_options);
66 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
67 $this->assign("activity", $activity);
68 return $this->list_action($patient_id);
71 //Upload multiple files on single click
72 function upload_action_process() {
74 // Collect a manually set owner if this has been set
75 // Used when want to manually assign the owning user/service such as the Direct mechanism
76 $non_HTTP_owner=false;
77 if ($this->manual_set_owner) {
78 $non_HTTP_owner=$this->manual_set_owner;
81 $couchDB = false;
82 $harddisk = false;
83 if($GLOBALS['document_storage_method']==0){
84 $harddisk = true;
86 if($GLOBALS['document_storage_method']==1){
87 $couchDB = true;
90 if ($_POST['process'] != "true")
91 return;
93 $doDecryption = false;
94 $encrypted = $_POST['encrypted'];
95 $passphrase = $_POST['passphrase'];
96 if ( !$GLOBALS['hide_document_encryption'] &&
97 $encrypted && $passphrase ) {
98 $doDecryption = true;
101 if (is_numeric($_POST['category_id'])) {
102 $category_id = $_POST['category_id'];
105 $patient_id = 0;
106 if (isset($_GET['patient_id']) && !$couchDB) {
107 $patient_id = $_GET['patient_id'];
109 else if (is_numeric($_POST['patient_id'])) {
110 $patient_id = $_POST['patient_id'];
113 $sentUploadStatus = array();
114 if( count($_FILES['file']['name']) > 0){
115 $upl_inc = 0;
116 foreach($_FILES['file']['name'] as $key => $value){
117 $fname = $value;
118 $err = "";
119 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
120 $fname = $value;
121 if (empty($fname)) {
122 $fname = htmlentities("<empty>");
124 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
125 if ($_FILES['file']['size'][$key] == 0) {
126 $error .= "The system does not permit uploading files of with size 0.\n";
128 }else{
129 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
130 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
131 fclose($tmpfile);
132 if ($doDecryption) {
133 $filetext = $this->decrypt($filetext, $passphrase);
135 if ( $_POST['destination'] != '' ) {
136 $fname = $_POST['destination'];
138 $d = new Document();
139 $rc = $d->createDocument($patient_id, $category_id, $fname,
140 $_FILES['file']['type'][$key], $filetext,
141 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
142 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
143 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
144 if ($rc) {
145 $error .= $rc . "\n";
147 else {
148 $this->assign("upload_success", "true");
150 $sentUploadStatus[] = $d;
151 $this->assign("file", $sentUploadStatus);
154 // Option to run a custom plugin for each file upload.
155 // This was initially created to delete the original source file in a custom setting.
156 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
157 if (file_exists($upload_plugin)) {
158 include_once($upload_plugin);
160 $upload_plugin_pp = 'documentUploadPostProcess';
161 if (function_exists($upload_plugin_pp)) {
162 $tmp = call_user_func($upload_plugin_pp, $value, $d);
163 if ($tmp) {
164 $error = $tmp;
167 // Following is just an example of code in such a plugin file.
168 /*****************************************************
169 function documentUploadPostProcess($filename, &$d) {
170 $userid = $_SESSION['authUserID'];
171 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
172 $owner = strtolower($row['username']);
173 $dn = '1_' . ucfirst($owner);
174 $filepath = "/shared_network_directory/$dn/$filename";
175 if (@unlink($filepath)) return '';
176 return "Failed to delete '$filepath'.";
178 *****************************************************/
183 $this->assign("error", nl2br($error));
184 //$this->_state = false;
185 $_POST['process'] = "";
186 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
189 function note_action_process($patient_id) {
190 // this function is a dual function that will set up a note associated with a document or send a document via email.
192 if ($_POST['process'] != "true")
193 return;
195 $n = new Note();
196 $n->set_owner($_SESSION['authUserID']);
197 parent::populate_object($n);
198 if ($_POST['identifier'] == "no"){
199 // associate a note with a document
200 $n->persist();
201 }elseif ($_POST['identifier'] == "yes"){
202 // send the document via email
203 $d = new Document($_POST['foreign_id']);
204 $url = $d->get_url();
205 $storagemethod = $d->get_storagemethod();
206 $couch_docid = $d->get_couch_docid();
207 $couch_revid = $d->get_couch_revid();
208 if($couch_docid && $couch_revid){
209 $couch = new CouchDB();
210 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
211 $resp = $couch->retrieve_doc($data);
212 $content = $resp->data;
213 if($content=='' && $GLOBALS['couchdb_log']==1){
214 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
215 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
216 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
217 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
218 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
219 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
220 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
221 die(xlt("File retrieval from CouchDB failed"));
223 // place it in a temporary file and will remove the file below after emailed
224 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
225 $fh = fopen($temp_couchdb_url,"w");
226 fwrite($fh,base64_decode($content));
227 fclose($fh);
228 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
229 } else {
230 $url = preg_replace("|^(.*)://|","",$url);
231 // Collect filename and path
232 $from_all = explode("/",$url);
233 $from_filename = array_pop($from_all);
234 $from_pathname_array = array();
235 for ($i=0;$i<$d->get_path_depth();$i++) {
236 $from_pathname_array[] = array_pop($from_all);
238 $from_pathname_array = array_reverse($from_pathname_array);
239 $from_pathname = implode("/",$from_pathname_array);
240 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
242 if (!file_exists($temp_url)) {
243 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;
245 $url = $temp_url;
246 $body_notes = attr($_POST['note']);
247 $pdetails = getPatientData($patient_id);
248 $pname = $pdetails['fname']." ".$pdetails['lname'];
249 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
250 if ($couch_docid && $couch_revid) {
251 // remove the temporary couchdb file
252 unlink($temp_couchdb_url);
255 $this->_state = false;
256 $_POST['process'] = "";
257 return $this->view_action($patient_id,$n->get_foreign_id());
260 function default_action() {
261 return $this->list_action();
264 function view_action($patient_id="",$doc_id) {
265 // Added by Rod to support document delete:
266 global $gacl_object, $phpgacl_location;
267 global $ISSUE_TYPES;
269 require_once(dirname(__FILE__) . "/../library/acl.inc");
270 require_once(dirname(__FILE__) . "/../library/lists.inc");
272 $d = new Document($doc_id);
273 $n = new Note();
275 $notes = $n->notes_factory($doc_id);
277 $this->assign("file", $d);
278 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
279 $this->assign("NOTE_ACTION",$this->_link("note"));
280 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
281 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
283 // Added by Rod to support document delete:
284 $delete_string = '';
285 if (acl_check('admin', 'super')) {
286 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
287 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
289 $this->assign("delete_string", $delete_string);
290 $this->assign("REFRESH_ACTION",$this->_link("list"));
292 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
293 "document_id=" . $d->get_id() . "&process=true");
295 // Added by Rod to support document date update:
296 $this->assign("DOCDATE", $d->get_docdate());
297 $this->assign("UPDATE_ACTION",$this->_link("update") .
298 "document_id=" . $d->get_id() . "&process=true");
300 // Added by Rod to support document issue update:
301 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
302 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
303 "pid = ? " . // AND enddate IS NULL " .
304 "ORDER BY type, begdate", array($patient_id) );
305 while ($irow = sqlFetchArray($ires)) {
306 $desc = $irow['type'];
307 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
308 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
309 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
310 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
312 $this->assign("ISSUES_LIST", $issues_options);
314 // For tagging to encounter
315 // Populate the dropdown with patient's encounter list
316 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
317 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
318 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
319 "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));
320 if ( sqlNumRows($result_docs) > 0)
321 while($row_result_docs = sqlFetchArray($result_docs)) {
322 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
323 $encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>". oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date']))) . "-" . text($row_result_docs['pc_catname'])."</option>";
325 $this->assign("ENC_LIST", $encOptions);
327 //Populate the dropdown with category list
328 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
329 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
330 while ($crow = sqlFetchArray($cres)) {
331 $catid = $crow['pc_catid'];
332 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
333 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
335 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
337 $this->assign("notes",$notes);
339 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
340 // Populate the dropdown with image procedure order list
341 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
342 $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));
343 $mapping = $this->get_mapped_procedure($d->get_id());
344 if(sqlNumRows($imgOrders) > 0){
345 while($row = sqlFetchArray($imgOrders)) {
346 $sel_proc = '';
347 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
348 $sel_proc = 'selected';
349 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
353 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
355 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
357 $this->_last_node = null;
359 $menu = new HTML_TreeMenu();
361 //pass an empty array because we don't want the documents for each category showing up in this list box
362 $rnode = $this->_array_recurse($this->tree->tree,array());
363 $menu->addItem($rnode);
364 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
366 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
368 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
369 $this->assign("activity", $activity);
371 return $this->list_action($patient_id);
374 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
376 $td = mcrypt_module_open( $cypher, '', $mode, '');
377 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
378 mcrypt_generic_init( $td, $key, $iv );
379 $crypttext = mcrypt_generic( $td, $plaintext );
380 mcrypt_generic_deinit( $td );
381 return $iv.$crypttext;
384 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
386 $plaintext = '';
387 $td = mcrypt_module_open( $cypher, '', $mode, '' );
388 $ivsize = mcrypt_enc_get_iv_size( $td) ;
389 $iv = substr( $crypttext, 0, $ivsize );
390 $crypttext = substr( $crypttext, $ivsize );
391 if( $iv )
393 mcrypt_generic_init( $td, $key, $iv );
394 $plaintext = mdecrypt_generic( $td, $crypttext );
396 return $plaintext;
400 * Retrieve file from hard disk / CouchDB.
401 * In case that file isn't download this function will return thumbnail image (if exist).
402 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
403 * */
404 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false) {
406 $encrypted = $_POST['encrypted'];
407 $passphrase = $_POST['passphrase'];
408 $doEncryption = false;
409 if ( !$GLOBALS['hide_document_encryption'] &&
410 $encrypted == "true" &&
411 $passphrase ) {
412 $doEncryption = true;
415 //controller function ruins booleans, so need to manually re-convert to booleans
416 if ($as_file == "true") {
417 $as_file=true;
419 else if ($as_file == "false") {
420 $as_file=false;
422 if ($original_file == "true") {
423 $original_file=true;
425 else if ($original_file == "false") {
426 $original_file=false;
428 if ($disable_exit == "true") {
429 $disable_exit=true;
431 else if ($disable_exit == "false") {
432 $disable_exit=false;
434 if ($show_original == "true") {
435 $show_original=true;
437 else if ($show_original == "false") {
438 $show_original=false;
441 $d = new Document($document_id);
442 $url = $d->get_url();
443 $th_url = $d->get_thumb_url();
445 $storagemethod = $d->get_storagemethod();
446 $couch_docid = $d->get_couch_docid();
447 $couch_revid = $d->get_couch_revid();
449 if($couch_docid && $couch_revid && $original_file){
450 $couch = new CouchDB();
451 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
452 $resp = $couch->retrieve_doc($data);
453 //Take thumbnail file when is not null and file is presented online
454 if (!$as_file && !is_null($th_url) && !$show_original) {
455 $content = $resp->th_data;
456 } else {
457 $content = $resp->data;
459 if($content=='' && $GLOBALS['couchdb_log']==1){
460 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
461 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
462 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
463 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
464 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
465 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
466 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
467 die(xl("File retrieval from CouchDB failed"));
469 if($disable_exit == true) {
470 return base64_decode($content);
472 header('Content-Description: File Transfer');
473 header('Content-Transfer-Encoding: binary');
474 header('Expires: 0');
475 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
476 header('Pragma: public');
477 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
478 $fh = fopen($tmpcouchpath,"w");
479 fwrite($fh,base64_decode($content));
480 fclose($fh);
481 $f = fopen($tmpcouchpath,"r");
482 if ( $doEncryption ) {
483 $filetext = fread( $f, filesize($tmpcouchpath) );
484 $ciphertext = $this->encrypt( $filetext, $passphrase );
485 $tmpfilepath = $GLOBALS['temporary_files_dir'];
486 $tmpfilename = "/encrypted_".$d->get_url_file();
487 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
488 fwrite( $tmpfile, $ciphertext );
489 fclose( $tmpfile );
490 header('Content-Disposition: attachment; filename='.$tmpfilename );
491 header("Content-Type: application/octet-stream" );
492 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
493 ob_clean();
494 flush();
495 readfile( $tmpfilepath.$tmpfilename );
496 unlink( $tmpfilepath.$tmpfilename );
497 } else {
498 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
499 header("Content-Type: " . $d->get_mimetype());
500 header("Content-Length: " . filesize($tmpcouchpath));
501 fpassthru($f);
503 fclose($f);
504 if($content!='')
505 unlink($tmpcouchpath);
506 exit;//exits only if file download from CouchDB is successfull.
509 //Take thumbnail file when is not null and file is presented online
510 if(!$as_file && !is_null($th_url) && !$show_original) {
511 $url = $th_url;
514 //strip url of protocol handler
515 $url = preg_replace("|^(.*)://|","",$url);
517 //change full path to current webroot. this is for documents that may have
518 //been moved from a different filesystem and the full path in the database
519 //is not current. this is also for documents that may of been moved to
520 //different patients. Note that the path_depth is used to see how far down
521 //the path to go. For example, originally the path_depth was always 1, which
522 //only allowed things like documents/1/<file>, but now can have more structured
523 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
524 // etc.
525 // NOTE that $from_filename and basename($url) are the same thing
526 $from_all = explode("/",$url);
527 $from_filename = array_pop($from_all);
528 $from_pathname_array = array();
529 for ($i=0;$i<$d->get_path_depth();$i++) {
530 $from_pathname_array[] = array_pop($from_all);
532 $from_pathname_array = array_reverse($from_pathname_array);
533 $from_pathname = implode("/",$from_pathname_array);
534 if($couch_docid && $couch_revid){
535 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
536 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
539 else{
540 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
543 if (file_exists($temp_url)) {
544 $url = $temp_url;
548 if (!file_exists($url)) {
549 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;
552 else {
553 if ($original_file) {
554 //normal case when serving the file referenced in database
555 if($disable_exit == true) {
556 $f = fopen($url,"r");
557 $filetext = fread( $f, filesize($url) );
558 return $filetext;
560 header('Content-Description: File Transfer');
561 header('Content-Transfer-Encoding: binary');
562 header('Expires: 0');
563 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
564 header('Pragma: public');
565 $f = fopen($url,"r");
566 if ( $doEncryption ) {
567 $filetext = fread( $f, filesize($url) );
568 $ciphertext = $this->encrypt( $filetext, $passphrase );
569 $tmpfilepath = $GLOBALS['temporary_files_dir'];
570 $tmpfilename = "/encrypted_".$d->get_url_file();
571 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
572 fwrite( $tmpfile, $ciphertext );
573 fclose( $tmpfile );
574 header('Content-Disposition: attachment; filename='.$tmpfilename );
575 header("Content-Type: application/octet-stream" );
576 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
577 ob_clean();
578 flush();
579 readfile( $tmpfilepath.$tmpfilename );
580 unlink( $tmpfilepath.$tmpfilename );
581 } else {
582 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
583 header("Content-Type: " . $d->get_mimetype());
584 header("Content-Length: " . filesize($url));
585 fpassthru($f);
587 exit;
589 else {
590 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
591 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
592 if($couch_docid && $couch_revid){
593 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
595 else{
596 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
598 if($disable_exit == true) {
599 return ;
601 header("Pragma: public");
602 header("Expires: 0");
603 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
604 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
605 header("Content-Type: image/jpeg");
606 header("Content-Length: " . filesize($url));
607 $f = fopen($url,"r");
608 fpassthru($f);
609 if($couch_docid && $couch_revid){
610 fclose($f);
611 unlink($url);
612 $url=str_replace("_converted.jpg",'.pdf',$url);
613 unlink($url);
615 exit;
620 function queue_action($patient_id="") {
621 $messages = $this->_tpl_vars['messages'];
622 $queue_files = array();
624 //see if the repository exists and it is a directory else error
625 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
626 $dir = opendir($this->_config['repository']);
627 //read each entry in the directory
628 while (($file = readdir($dir)) !== false) {
629 //concat the filename and path
630 $file = $this->_config['repository'] .$file;
631 $file_info = array();
632 //if the filename is a file get its info and put into a tmp array
633 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
634 $file_info['filename'] = basename_international($file);
635 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
636 $d = $this->Document->document_factory_url("file://" . $file);
637 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
638 $file_info['patient_id'] = $patient_match[1];
639 $file_info['document_id'] = $d->get_id();
640 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
642 //merge the tmp array into the larger array
643 $queue_files[] = $file_info;
646 closedir($dir);
648 else {
649 $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";
653 $this->assign("queue_files",$queue_files);
654 $this->_last_node = null;
656 $menu = new HTML_TreeMenu();
658 //pass an empty array because we don't want the documents for each category showing up in this list box
659 $rnode = $this->_array_recurse($this->tree->tree,array());
660 $menu->addItem($rnode);
661 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
663 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
665 $this->assign("messages",nl2br($messages));
666 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
669 function queue_action_process() {
670 if ($_POST['process'] != "true")
671 return;
673 $messages = $this->_tpl_vars['messages'];
675 //build a category tree so we can have a list of category ids that are valid
676 $ct = new CategoryTree(1);
677 $categories = $ct->_id_name;
679 //see if there were and posted files and assign them
680 $files = null;
681 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
683 //loop through posted files
684 foreach($files as $doc_id=> $file) {
685 //only operate on files checked as active
686 if (!$file['active']) continue;
688 //run basic validation checks
689 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
690 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
691 continue;
694 //validate that the pod exists
695 $d = new Document($doc_id);
696 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
697 $result = $d->_db->Execute($sql);
699 if (!$result || $result->EOF) {
700 //patient id does not exist
701 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
702 continue;
705 //validate that the category id exists
706 if (!isset($categories[$file['category_id']])) {
707 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
708 continue;
711 //now do the work of moving the file
712 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
714 //see if the patient dir exists in the repository and create if not
715 if (!file_exists($new_path)) {
716 if (!mkdir($new_path,0700)) {
717 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
718 continue;
722 //fname is the name of the file after it is moved
723 $fname = $file['name'];
725 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
726 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
727 if ($patient_match[1] == $file['patient_id']) {
728 $fname = preg_replace("/^([0-9]+)_/","",$fname);
731 //filenames should not have funny chars
732 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
734 //see if there is an existing file with the same name and rename as necessary
735 if (file_exists($new_path.$file['name'])) {
736 $messages .= "File with same name already exists at location: " . $new_path . "\n";
737 $fname = basename_international($this->_rename_file($new_path.$file['name']));
738 $messages .= "Current file name was changed to " . $fname ."\n";
741 //now move the file
742 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
743 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
744 $d->url = "file://" .$new_path.$fname;
745 $d->set_foreign_id($file['patient_id']);
746 $d->set_mimetype($mimetype);
747 $d->persist();
748 $d->populate();
750 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
751 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
752 $d->_db->Execute($sql);
755 else {
756 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
759 $this->assign("messages",$messages);
760 $_POST['process'] = "";
763 function move_action_process($patient_id="",$document_id) {
764 if ($_POST['process'] != "true")
765 return;
767 $new_category_id = $_POST['new_category_id'];
768 $new_patient_id = $_POST['new_patient_id'];
770 //move to new category
771 if (is_numeric($new_category_id) && is_numeric($document_id)) {
772 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
773 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
774 //echo $sql;
775 $this->tree->_db->Execute($sql);
778 //move to new patient
779 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
780 $d = new Document($document_id);
781 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
782 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
783 $result = $d->_db->Execute($sql);
785 if (!$result || $result->EOF) {
786 //patient id does not exist
787 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
789 else {
790 $couchsavefailed = !$d->change_patient($new_patient_id);
792 $this->_state = false;
793 if(!$couchsavefailed){
795 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
797 else{
799 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
801 $this->assign("messages",$messages);
802 return $this->list_action($patient_id);
805 //in this case return the document to the queue instead of moving it
806 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
807 $d = new Document($document_id);
808 $new_path = $this->_config['repository'];
809 $fname = $d->get_url_file();
811 //see if there is an existing file with the same name and rename as necessary
812 if (file_exists($new_path.$d->get_url_file())) {
813 $messages .= "File with same name already exists in the queue.\n";
814 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
815 $messages .= "Current file name was changed to " . $fname ."\n";
818 //now move the file
819 if (rename($d->get_url_filepath(),$new_path.$fname)) {
820 $d->url = "file://" .$new_path.$fname;
821 $d->set_foreign_id("");
822 $d->persist();
823 $d->persist();
824 $d->populate();
826 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
827 $d->_db->Execute($sql);
828 $messages .= "Document returned to queue successfully.\n";
831 else {
832 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
835 $this->_state = false;
836 $this->assign("messages",$messages);
837 return $this->list_action($patient_id);
840 $this->_state = false;
841 $this->assign("messages",$messages);
842 return $this->view_action($patient_id,$document_id);
845 function validate_action_process($patient_id="", $document_id) {
847 $d = new Document($document_id);
848 if($d->couch_docid && $d->couch_revid){
849 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
850 $url = $file_path.$d->get_url();
851 $couch = new CouchDB();
852 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
853 $resp = $couch->retrieve_doc($data);
854 $content = $resp->data;
855 //--------Temporarily writing the file for calculating the hash--------//
856 //-----------Will be removed after calculating the hash value----------//
857 $temp_file = fopen($url,"w");
858 fwrite($temp_file,base64_decode($content));
859 fclose($temp_file);
861 else{
862 $url = $d->get_url();
864 //strip url of protocol handler
865 $url = preg_replace("|^(.*)://|","",$url);
867 //change full path to current webroot. this is for documents that may have
868 //been moved from a different filesystem and the full path in the database
869 //is not current. this is also for documents that may of been moved to
870 //different patients. Note that the path_depth is used to see how far down
871 //the path to go. For example, originally the path_depth was always 1, which
872 //only allowed things like documents/1/<file>, but now can have more structured
873 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
874 // etc.
875 // NOTE that $from_filename and basename($url) are the same thing
876 $from_all = explode("/",$url);
877 $from_filename = array_pop($from_all);
878 $from_pathname_array = array();
879 for ($i=0;$i<$d->get_path_depth();$i++) {
880 $from_pathname_array[] = array_pop($from_all);
882 $from_pathname_array = array_reverse($from_pathname_array);
883 $from_pathname = implode("/",$from_pathname_array);
884 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
885 if (file_exists($temp_url)) {
886 $url = $temp_url;
889 if ($_POST['process'] != "true") {
890 die("process is '" . $_POST['process'] . "', expected 'true'");
891 return;
894 $d = new Document( $document_id );
895 $current_hash = sha1_file( $url );
896 $messages = xl('Current Hash').": ".$current_hash."<br>";
897 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
898 if ( $d->get_hash() == '' ) {
899 $d->hash = $current_hash;
900 $d->persist();
901 $d->populate();
902 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
903 } else if ( $current_hash != $d->get_hash() ) {
904 $messages .= xl('Hash does not match. Data integrity has been compromised.');
905 } else {
906 $messages .= xl('Document passed integrity check.');
908 $this->_state = false;
909 $this->assign("messages", $messages);
910 if($d->couch_docid && $d->couch_revid){
911 //Removing the temporary file which is used to create the hash
912 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
914 return $this->view_action($patient_id, $document_id);
917 // Added by Rod for metadata update.
919 function update_action_process($patient_id="", $document_id) {
921 if ($_POST['process'] != "true") {
922 die("process is '" . $_POST['process'] . "', expected 'true'");
923 return;
926 $docdate = $_POST['docdate'];
927 $docname = $_POST['docname'];
928 $issue_id = $_POST['issue_id'];
930 if (is_numeric($document_id)) {
931 $messages = '';
932 $d = new Document( $document_id );
933 $file_name = $d->get_url_file();
934 if ( $docname != '' &&
935 $docname != $file_name ) {
936 // Ready to rename - check for relocation
937 $old_url = $this->_check_relocation($d->get_url());
938 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
939 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
940 if ( rename( $old_url, $new_url ) ) {
941 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
942 if ( file_exists( $old_url ) ) {
943 unlink( $old_url );
945 $d->url = $new_url;
946 $d->persist();
947 $d->populate();
948 $messages .= xl('Document successfully renamed.')."<br>";
949 } else {
950 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
954 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
955 $docdate = "'$docdate'";
956 } else {
957 $docdate = "NULL";
959 if (!is_numeric($issue_id)) {
960 $issue_id = 0;
962 $couch_docid = $d->get_couch_docid();
963 $couch_revid = $d->get_couch_revid();
964 if($couch_docid && $couch_revid ){
965 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
966 "list_id = '$issue_id' " .
967 "WHERE id = '$document_id'";
968 $this->tree->_db->Execute($sql);
971 else{
972 $sql = "UPDATE documents SET docdate = $docdate, " .
973 "list_id = '$issue_id' " .
974 "WHERE id = '$document_id'";
975 $this->tree->_db->Execute($sql);
977 $messages .= xl('Document date and issue updated successfully') . "<br>";
980 $this->_state = false;
981 $this->assign("messages", $messages);
982 return $this->view_action($patient_id, $document_id);
985 function list_action($patient_id = "") {
986 $this->_last_node = null;
987 $categories_list = $this->tree->_get_categories_array($patient_id);
988 //print_r($categories_list);
990 $menu = new HTML_TreeMenu();
991 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
992 $menu->addItem($rnode);
993 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
994 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
996 $this->assign("tree_html",$treeMenu->toHTML());
998 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1001 /* This is a recursive function to rename a file to something that doesn't already exist.
1002 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1003 * at end) to ensure documents opened correctly by external browser viewers. If the
1004 * counter is at the end of the file, then will use it (to continue to work with older
1005 * files), however all new counters will be placed within filenames.
1007 * Modified to only deal with base file name when renaming, to avoid issues with directory
1008 * names with dots.
1010 function _rename_file($fname, $self=FALSE) {
1011 // Allow same routine for new file name check
1012 if (!file_exists($fname)) return($fname);
1014 $path = dirname($fname);
1015 $file = basename_international($fname);
1017 $fparts = explode(".",$file);
1018 switch (count($fparts)) {
1019 case 1:
1020 // Has a single node (base file name). Create counter node with value 0
1021 $fparts[1] = '1';
1022 break;
1023 case 2:
1024 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1025 if (is_numeric($fparts[1])) {
1026 $fparts[1] += 1;
1027 } else {
1028 array_push($fparts, $fparts[1]);
1029 $fparts[1] = '1';
1031 break;
1032 default:
1033 // Multiple nodes
1034 $ix_end = count($fparts) - 1;
1035 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1036 // Switch old style to new and check again
1037 $wrk = $fparts[$ix_end - 1];
1038 $fparts[$ix_end - 1] = $fparts[$ix_end];
1039 $fparts[$ix_end] = $wrk;
1040 } else if (is_numeric($fparts[$ix_end - 1])) {
1041 $fparts[$ix_end - 1] += 1;
1042 } else {
1043 array_push($fparts, $fparts[$ix_end]);
1044 $fparts[$ix_end] = '1';
1046 break;
1049 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1051 if (file_exists($fname)) {
1052 return $this->_rename_file($fname, TRUE);
1053 } else {
1054 return($fname);
1058 function &_array_recurse($array,$categories = array()) {
1059 if (!is_array($array)) {
1060 $array = array();
1062 $node = &$this->_last_node;
1063 $current_node = &$node;
1064 $expandedIcon = 'folder-expanded.gif';
1065 foreach($array as $id => $ar) {
1066 $icon = 'folder.gif';
1067 if (is_array($ar) || !empty($id)) {
1068 if ($node == null) {
1069 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1070 $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));
1071 $this->_last_node = &$rnode;
1072 $node = &$rnode;
1073 $current_node = &$rnode;
1075 else {
1076 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1077 $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)));
1078 $current_node = &$this->_last_node;
1081 $this->_array_recurse($ar,$categories);
1083 else {
1084 if ($id === 0 && !empty($ar)) {
1085 $info = $this->tree->get_node_info($id);
1086 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1087 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1089 else {
1090 //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
1091 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1092 if ($id !== 0 && is_object($node)) {
1093 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1094 $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)));
1100 // If there are documents in this document category, then add their
1101 // attributes to the current node.
1102 $icon = "file3.png";
1103 if (is_array($categories[$id])) {
1104 foreach ($categories[$id] as $doc) {
1105 if($this->tree->get_node_name($id) == "CCR"){
1106 $current_node->addItem(new HTML_TreeNode(array(
1107 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1108 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1109 'icon' => $icon,
1110 'expandedIcon' => $expandedIcon,
1111 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1112 )));
1113 }elseif($this->tree->get_node_name($id) == "CCD"){
1114 $current_node->addItem(new HTML_TreeNode(array(
1115 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1116 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1117 'icon' => $icon,
1118 'expandedIcon' => $expandedIcon,
1119 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1120 )));
1121 }else{
1122 $current_node->addItem(new HTML_TreeNode(array(
1123 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1124 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1125 'icon' => $icon,
1126 'expandedIcon' => $expandedIcon
1127 )));
1133 return $node;
1136 //function for logging the errors in writing file to CouchDB/Hard Disk
1137 function document_upload_download_log($patientid,$content){
1138 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1139 $log_file = 'log.txt';
1140 if(!is_dir($log_path))
1141 mkdir($log_path,0777,true);
1142 $LOG = fopen($log_path.$log_file,'a');
1143 fwrite($LOG,$content);
1144 fclose($LOG);
1147 function document_send($email,$body,$attfile,$pname) {
1148 if (empty($email)) {
1149 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1150 return;
1153 $desc = "Please check the attached patient document.\n Content:".attr($body);
1154 $mail = new MyMailer();
1155 $from_name = $GLOBALS["practice_return_email_path"];
1156 $from = $GLOBALS["practice_return_email_path"];
1157 $mail->AddReplyTo($from,$from_name);
1158 $mail->SetFrom($from,$from );
1159 $to = $email ; $to_name =$email;
1160 $mail->AddAddress($to, $to_name);
1161 $subject = "Patient documents";
1162 $mail->Subject = $subject;
1163 $mail->Body = $desc;
1164 $mail->AddAttachment($attfile);
1165 if ($mail->Send()) {
1166 $retstatus = "email_sent";
1167 } else {
1168 $email_status = $mail->ErrorInfo;
1169 //echo "EMAIL ERROR: ".$email_status;
1170 $retstatus = "email_fail";
1174 //place to hold optional code
1175 //$first_node = array_keys($t->tree);
1176 //$first_node = $first_node[0];
1177 //$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')"));
1179 //$this->_last_node = &$node1;
1181 // Function to tag a document to an encounter.
1182 function tag_action_process($patient_id="", $document_id) {
1183 if ($_POST['process'] != "true") {
1184 die("process is '" . text($_POST['process']) . "', expected 'true'");
1185 return;
1188 // Create Encounter and Tag it.
1189 $event_date = date('Y-m-d H:i:s');
1190 $encounter_id = $_POST['encounter_id'];
1191 $encounter_check = $_POST['encounter_check'];
1192 $visit_category_id = $_POST['visit_category_id'];
1194 if (is_numeric($document_id)) {
1195 $messages = '';
1196 $d = new Document( $document_id );
1197 $file_name = $d->get_url_file();
1198 if (!is_numeric($encounter_id)) {
1199 $encounter_id = 0;
1202 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1203 if ($encounter_check) {
1204 $provider_id = $_SESSION['authUserID'] ;
1206 // Get the logged in user's facility
1207 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1208 $username = $facilityRow['username'];
1209 $facility = $facilityRow['facility'];
1210 $facility_id = $facilityRow['facility_id'];
1211 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1212 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1213 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1215 $conn = $GLOBALS['adodb']['db'];
1216 $encounter = $conn->GenID("sequences");
1217 $query = "INSERT INTO form_encounter SET
1218 date = ?,
1219 reason = ?,
1220 facility = ?,
1221 sensitivity = 'normal',
1222 pc_catid = ?,
1223 facility_id = ?,
1224 billing_facility = ?,
1225 provider_id = ?,
1226 pid = ?,
1227 encounter = ?";
1228 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1229 $formID = sqlInsert($query,$bindArray);
1230 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1231 $d->set_encounter_id($encounter);
1232 $this->image_result_indication($d->id, $encounter);
1234 } else {
1235 $d->set_encounter_id($encounter_id);
1236 $this->image_result_indication($d->id, $encounter_id);
1238 $d->set_encounter_check($encounter_check);
1239 $d->persist();
1241 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1244 $this->_state = false;
1245 $this->assign("messages", $messages);
1247 return $this->view_action($patient_id, $document_id);
1250 function image_procedure_action($patient_id="",$document_id){
1252 $img_procedure_id = $_POST['image_procedure_id'];
1253 $proc_code = $_POST['procedure_code'];
1255 if(is_numeric($document_id)){
1257 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1258 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1259 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1260 if($img_report_id == 0){
1261 $report_date = date('Y-m-d H:i:s');
1262 $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));
1265 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1266 if(empty($img_result)){
1267 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));
1270 $this->image_result_indication($document_id, 0,$img_procedure_id);
1272 return $this->view_action($patient_id, $document_id);
1275 function clear_procedure_tag_action($patient_id="",$document_id){
1276 if(is_numeric($document_id)){
1277 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1279 return $this->view_action($patient_id, $document_id);
1282 function get_mapped_procedure($document_id){
1283 $map = array();
1284 if(is_numeric($document_id)){
1285 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1286 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1287 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1288 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1289 where pres.document_id = ?",array($document_id));
1291 return $map;
1294 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0){
1295 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1296 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1298 if($encounter != 0) {
1299 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1301 else if($image_procedure_id != 0){
1302 $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));
1304 else{
1305 $ep = array('assigned_to' => $_SESSION['authUser']);
1308 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1309 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1310 setGpRelation(1, $doc_id, 6, $noteid);
1313 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1314 * Also usable for documents that may of been moved to different patients.
1316 * @param string $url - Current url string from database.
1317 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1318 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1320 * @return string
1322 function _check_relocation($url, $new_pid = null, $new_name = null) {
1323 //strip url of protocol handler
1324 $url = preg_replace("|^(.*)://|","",$url);
1325 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1326 while (current($fsnodes) != "documents") {
1327 array_shift($fsnodes);
1329 if ($new_pid) {
1330 $fsnodes[1] = $new_pid;
1332 if ($new_name) {
1333 $fsnodes[count($fsnodes)-1] = $new_name;
1335 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1336 // Make sure the url is available after corrections
1337 if ($new_pid || $new_name) {
1338 $url = $this->_rename_file($url);
1340 //Add full path and remaining nodes
1341 return $url;