groups fix in the add appt screen
[openemr.git] / controllers / C_Document.class.php
blob8a3ff808c55dffcdb88b7d169e695aa3acbc7021
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;
117 foreach($_FILES['file']['name'] as $key => $value){
118 $fname = $value;
119 $err = "";
120 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
121 $fname = $value;
122 if (empty($fname)) {
123 $fname = htmlentities("<empty>");
125 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
126 if ($_FILES['file']['size'][$key] == 0) {
127 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
129 }elseif($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])){
130 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
131 }else{
132 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
133 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
134 fclose($tmpfile);
135 if ($doDecryption) {
136 $filetext = $this->decrypt($filetext, $passphrase);
138 if ( $_POST['destination'] != '' ) {
139 $fname = $_POST['destination'];
141 $d = new Document();
142 $rc = $d->createDocument($patient_id, $category_id, $fname,
143 $_FILES['file']['type'][$key], $filetext,
144 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
145 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
146 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
147 if ($rc) {
148 $error .= $rc . "\n";
150 else {
151 $this->assign("upload_success", "true");
153 $sentUploadStatus[] = $d;
154 $this->assign("file", $sentUploadStatus);
157 // Option to run a custom plugin for each file upload.
158 // This was initially created to delete the original source file in a custom setting.
159 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
160 if (file_exists($upload_plugin)) {
161 include_once($upload_plugin);
163 $upload_plugin_pp = 'documentUploadPostProcess';
164 if (function_exists($upload_plugin_pp)) {
165 $tmp = call_user_func($upload_plugin_pp, $value, $d);
166 if ($tmp) {
167 $error = $tmp;
170 // Following is just an example of code in such a plugin file.
171 /*****************************************************
172 function documentUploadPostProcess($filename, &$d) {
173 $userid = $_SESSION['authUserID'];
174 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
175 $owner = strtolower($row['username']);
176 $dn = '1_' . ucfirst($owner);
177 $filepath = "/shared_network_directory/$dn/$filename";
178 if (@unlink($filepath)) return '';
179 return "Failed to delete '$filepath'.";
181 *****************************************************/
186 $this->assign("error", nl2br($error));
187 //$this->_state = false;
188 $_POST['process'] = "";
189 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
192 function note_action_process($patient_id) {
193 // this function is a dual function that will set up a note associated with a document or send a document via email.
195 if ($_POST['process'] != "true")
196 return;
198 $n = new Note();
199 $n->set_owner($_SESSION['authUserID']);
200 parent::populate_object($n);
201 if ($_POST['identifier'] == "no"){
202 // associate a note with a document
203 $n->persist();
204 }elseif ($_POST['identifier'] == "yes"){
205 // send the document via email
206 $d = new Document($_POST['foreign_id']);
207 $url = $d->get_url();
208 $storagemethod = $d->get_storagemethod();
209 $couch_docid = $d->get_couch_docid();
210 $couch_revid = $d->get_couch_revid();
211 if($couch_docid && $couch_revid){
212 $couch = new CouchDB();
213 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
214 $resp = $couch->retrieve_doc($data);
215 $content = $resp->data;
216 if($content=='' && $GLOBALS['couchdb_log']==1){
217 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
218 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
219 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
220 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
221 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
222 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
223 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
224 die(xlt("File retrieval from CouchDB failed"));
226 // place it in a temporary file and will remove the file below after emailed
227 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
228 $fh = fopen($temp_couchdb_url,"w");
229 fwrite($fh,base64_decode($content));
230 fclose($fh);
231 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
232 } else {
233 $url = preg_replace("|^(.*)://|","",$url);
234 // Collect filename and path
235 $from_all = explode("/",$url);
236 $from_filename = array_pop($from_all);
237 $from_pathname_array = array();
238 for ($i=0;$i<$d->get_path_depth();$i++) {
239 $from_pathname_array[] = array_pop($from_all);
241 $from_pathname_array = array_reverse($from_pathname_array);
242 $from_pathname = implode("/",$from_pathname_array);
243 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
245 if (!file_exists($temp_url)) {
246 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;
248 $url = $temp_url;
249 $body_notes = attr($_POST['note']);
250 $pdetails = getPatientData($patient_id);
251 $pname = $pdetails['fname']." ".$pdetails['lname'];
252 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
253 if ($couch_docid && $couch_revid) {
254 // remove the temporary couchdb file
255 unlink($temp_couchdb_url);
258 $this->_state = false;
259 $_POST['process'] = "";
260 return $this->view_action($patient_id,$n->get_foreign_id());
263 function default_action() {
264 return $this->list_action();
267 function view_action($patient_id="",$doc_id) {
268 // Added by Rod to support document delete:
269 global $gacl_object, $phpgacl_location;
270 global $ISSUE_TYPES;
272 require_once(dirname(__FILE__) . "/../library/acl.inc");
273 require_once(dirname(__FILE__) . "/../library/lists.inc");
275 $d = new Document($doc_id);
276 $n = new Note();
278 $notes = $n->notes_factory($doc_id);
280 $this->assign("file", $d);
281 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
282 $this->assign("NOTE_ACTION",$this->_link("note"));
283 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
284 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
286 // Added by Rod to support document delete:
287 $delete_string = '';
288 if (acl_check('admin', 'super')) {
289 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
290 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
292 $this->assign("delete_string", $delete_string);
293 $this->assign("REFRESH_ACTION",$this->_link("list"));
295 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
296 "document_id=" . $d->get_id() . "&process=true");
298 // Added by Rod to support document date update:
299 $this->assign("DOCDATE", $d->get_docdate());
300 $this->assign("UPDATE_ACTION",$this->_link("update") .
301 "document_id=" . $d->get_id() . "&process=true");
303 // Added by Rod to support document issue update:
304 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
305 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
306 "pid = ? " . // AND enddate IS NULL " .
307 "ORDER BY type, begdate", array($patient_id) );
308 while ($irow = sqlFetchArray($ires)) {
309 $desc = $irow['type'];
310 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
311 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
312 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
313 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
315 $this->assign("ISSUES_LIST", $issues_options);
317 // For tagging to encounter
318 // Populate the dropdown with patient's encounter list
319 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
320 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
321 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
322 "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));
323 if ( sqlNumRows($result_docs) > 0)
324 while($row_result_docs = sqlFetchArray($result_docs)) {
325 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
326 $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>";
328 $this->assign("ENC_LIST", $encOptions);
330 //Populate the dropdown with category list
331 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
332 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
333 while ($crow = sqlFetchArray($cres)) {
334 $catid = $crow['pc_catid'];
335 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
336 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
338 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
340 $this->assign("notes",$notes);
342 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
343 // Populate the dropdown with image procedure order list
344 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
345 $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));
346 $mapping = $this->get_mapped_procedure($d->get_id());
347 if(sqlNumRows($imgOrders) > 0){
348 while($row = sqlFetchArray($imgOrders)) {
349 $sel_proc = '';
350 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
351 $sel_proc = 'selected';
352 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
356 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
358 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
360 $this->_last_node = null;
362 $menu = new HTML_TreeMenu();
364 //pass an empty array because we don't want the documents for each category showing up in this list box
365 $rnode = $this->_array_recurse($this->tree->tree,array());
366 $menu->addItem($rnode);
367 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
369 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
371 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
372 $this->assign("activity", $activity);
374 return $this->list_action($patient_id);
377 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
379 $td = mcrypt_module_open( $cypher, '', $mode, '');
380 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
381 mcrypt_generic_init( $td, $key, $iv );
382 $crypttext = mcrypt_generic( $td, $plaintext );
383 mcrypt_generic_deinit( $td );
384 return $iv.$crypttext;
387 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
389 $plaintext = '';
390 $td = mcrypt_module_open( $cypher, '', $mode, '' );
391 $ivsize = mcrypt_enc_get_iv_size( $td) ;
392 $iv = substr( $crypttext, 0, $ivsize );
393 $crypttext = substr( $crypttext, $ivsize );
394 if( $iv )
396 mcrypt_generic_init( $td, $key, $iv );
397 $plaintext = mdecrypt_generic( $td, $crypttext );
399 return $plaintext;
403 * Retrieve file from hard disk / CouchDB.
404 * In case that file isn't download this function will return thumbnail image (if exist).
405 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
406 * */
407 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false) {
409 $encrypted = $_POST['encrypted'];
410 $passphrase = $_POST['passphrase'];
411 $doEncryption = false;
412 if ( !$GLOBALS['hide_document_encryption'] &&
413 $encrypted == "true" &&
414 $passphrase ) {
415 $doEncryption = true;
418 //controller function ruins booleans, so need to manually re-convert to booleans
419 if ($as_file == "true") {
420 $as_file=true;
422 else if ($as_file == "false") {
423 $as_file=false;
425 if ($original_file == "true") {
426 $original_file=true;
428 else if ($original_file == "false") {
429 $original_file=false;
431 if ($disable_exit == "true") {
432 $disable_exit=true;
434 else if ($disable_exit == "false") {
435 $disable_exit=false;
437 if ($show_original == "true") {
438 $show_original=true;
440 else if ($show_original == "false") {
441 $show_original=false;
444 $d = new Document($document_id);
445 $url = $d->get_url();
446 $th_url = $d->get_thumb_url();
448 $storagemethod = $d->get_storagemethod();
449 $couch_docid = $d->get_couch_docid();
450 $couch_revid = $d->get_couch_revid();
452 if($couch_docid && $couch_revid && $original_file){
453 $couch = new CouchDB();
454 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
455 $resp = $couch->retrieve_doc($data);
456 //Take thumbnail file when is not null and file is presented online
457 if (!$as_file && !is_null($th_url) && !$show_original) {
458 $content = $resp->th_data;
459 } else {
460 $content = $resp->data;
462 if($content=='' && $GLOBALS['couchdb_log']==1){
463 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
464 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
465 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
466 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
467 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
468 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
469 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
470 die(xl("File retrieval from CouchDB failed"));
472 if($disable_exit == true) {
473 return base64_decode($content);
475 header('Content-Description: File Transfer');
476 header('Content-Transfer-Encoding: binary');
477 header('Expires: 0');
478 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
479 header('Pragma: public');
480 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
481 $fh = fopen($tmpcouchpath,"w");
482 fwrite($fh,base64_decode($content));
483 fclose($fh);
484 $f = fopen($tmpcouchpath,"r");
485 if ( $doEncryption ) {
486 $filetext = fread( $f, filesize($tmpcouchpath) );
487 $ciphertext = $this->encrypt( $filetext, $passphrase );
488 $tmpfilepath = $GLOBALS['temporary_files_dir'];
489 $tmpfilename = "/encrypted_".$d->get_url_file();
490 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
491 fwrite( $tmpfile, $ciphertext );
492 fclose( $tmpfile );
493 header('Content-Disposition: attachment; filename='.$tmpfilename );
494 header("Content-Type: application/octet-stream" );
495 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
496 ob_clean();
497 flush();
498 readfile( $tmpfilepath.$tmpfilename );
499 unlink( $tmpfilepath.$tmpfilename );
500 } else {
501 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
502 header("Content-Type: " . $d->get_mimetype());
503 header("Content-Length: " . filesize($tmpcouchpath));
504 fpassthru($f);
506 fclose($f);
507 if($content!='')
508 unlink($tmpcouchpath);
509 exit;//exits only if file download from CouchDB is successfull.
512 //Take thumbnail file when is not null and file is presented online
513 if(!$as_file && !is_null($th_url) && !$show_original) {
514 $url = $th_url;
517 //strip url of protocol handler
518 $url = preg_replace("|^(.*)://|","",$url);
520 //change full path to current webroot. this is for documents that may have
521 //been moved from a different filesystem and the full path in the database
522 //is not current. this is also for documents that may of been moved to
523 //different patients. Note that the path_depth is used to see how far down
524 //the path to go. For example, originally the path_depth was always 1, which
525 //only allowed things like documents/1/<file>, but now can have more structured
526 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
527 // etc.
528 // NOTE that $from_filename and basename($url) are the same thing
529 $from_all = explode("/",$url);
530 $from_filename = array_pop($from_all);
531 $from_pathname_array = array();
532 for ($i=0;$i<$d->get_path_depth();$i++) {
533 $from_pathname_array[] = array_pop($from_all);
535 $from_pathname_array = array_reverse($from_pathname_array);
536 $from_pathname = implode("/",$from_pathname_array);
537 if($couch_docid && $couch_revid){
538 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
539 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
542 else{
543 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
546 if (file_exists($temp_url)) {
547 $url = $temp_url;
551 if (!file_exists($url)) {
552 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;
555 else {
556 if ($original_file) {
557 //normal case when serving the file referenced in database
558 if($disable_exit == true) {
559 $f = fopen($url,"r");
560 $filetext = fread( $f, filesize($url) );
561 return $filetext;
563 header('Content-Description: File Transfer');
564 header('Content-Transfer-Encoding: binary');
565 header('Expires: 0');
566 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
567 header('Pragma: public');
568 $f = fopen($url,"r");
569 if ( $doEncryption ) {
570 $filetext = fread( $f, filesize($url) );
571 $ciphertext = $this->encrypt( $filetext, $passphrase );
572 $tmpfilepath = $GLOBALS['temporary_files_dir'];
573 $tmpfilename = "/encrypted_".$d->get_url_file();
574 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
575 fwrite( $tmpfile, $ciphertext );
576 fclose( $tmpfile );
577 header('Content-Disposition: attachment; filename='.$tmpfilename );
578 header("Content-Type: application/octet-stream" );
579 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
580 ob_clean();
581 flush();
582 readfile( $tmpfilepath.$tmpfilename );
583 unlink( $tmpfilepath.$tmpfilename );
584 } else {
585 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
586 header("Content-Type: " . $d->get_mimetype());
587 header("Content-Length: " . filesize($url));
588 fpassthru($f);
590 exit;
592 else {
593 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
594 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
595 if($couch_docid && $couch_revid){
596 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
598 else{
599 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
601 if($disable_exit == true) {
602 return ;
604 header("Pragma: public");
605 header("Expires: 0");
606 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
607 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
608 header("Content-Type: image/jpeg");
609 header("Content-Length: " . filesize($url));
610 $f = fopen($url,"r");
611 fpassthru($f);
612 if($couch_docid && $couch_revid){
613 fclose($f);
614 unlink($url);
615 $url=str_replace("_converted.jpg",'.pdf',$url);
616 unlink($url);
618 exit;
623 function queue_action($patient_id="") {
624 $messages = $this->_tpl_vars['messages'];
625 $queue_files = array();
627 //see if the repository exists and it is a directory else error
628 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
629 $dir = opendir($this->_config['repository']);
630 //read each entry in the directory
631 while (($file = readdir($dir)) !== false) {
632 //concat the filename and path
633 $file = $this->_config['repository'] .$file;
634 $file_info = array();
635 //if the filename is a file get its info and put into a tmp array
636 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
637 $file_info['filename'] = basename_international($file);
638 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
639 $d = $this->Document->document_factory_url("file://" . $file);
640 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
641 $file_info['patient_id'] = $patient_match[1];
642 $file_info['document_id'] = $d->get_id();
643 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
645 //merge the tmp array into the larger array
646 $queue_files[] = $file_info;
649 closedir($dir);
651 else {
652 $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";
656 $this->assign("queue_files",$queue_files);
657 $this->_last_node = null;
659 $menu = new HTML_TreeMenu();
661 //pass an empty array because we don't want the documents for each category showing up in this list box
662 $rnode = $this->_array_recurse($this->tree->tree,array());
663 $menu->addItem($rnode);
664 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
666 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
668 $this->assign("messages",nl2br($messages));
669 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
672 function queue_action_process() {
673 if ($_POST['process'] != "true")
674 return;
676 $messages = $this->_tpl_vars['messages'];
678 //build a category tree so we can have a list of category ids that are valid
679 $ct = new CategoryTree(1);
680 $categories = $ct->_id_name;
682 //see if there were and posted files and assign them
683 $files = null;
684 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
686 //loop through posted files
687 foreach($files as $doc_id=> $file) {
688 //only operate on files checked as active
689 if (!$file['active']) continue;
691 //run basic validation checks
692 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
693 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
694 continue;
697 //validate that the pod exists
698 $d = new Document($doc_id);
699 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
700 $result = $d->_db->Execute($sql);
702 if (!$result || $result->EOF) {
703 //patient id does not exist
704 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
705 continue;
708 //validate that the category id exists
709 if (!isset($categories[$file['category_id']])) {
710 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
711 continue;
714 //now do the work of moving the file
715 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
717 //see if the patient dir exists in the repository and create if not
718 if (!file_exists($new_path)) {
719 if (!mkdir($new_path,0700)) {
720 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
721 continue;
725 //fname is the name of the file after it is moved
726 $fname = $file['name'];
728 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
729 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
730 if ($patient_match[1] == $file['patient_id']) {
731 $fname = preg_replace("/^([0-9]+)_/","",$fname);
734 //filenames should not have funny chars
735 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
737 //see if there is an existing file with the same name and rename as necessary
738 if (file_exists($new_path.$file['name'])) {
739 $messages .= "File with same name already exists at location: " . $new_path . "\n";
740 $fname = basename_international($this->_rename_file($new_path.$file['name']));
741 $messages .= "Current file name was changed to " . $fname ."\n";
744 //now move the file
745 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
746 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
747 $d->url = "file://" .$new_path.$fname;
748 $d->set_foreign_id($file['patient_id']);
749 $d->set_mimetype($mimetype);
750 $d->persist();
751 $d->populate();
753 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
754 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
755 $d->_db->Execute($sql);
758 else {
759 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
762 $this->assign("messages",$messages);
763 $_POST['process'] = "";
766 function move_action_process($patient_id="",$document_id) {
767 if ($_POST['process'] != "true")
768 return;
770 $new_category_id = $_POST['new_category_id'];
771 $new_patient_id = $_POST['new_patient_id'];
773 //move to new category
774 if (is_numeric($new_category_id) && is_numeric($document_id)) {
775 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
776 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
777 //echo $sql;
778 $this->tree->_db->Execute($sql);
781 //move to new patient
782 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
783 $d = new Document($document_id);
784 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
785 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
786 $result = $d->_db->Execute($sql);
788 if (!$result || $result->EOF) {
789 //patient id does not exist
790 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
792 else {
793 $couchsavefailed = !$d->change_patient($new_patient_id);
795 $this->_state = false;
796 if(!$couchsavefailed){
798 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
800 else{
802 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
804 $this->assign("messages",$messages);
805 return $this->list_action($patient_id);
808 //in this case return the document to the queue instead of moving it
809 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
810 $d = new Document($document_id);
811 $new_path = $this->_config['repository'];
812 $fname = $d->get_url_file();
814 //see if there is an existing file with the same name and rename as necessary
815 if (file_exists($new_path.$d->get_url_file())) {
816 $messages .= "File with same name already exists in the queue.\n";
817 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
818 $messages .= "Current file name was changed to " . $fname ."\n";
821 //now move the file
822 if (rename($d->get_url_filepath(),$new_path.$fname)) {
823 $d->url = "file://" .$new_path.$fname;
824 $d->set_foreign_id("");
825 $d->persist();
826 $d->persist();
827 $d->populate();
829 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
830 $d->_db->Execute($sql);
831 $messages .= "Document returned to queue successfully.\n";
834 else {
835 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
838 $this->_state = false;
839 $this->assign("messages",$messages);
840 return $this->list_action($patient_id);
843 $this->_state = false;
844 $this->assign("messages",$messages);
845 return $this->view_action($patient_id,$document_id);
848 function validate_action_process($patient_id="", $document_id) {
850 $d = new Document($document_id);
851 if($d->couch_docid && $d->couch_revid){
852 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
853 $url = $file_path.$d->get_url();
854 $couch = new CouchDB();
855 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
856 $resp = $couch->retrieve_doc($data);
857 $content = $resp->data;
858 //--------Temporarily writing the file for calculating the hash--------//
859 //-----------Will be removed after calculating the hash value----------//
860 $temp_file = fopen($url,"w");
861 fwrite($temp_file,base64_decode($content));
862 fclose($temp_file);
864 else{
865 $url = $d->get_url();
867 //strip url of protocol handler
868 $url = preg_replace("|^(.*)://|","",$url);
870 //change full path to current webroot. this is for documents that may have
871 //been moved from a different filesystem and the full path in the database
872 //is not current. this is also for documents that may of been moved to
873 //different patients. Note that the path_depth is used to see how far down
874 //the path to go. For example, originally the path_depth was always 1, which
875 //only allowed things like documents/1/<file>, but now can have more structured
876 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
877 // etc.
878 // NOTE that $from_filename and basename($url) are the same thing
879 $from_all = explode("/",$url);
880 $from_filename = array_pop($from_all);
881 $from_pathname_array = array();
882 for ($i=0;$i<$d->get_path_depth();$i++) {
883 $from_pathname_array[] = array_pop($from_all);
885 $from_pathname_array = array_reverse($from_pathname_array);
886 $from_pathname = implode("/",$from_pathname_array);
887 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
888 if (file_exists($temp_url)) {
889 $url = $temp_url;
892 if ($_POST['process'] != "true") {
893 die("process is '" . $_POST['process'] . "', expected 'true'");
894 return;
897 $d = new Document( $document_id );
898 $current_hash = sha1_file( $url );
899 $messages = xl('Current Hash').": ".$current_hash."<br>";
900 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
901 if ( $d->get_hash() == '' ) {
902 $d->hash = $current_hash;
903 $d->persist();
904 $d->populate();
905 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
906 } else if ( $current_hash != $d->get_hash() ) {
907 $messages .= xl('Hash does not match. Data integrity has been compromised.');
908 } else {
909 $messages .= xl('Document passed integrity check.');
911 $this->_state = false;
912 $this->assign("messages", $messages);
913 if($d->couch_docid && $d->couch_revid){
914 //Removing the temporary file which is used to create the hash
915 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
917 return $this->view_action($patient_id, $document_id);
920 // Added by Rod for metadata update.
922 function update_action_process($patient_id="", $document_id) {
924 if ($_POST['process'] != "true") {
925 die("process is '" . $_POST['process'] . "', expected 'true'");
926 return;
929 $docdate = $_POST['docdate'];
930 $docname = $_POST['docname'];
931 $issue_id = $_POST['issue_id'];
933 if (is_numeric($document_id)) {
934 $messages = '';
935 $d = new Document( $document_id );
936 $file_name = $d->get_url_file();
937 if ( $docname != '' &&
938 $docname != $file_name ) {
939 // Ready to rename - check for relocation
940 $old_url = $this->_check_relocation($d->get_url());
941 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
942 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
943 if ( rename( $old_url, $new_url ) ) {
944 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
945 if ( file_exists( $old_url ) ) {
946 unlink( $old_url );
948 $d->url = $new_url;
949 $d->persist();
950 $d->populate();
951 $messages .= xl('Document successfully renamed.')."<br>";
952 } else {
953 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
957 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
958 $docdate = "'$docdate'";
959 } else {
960 $docdate = "NULL";
962 if (!is_numeric($issue_id)) {
963 $issue_id = 0;
965 $couch_docid = $d->get_couch_docid();
966 $couch_revid = $d->get_couch_revid();
967 if($couch_docid && $couch_revid ){
968 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
969 "list_id = '$issue_id' " .
970 "WHERE id = '$document_id'";
971 $this->tree->_db->Execute($sql);
974 else{
975 $sql = "UPDATE documents SET docdate = $docdate, " .
976 "list_id = '$issue_id' " .
977 "WHERE id = '$document_id'";
978 $this->tree->_db->Execute($sql);
980 $messages .= xl('Document date and issue updated successfully') . "<br>";
983 $this->_state = false;
984 $this->assign("messages", $messages);
985 return $this->view_action($patient_id, $document_id);
988 function list_action($patient_id = "") {
989 $this->_last_node = null;
990 $categories_list = $this->tree->_get_categories_array($patient_id);
991 //print_r($categories_list);
993 $menu = new HTML_TreeMenu();
994 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
995 $menu->addItem($rnode);
996 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
997 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
999 $this->assign("tree_html",$treeMenu->toHTML());
1001 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1004 /* This is a recursive function to rename a file to something that doesn't already exist.
1005 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1006 * at end) to ensure documents opened correctly by external browser viewers. If the
1007 * counter is at the end of the file, then will use it (to continue to work with older
1008 * files), however all new counters will be placed within filenames.
1010 * Modified to only deal with base file name when renaming, to avoid issues with directory
1011 * names with dots.
1013 function _rename_file($fname, $self=FALSE) {
1014 // Allow same routine for new file name check
1015 if (!file_exists($fname)) return($fname);
1017 $path = dirname($fname);
1018 $file = basename_international($fname);
1020 $fparts = explode(".",$file);
1021 switch (count($fparts)) {
1022 case 1:
1023 // Has a single node (base file name). Create counter node with value 0
1024 $fparts[1] = '1';
1025 break;
1026 case 2:
1027 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1028 if (is_numeric($fparts[1])) {
1029 $fparts[1] += 1;
1030 } else {
1031 array_push($fparts, $fparts[1]);
1032 $fparts[1] = '1';
1034 break;
1035 default:
1036 // Multiple nodes
1037 $ix_end = count($fparts) - 1;
1038 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1039 // Switch old style to new and check again
1040 $wrk = $fparts[$ix_end - 1];
1041 $fparts[$ix_end - 1] = $fparts[$ix_end];
1042 $fparts[$ix_end] = $wrk;
1043 } else if (is_numeric($fparts[$ix_end - 1])) {
1044 $fparts[$ix_end - 1] += 1;
1045 } else {
1046 array_push($fparts, $fparts[$ix_end]);
1047 $fparts[$ix_end] = '1';
1049 break;
1052 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1054 if (file_exists($fname)) {
1055 return $this->_rename_file($fname, TRUE);
1056 } else {
1057 return($fname);
1061 function &_array_recurse($array,$categories = array()) {
1062 if (!is_array($array)) {
1063 $array = array();
1065 $node = &$this->_last_node;
1066 $current_node = &$node;
1067 $expandedIcon = 'folder-expanded.gif';
1068 foreach($array as $id => $ar) {
1069 $icon = 'folder.gif';
1070 if (is_array($ar) || !empty($id)) {
1071 if ($node == null) {
1072 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1073 $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));
1074 $this->_last_node = &$rnode;
1075 $node = &$rnode;
1076 $current_node = &$rnode;
1078 else {
1079 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1080 $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)));
1081 $current_node = &$this->_last_node;
1084 $this->_array_recurse($ar,$categories);
1086 else {
1087 if ($id === 0 && !empty($ar)) {
1088 $info = $this->tree->get_node_info($id);
1089 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1090 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1092 else {
1093 //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
1094 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1095 if ($id !== 0 && is_object($node)) {
1096 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1097 $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)));
1103 // If there are documents in this document category, then add their
1104 // attributes to the current node.
1105 $icon = "file3.png";
1106 if (is_array($categories[$id])) {
1107 foreach ($categories[$id] as $doc) {
1108 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1109 // If user has no access then there will be no link.
1110 if (!acl_check_aco_spec($doc['aco_spec'])) $link = '';
1111 if($this->tree->get_node_name($id) == "CCR"){
1112 $current_node->addItem(new HTML_TreeNode(array(
1113 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1114 'link' => $link,
1115 'icon' => $icon,
1116 'expandedIcon' => $expandedIcon,
1117 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1118 )));
1119 }elseif($this->tree->get_node_name($id) == "CCD"){
1120 $current_node->addItem(new HTML_TreeNode(array(
1121 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1122 'link' => $link,
1123 'icon' => $icon,
1124 'expandedIcon' => $expandedIcon,
1125 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1126 )));
1127 }else{
1128 $current_node->addItem(new HTML_TreeNode(array(
1129 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1130 'link' => $link,
1131 'icon' => $icon,
1132 'expandedIcon' => $expandedIcon
1133 )));
1139 return $node;
1142 //function for logging the errors in writing file to CouchDB/Hard Disk
1143 function document_upload_download_log($patientid,$content){
1144 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1145 $log_file = 'log.txt';
1146 if(!is_dir($log_path))
1147 mkdir($log_path,0777,true);
1148 $LOG = fopen($log_path.$log_file,'a');
1149 fwrite($LOG,$content);
1150 fclose($LOG);
1153 function document_send($email,$body,$attfile,$pname) {
1154 if (empty($email)) {
1155 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1156 return;
1159 $desc = "Please check the attached patient document.\n Content:".attr($body);
1160 $mail = new MyMailer();
1161 $from_name = $GLOBALS["practice_return_email_path"];
1162 $from = $GLOBALS["practice_return_email_path"];
1163 $mail->AddReplyTo($from,$from_name);
1164 $mail->SetFrom($from,$from );
1165 $to = $email ; $to_name =$email;
1166 $mail->AddAddress($to, $to_name);
1167 $subject = "Patient documents";
1168 $mail->Subject = $subject;
1169 $mail->Body = $desc;
1170 $mail->AddAttachment($attfile);
1171 if ($mail->Send()) {
1172 $retstatus = "email_sent";
1173 } else {
1174 $email_status = $mail->ErrorInfo;
1175 //echo "EMAIL ERROR: ".$email_status;
1176 $retstatus = "email_fail";
1180 //place to hold optional code
1181 //$first_node = array_keys($t->tree);
1182 //$first_node = $first_node[0];
1183 //$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')"));
1185 //$this->_last_node = &$node1;
1187 // Function to tag a document to an encounter.
1188 function tag_action_process($patient_id="", $document_id) {
1189 if ($_POST['process'] != "true") {
1190 die("process is '" . text($_POST['process']) . "', expected 'true'");
1191 return;
1194 // Create Encounter and Tag it.
1195 $event_date = date('Y-m-d H:i:s');
1196 $encounter_id = $_POST['encounter_id'];
1197 $encounter_check = $_POST['encounter_check'];
1198 $visit_category_id = $_POST['visit_category_id'];
1200 if (is_numeric($document_id)) {
1201 $messages = '';
1202 $d = new Document( $document_id );
1203 $file_name = $d->get_url_file();
1204 if (!is_numeric($encounter_id)) {
1205 $encounter_id = 0;
1208 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1209 if ($encounter_check) {
1210 $provider_id = $_SESSION['authUserID'] ;
1212 // Get the logged in user's facility
1213 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1214 $username = $facilityRow['username'];
1215 $facility = $facilityRow['facility'];
1216 $facility_id = $facilityRow['facility_id'];
1217 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1218 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1219 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1221 $conn = $GLOBALS['adodb']['db'];
1222 $encounter = $conn->GenID("sequences");
1223 $query = "INSERT INTO form_encounter SET
1224 date = ?,
1225 reason = ?,
1226 facility = ?,
1227 sensitivity = 'normal',
1228 pc_catid = ?,
1229 facility_id = ?,
1230 billing_facility = ?,
1231 provider_id = ?,
1232 pid = ?,
1233 encounter = ?";
1234 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1235 $formID = sqlInsert($query,$bindArray);
1236 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1237 $d->set_encounter_id($encounter);
1238 $this->image_result_indication($d->id, $encounter);
1240 } else {
1241 $d->set_encounter_id($encounter_id);
1242 $this->image_result_indication($d->id, $encounter_id);
1244 $d->set_encounter_check($encounter_check);
1245 $d->persist();
1247 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1250 $this->_state = false;
1251 $this->assign("messages", $messages);
1253 return $this->view_action($patient_id, $document_id);
1256 function image_procedure_action($patient_id="",$document_id){
1258 $img_procedure_id = $_POST['image_procedure_id'];
1259 $proc_code = $_POST['procedure_code'];
1261 if(is_numeric($document_id)){
1263 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1264 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1265 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1266 if($img_report_id == 0){
1267 $report_date = date('Y-m-d H:i:s');
1268 $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));
1271 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1272 if(empty($img_result)){
1273 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));
1276 $this->image_result_indication($document_id, 0,$img_procedure_id);
1278 return $this->view_action($patient_id, $document_id);
1281 function clear_procedure_tag_action($patient_id="",$document_id){
1282 if(is_numeric($document_id)){
1283 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1285 return $this->view_action($patient_id, $document_id);
1288 function get_mapped_procedure($document_id){
1289 $map = array();
1290 if(is_numeric($document_id)){
1291 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1292 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1293 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1294 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1295 where pres.document_id = ?",array($document_id));
1297 return $map;
1300 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0){
1301 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1302 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1304 if($encounter != 0) {
1305 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1307 else if($image_procedure_id != 0){
1308 $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));
1310 else{
1311 $ep = array('assigned_to' => $_SESSION['authUser']);
1314 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1315 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1316 setGpRelation(1, $doc_id, 6, $noteid);
1319 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1320 * Also usable for documents that may of been moved to different patients.
1322 * @param string $url - Current url string from database.
1323 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1324 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1326 * @return string
1328 function _check_relocation($url, $new_pid = null, $new_name = null) {
1329 //strip url of protocol handler
1330 $url = preg_replace("|^(.*)://|","",$url);
1331 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1332 while (current($fsnodes) != "documents") {
1333 array_shift($fsnodes);
1335 if ($new_pid) {
1336 $fsnodes[1] = $new_pid;
1338 if ($new_name) {
1339 $fsnodes[count($fsnodes)-1] = $new_name;
1341 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1342 // Make sure the url is available after corrections
1343 if ($new_pid || $new_name) {
1344 $url = $this->_rename_file($url);
1346 //Add full path and remaining nodes
1347 return $url;