Fixed bug: https://sourceforge.net/p/openemr/bugs/416/
[openemr.git] / controllers / C_Document.class.php
blobb6c40847acecedc2728cc0ec636f0194f96b8751
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/classes/Controller.class.php");
8 require_once(dirname(__FILE__) . "/../library/classes/Document.class.php");
9 require_once(dirname(__FILE__) . "/../library/classes/CategoryTree.class.php");
10 require_once(dirname(__FILE__) . "/../library/classes/TreeMenu.php");
11 require_once(dirname(__FILE__) . "/../library/classes/Note.class.php");
12 require_once(dirname(__FILE__) . "/../library/classes/CouchDB.class.php");
13 require_once(dirname(__FILE__) . "/../library/forms.inc");
14 require_once(dirname(__FILE__) . "/../library/formatting.inc.php");
15 require_once(dirname(__FILE__) . "/../library/classes/postmaster.php" );
17 class C_Document extends Controller {
19 var $template_mod;
20 var $documents;
21 var $document_categories;
22 var $tree;
23 var $_config;
24 var $manual_set_owner=false; // allows manual setting of a document owner/service
26 function __construct($template_mod = "general") {
27 parent::__construct();
28 $this->documents = array();
29 $this->template_mod = $template_mod;
30 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
31 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
33 //get global config options for this namespace
34 $this->_config = $GLOBALS['oer_config']['documents'];
36 $this->_args = array("patient_id" => $_GET['patient_id']);
38 $this->assign("STYLE", $GLOBALS['style']);
39 $t = new CategoryTree(1);
40 //print_r($t->tree);
41 $this->tree = $t;
42 $this->Document = new Document();
45 function upload_action($patient_id,$category_id) {
46 $category_name = $this->tree->get_node_name($category_id);
47 $this->assign("category_id", $category_id);
48 $this->assign("category_name", $category_name);
49 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
50 $this->assign("patient_id", $patient_id);
52 // Added by Rod to support document template download from general_upload.html.
53 // Cloned from similar stuff in manage_document_templates.php.
54 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
55 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
56 $dh = opendir($templatedir);
57 if ($dh) {
58 $templateslist = array();
59 while (false !== ($sfname = readdir($dh))) {
60 if (substr($sfname, 0, 1) == '.') continue;
61 $templateslist[$sfname] = $sfname;
63 closedir($dh);
64 ksort($templateslist);
65 foreach ($templateslist as $sfname) {
66 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
67 "'>" . htmlspecialchars($sfname) . "</option>";
70 $this->assign("TEMPLATES_LIST", $templates_options);
72 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
73 $this->assign("activity", $activity);
74 return $this->list_action($patient_id);
77 //Upload multiple files on single click
78 function upload_action_process() {
80 // Collect a manually set owner if this has been set
81 // Used when want to manually assign the owning user/service such as the Direct mechanism
82 $non_HTTP_owner=false;
83 if ($this->manual_set_owner) {
84 $non_HTTP_owner=$this->manual_set_owner;
87 $couchDB = false;
88 $harddisk = false;
89 if($GLOBALS['document_storage_method']==0){
90 $harddisk = true;
92 if($GLOBALS['document_storage_method']==1){
93 $couchDB = true;
96 if ($_POST['process'] != "true")
97 return;
99 $doDecryption = false;
100 $encrypted = $_POST['encrypted'];
101 $passphrase = $_POST['passphrase'];
102 if ( !$GLOBALS['hide_document_encryption'] &&
103 $encrypted && $passphrase ) {
104 $doDecryption = true;
107 if (is_numeric($_POST['category_id'])) {
108 $category_id = $_POST['category_id'];
111 $patient_id = 0;
112 if (isset($_GET['patient_id']) && !$couchDB) {
113 $patient_id = $_GET['patient_id'];
115 else if (is_numeric($_POST['patient_id'])) {
116 $patient_id = $_POST['patient_id'];
119 $sentUploadStatus = array();
120 if( count($_FILES['file']['name']) > 0){
121 $upl_inc = 0;
122 foreach($_FILES['file']['name'] as $key => $value){
123 $fname = $value;
124 $err = "";
125 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
126 $fname = $value;
127 if (empty($fname)) {
128 $fname = htmlentities("<empty>");
130 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
131 if ($_FILES['file']['size'][$key] == 0) {
132 $error .= "The system does not permit uploading files of with size 0.\n";
134 }else{
135 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
136 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
137 fclose($tmpfile);
138 if ($doDecryption) {
139 $filetext = $this->decrypt($filetext, $passphrase);
141 if ( $_POST['destination'] != '' ) {
142 $fname = $_POST['destination'];
144 $d = new Document();
145 $rc = $d->createDocument($patient_id, $category_id, $fname,
146 $_FILES['file']['type'][$key], $filetext,
147 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
148 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
149 $non_HTTP_owner);
150 if ($rc) {
151 $error .= $rc . "\n";
153 else {
154 $this->assign("upload_success", "true");
156 $sentUploadStatus[] = $d;
157 $this->assign("file", $sentUploadStatus);
160 // Option to run a custom plugin for each file upload.
161 // This was initially created to delete the original source file in a custom setting.
162 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
163 if (file_exists($upload_plugin)) {
164 include_once($upload_plugin);
166 $upload_plugin_pp = 'documentUploadPostProcess';
167 if (function_exists($upload_plugin_pp)) {
168 $tmp = call_user_func($upload_plugin_pp, $value, $d);
169 if ($tmp) {
170 $error = $tmp;
173 // Following is just an example of code in such a plugin file.
174 /*****************************************************
175 function documentUploadPostProcess($filename, &$d) {
176 $userid = $_SESSION['authUserID'];
177 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
178 $owner = strtolower($row['username']);
179 $dn = '1_' . ucfirst($owner);
180 $filepath = "/shared_network_directory/$dn/$filename";
181 if (@unlink($filepath)) return '';
182 return "Failed to delete '$filepath'.";
184 *****************************************************/
189 $this->assign("error", nl2br($error));
190 //$this->_state = false;
191 $_POST['process'] = "";
192 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
195 function note_action_process($patient_id) {
196 // this function is a dual function that will set up a note associated with a document or send a document via email.
198 if ($_POST['process'] != "true")
199 return;
201 $n = new Note();
202 $n->set_owner($_SESSION['authUserID']);
203 parent::populate_object($n);
204 if ($_POST['identifier'] == "no"){
205 // associate a note with a document
206 $n->persist();
207 }elseif ($_POST['identifier'] == "yes"){
208 // send the document via email
209 $d = new Document($_POST['foreign_id']);
210 $url = $d->get_url();
211 $storagemethod = $d->get_storagemethod();
212 $couch_docid = $d->get_couch_docid();
213 $couch_revid = $d->get_couch_revid();
214 if($couch_docid && $couch_revid){
215 $couch = new CouchDB();
216 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
217 $resp = $couch->retrieve_doc($data);
218 $content = $resp->data;
219 if($content=='' && $GLOBALS['couchdb_log']==1){
220 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
221 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
222 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
223 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
224 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
225 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
226 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
227 die(xlt("File retrieval from CouchDB failed"));
229 // place it in a temporary file and will remove the file below after emailed
230 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
231 $fh = fopen($temp_couchdb_url,"w");
232 fwrite($fh,base64_decode($content));
233 fclose($fh);
234 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
235 } else {
236 $url = preg_replace("|^(.*)://|","",$url);
237 // Collect filename and path
238 $from_all = explode("/",$url);
239 $from_filename = array_pop($from_all);
240 $from_pathname_array = array();
241 for ($i=0;$i<$d->get_path_depth();$i++) {
242 $from_pathname_array[] = array_pop($from_all);
244 $from_pathname_array = array_reverse($from_pathname_array);
245 $from_pathname = implode("/",$from_pathname_array);
246 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
248 if (!file_exists($temp_url)) {
249 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;
251 $url = $temp_url;
252 $body_notes = attr($_POST['note']);
253 $pdetails = getPatientData($patient_id);
254 $pname = $pdetails['fname']." ".$pdetails['lname'];
255 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
256 if ($couch_docid && $couch_revid) {
257 // remove the temporary couchdb file
258 unlink($temp_couchdb_url);
261 $this->_state = false;
262 $_POST['process'] = "";
263 return $this->view_action($patient_id,$n->get_foreign_id());
266 function default_action() {
267 return $this->list_action();
270 function view_action($patient_id="",$doc_id) {
271 // Added by Rod to support document delete:
272 global $gacl_object, $phpgacl_location;
273 global $ISSUE_TYPES;
275 require_once(dirname(__FILE__) . "/../library/acl.inc");
276 require_once(dirname(__FILE__) . "/../library/lists.inc");
278 $d = new Document($doc_id);
279 $n = new Note();
281 $notes = $n->notes_factory($doc_id);
283 $this->assign("file", $d);
284 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
285 $this->assign("NOTE_ACTION",$this->_link("note"));
286 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
287 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
289 // Added by Rod to support document delete:
290 $delete_string = '';
291 if (acl_check('admin', 'super')) {
292 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
293 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
295 $this->assign("delete_string", $delete_string);
296 $this->assign("REFRESH_ACTION",$this->_link("list"));
298 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
299 "document_id=" . $d->get_id() . "&process=true");
301 // Added by Rod to support document date update:
302 $this->assign("DOCDATE", $d->get_docdate());
303 $this->assign("UPDATE_ACTION",$this->_link("update") .
304 "document_id=" . $d->get_id() . "&process=true");
306 // Added by Rod to support document issue update:
307 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
308 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
309 "pid = ? " . // AND enddate IS NULL " .
310 "ORDER BY type, begdate", array($patient_id) );
311 while ($irow = sqlFetchArray($ires)) {
312 $desc = $irow['type'];
313 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
314 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
315 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
316 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
318 $this->assign("ISSUES_LIST", $issues_options);
320 // For tagging to encounter
321 // Populate the dropdown with patient's encounter list
322 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
323 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
324 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
325 "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));
326 if ( sqlNumRows($result_docs) > 0)
327 while($row_result_docs = sqlFetchArray($result_docs)) {
328 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
329 $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>";
331 $this->assign("ENC_LIST", $encOptions);
333 //Populate the dropdown with category list
334 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
335 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
336 while ($crow = sqlFetchArray($cres)) {
337 $catid = $crow['pc_catid'];
338 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
339 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
341 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
343 $this->assign("notes",$notes);
345 $this->_last_node = null;
347 $menu = new HTML_TreeMenu();
349 //pass an empty array because we don't want the documents for each category showing up in this list box
350 $rnode = $this->_array_recurse($this->tree->tree,array());
351 $menu->addItem($rnode);
352 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
354 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
356 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
357 $this->assign("activity", $activity);
359 return $this->list_action($patient_id);
362 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
364 $td = mcrypt_module_open( $cypher, '', $mode, '');
365 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
366 mcrypt_generic_init( $td, $key, $iv );
367 $crypttext = mcrypt_generic( $td, $plaintext );
368 mcrypt_generic_deinit( $td );
369 return $iv.$crypttext;
372 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
374 $plaintext = '';
375 $td = mcrypt_module_open( $cypher, '', $mode, '' );
376 $ivsize = mcrypt_enc_get_iv_size( $td) ;
377 $iv = substr( $crypttext, 0, $ivsize );
378 $crypttext = substr( $crypttext, $ivsize );
379 if( $iv )
381 mcrypt_generic_init( $td, $key, $iv );
382 $plaintext = mdecrypt_generic( $td, $crypttext );
384 return $plaintext;
388 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false) {
390 $encrypted = $_POST['encrypted'];
391 $passphrase = $_POST['passphrase'];
392 $doEncryption = false;
393 if ( !$GLOBALS['hide_document_encryption'] &&
394 $encrypted == "true" &&
395 $passphrase ) {
396 $doEncryption = true;
399 //controller function ruins booleans, so need to manually re-convert to booleans
400 if ($as_file == "true") {
401 $as_file=true;
403 else if ($as_file == "false") {
404 $as_file=false;
406 if ($original_file == "true") {
407 $original_file=true;
409 else if ($original_file == "false") {
410 $original_file=false;
412 if ($disable_exit == "true") {
413 $disable_exit=true;
415 else if ($disable_exit == "false") {
416 $disable_exit=false;
419 $d = new Document($document_id);
420 $url = $d->get_url();
421 $storagemethod = $d->get_storagemethod();
422 $couch_docid = $d->get_couch_docid();
423 $couch_revid = $d->get_couch_revid();
425 if($couch_docid && $couch_revid && $original_file){
426 $couch = new CouchDB();
427 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
428 $resp = $couch->retrieve_doc($data);
429 $content = $resp->data;
430 if($content=='' && $GLOBALS['couchdb_log']==1){
431 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
432 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
433 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
434 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
435 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
436 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
437 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
438 die(xl("File retrieval from CouchDB failed"));
440 if($disable_exit == true) {
441 return base64_decode($content);
443 header('Content-Description: File Transfer');
444 header('Content-Transfer-Encoding: binary');
445 header('Expires: 0');
446 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
447 header('Pragma: public');
448 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
449 $fh = fopen($tmpcouchpath,"w");
450 fwrite($fh,base64_decode($content));
451 fclose($fh);
452 $f = fopen($tmpcouchpath,"r");
453 if ( $doEncryption ) {
454 $filetext = fread( $f, filesize($tmpcouchpath) );
455 $ciphertext = $this->encrypt( $filetext, $passphrase );
456 $tmpfilepath = $GLOBALS['temporary_files_dir'];
457 $tmpfilename = "/encrypted_".$d->get_url_file();
458 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
459 fwrite( $tmpfile, $ciphertext );
460 fclose( $tmpfile );
461 header('Content-Disposition: attachment; filename='.$tmpfilename );
462 header("Content-Type: application/octet-stream" );
463 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
464 ob_clean();
465 flush();
466 readfile( $tmpfilepath.$tmpfilename );
467 unlink( $tmpfilepath.$tmpfilename );
468 } else {
469 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
470 header("Content-Type: " . $d->get_mimetype());
471 header("Content-Length: " . filesize($tmpcouchpath));
472 fpassthru($f);
474 fclose($f);
475 if($content!='')
476 unlink($tmpcouchpath);
477 exit;//exits only if file download from CouchDB is successfull.
479 //strip url of protocol handler
480 $url = preg_replace("|^(.*)://|","",$url);
482 //change full path to current webroot. this is for documents that may have
483 //been moved from a different filesystem and the full path in the database
484 //is not current. this is also for documents that may of been moved to
485 //different patients. Note that the path_depth is used to see how far down
486 //the path to go. For example, originally the path_depth was always 1, which
487 //only allowed things like documents/1/<file>, but now can have more structured
488 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
489 // etc.
490 // NOTE that $from_filename and basename($url) are the same thing
491 $from_all = explode("/",$url);
492 $from_filename = array_pop($from_all);
493 $from_pathname_array = array();
494 for ($i=0;$i<$d->get_path_depth();$i++) {
495 $from_pathname_array[] = array_pop($from_all);
497 $from_pathname_array = array_reverse($from_pathname_array);
498 $from_pathname = implode("/",$from_pathname_array);
499 if($couch_docid && $couch_revid){
500 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
501 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
504 else{
505 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
508 if (file_exists($temp_url)) {
509 $url = $temp_url;
513 if (!file_exists($url)) {
514 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;
517 else {
518 if ($original_file) {
519 //normal case when serving the file referenced in database
520 if($disable_exit == true) {
521 $f = fopen($url,"r");
522 $filetext = fread( $f, filesize($url) );
523 return $filetext;
525 header('Content-Description: File Transfer');
526 header('Content-Transfer-Encoding: binary');
527 header('Expires: 0');
528 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
529 header('Pragma: public');
530 $f = fopen($url,"r");
531 if ( $doEncryption ) {
532 $filetext = fread( $f, filesize($url) );
533 $ciphertext = $this->encrypt( $filetext, $passphrase );
534 $tmpfilepath = $GLOBALS['temporary_files_dir'];
535 $tmpfilename = "/encrypted_".$d->get_url_file();
536 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
537 fwrite( $tmpfile, $ciphertext );
538 fclose( $tmpfile );
539 header('Content-Disposition: attachment; filename='.$tmpfilename );
540 header("Content-Type: application/octet-stream" );
541 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
542 ob_clean();
543 flush();
544 readfile( $tmpfilepath.$tmpfilename );
545 unlink( $tmpfilepath.$tmpfilename );
546 } else {
547 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
548 header("Content-Type: " . $d->get_mimetype());
549 header("Content-Length: " . filesize($url));
550 fpassthru($f);
552 exit;
554 else {
555 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
556 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
557 if($couch_docid && $couch_revid){
558 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
560 else{
561 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
563 if($disable_exit == true) {
564 return ;
566 header("Pragma: public");
567 header("Expires: 0");
568 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
569 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
570 header("Content-Type: image/jpeg");
571 header("Content-Length: " . filesize($url));
572 $f = fopen($url,"r");
573 fpassthru($f);
574 if($couch_docid && $couch_revid){
575 fclose($f);
576 unlink($url);
577 $url=str_replace("_converted.jpg",'.pdf',$url);
578 unlink($url);
580 exit;
585 function queue_action($patient_id="") {
586 $messages = $this->_tpl_vars['messages'];
587 $queue_files = array();
589 //see if the repository exists and it is a directory else error
590 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
591 $dir = opendir($this->_config['repository']);
592 //read each entry in the directory
593 while (($file = readdir($dir)) !== false) {
594 //concat the filename and path
595 $file = $this->_config['repository'] .$file;
596 $file_info = array();
597 //if the filename is a file get its info and put into a tmp array
598 if (is_file($file) && strpos(basename($file),".") !== 0) {
599 $file_info['filename'] = basename($file);
600 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
601 $d = $this->Document->document_factory_url("file://" . $file);
602 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
603 $file_info['patient_id'] = $patient_match[1];
604 $file_info['document_id'] = $d->get_id();
605 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
607 //merge the tmp array into the larger array
608 $queue_files[] = $file_info;
611 closedir($dir);
613 else {
614 $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";
618 $this->assign("queue_files",$queue_files);
619 $this->_last_node = null;
621 $menu = new HTML_TreeMenu();
623 //pass an empty array because we don't want the documents for each category showing up in this list box
624 $rnode = $this->_array_recurse($this->tree->tree,array());
625 $menu->addItem($rnode);
626 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
628 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
630 $this->assign("messages",nl2br($messages));
631 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
634 function queue_action_process() {
635 if ($_POST['process'] != "true")
636 return;
638 $messages = $this->_tpl_vars['messages'];
640 //build a category tree so we can have a list of category ids that are valid
641 $ct = new CategoryTree(1);
642 $categories = $ct->_id_name;
644 //see if there were and posted files and assign them
645 $files = null;
646 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
648 //loop through posted files
649 foreach($files as $doc_id=> $file) {
650 //only operate on files checked as active
651 if (!$file['active']) continue;
653 //run basic validation checks
654 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
655 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
656 continue;
659 //validate that the pod exists
660 $d = new Document($doc_id);
661 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
662 $result = $d->_db->Execute($sql);
664 if (!$result || $result->EOF) {
665 //patient id does not exist
666 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
667 continue;
670 //validate that the category id exists
671 if (!isset($categories[$file['category_id']])) {
672 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
673 continue;
676 //now do the work of moving the file
677 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
679 //see if the patient dir exists in the repository and create if not
680 if (!file_exists($new_path)) {
681 if (!mkdir($new_path,0700)) {
682 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
683 continue;
687 //fname is the name of the file after it is moved
688 $fname = $file['name'];
690 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
691 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
692 if ($patient_match[1] == $file['patient_id']) {
693 $fname = preg_replace("/^([0-9]+)_/","",$fname);
696 //filenames should not have funny chars
697 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
699 //see if there is an existing file with the same name and rename as necessary
700 if (file_exists($new_path.$file['name'])) {
701 $messages .= "File with same name already exists at location: " . $new_path . "\n";
702 $fname = basename($this->_rename_file($new_path.$file['name']));
703 $messages .= "Current file name was changed to " . $fname ."\n";
706 //now move the file
707 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
708 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
709 $d->url = "file://" .$new_path.$fname;
710 $d->set_foreign_id($file['patient_id']);
711 $d->set_mimetype($mimetype);
712 $d->persist();
713 $d->populate();
715 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
716 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
717 $d->_db->Execute($sql);
720 else {
721 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
724 $this->assign("messages",$messages);
725 $_POST['process'] = "";
728 function move_action_process($patient_id="",$document_id) {
729 if ($_POST['process'] != "true")
730 return;
732 $new_category_id = $_POST['new_category_id'];
733 $new_patient_id = $_POST['new_patient_id'];
735 //move to new category
736 if (is_numeric($new_category_id) && is_numeric($document_id)) {
737 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
738 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
739 //echo $sql;
740 $this->tree->_db->Execute($sql);
743 //move to new patient
744 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
745 $d = new Document($document_id);
746 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
747 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
748 $result = $d->_db->Execute($sql);
750 if (!$result || $result->EOF) {
751 //patient id does not exist
752 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
754 else {
755 $couchsavefailed = !$d->change_patient($new_patient_id);
757 $this->_state = false;
758 if(!$couchsavefailed){
760 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
762 else{
764 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
766 $this->assign("messages",$messages);
767 return $this->list_action($patient_id);
770 //in this case return the document to the queue instead of moving it
771 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
772 $d = new Document($document_id);
773 $new_path = $this->_config['repository'];
774 $fname = $d->get_url_file();
776 //see if there is an existing file with the same name and rename as necessary
777 if (file_exists($new_path.$d->get_url_file())) {
778 $messages .= "File with same name already exists in the queue.\n";
779 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
780 $messages .= "Current file name was changed to " . $fname ."\n";
783 //now move the file
784 if (rename($d->get_url_filepath(),$new_path.$fname)) {
785 $d->url = "file://" .$new_path.$fname;
786 $d->set_foreign_id("");
787 $d->persist();
788 $d->persist();
789 $d->populate();
791 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
792 $d->_db->Execute($sql);
793 $messages .= "Document returned to queue successfully.\n";
796 else {
797 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
800 $this->_state = false;
801 $this->assign("messages",$messages);
802 return $this->list_action($patient_id);
805 $this->_state = false;
806 $this->assign("messages",$messages);
807 return $this->view_action($patient_id,$document_id);
810 function validate_action_process($patient_id="", $document_id) {
812 $d = new Document($document_id);
813 if($d->couch_docid && $d->couch_revid){
814 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
815 $url = $file_path.$d->get_url();
816 $couch = new CouchDB();
817 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
818 $resp = $couch->retrieve_doc($data);
819 $content = $resp->data;
820 //--------Temporarily writing the file for calculating the hash--------//
821 //-----------Will be removed after calculating the hash value----------//
822 $temp_file = fopen($url,"w");
823 fwrite($temp_file,base64_decode($content));
824 fclose($temp_file);
826 else{
827 $url = $d->get_url();
829 //strip url of protocol handler
830 $url = preg_replace("|^(.*)://|","",$url);
832 //change full path to current webroot. this is for documents that may have
833 //been moved from a different filesystem and the full path in the database
834 //is not current. this is also for documents that may of been moved to
835 //different patients. Note that the path_depth is used to see how far down
836 //the path to go. For example, originally the path_depth was always 1, which
837 //only allowed things like documents/1/<file>, but now can have more structured
838 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
839 // etc.
840 // NOTE that $from_filename and basename($url) are the same thing
841 $from_all = explode("/",$url);
842 $from_filename = array_pop($from_all);
843 $from_pathname_array = array();
844 for ($i=0;$i<$d->get_path_depth();$i++) {
845 $from_pathname_array[] = array_pop($from_all);
847 $from_pathname_array = array_reverse($from_pathname_array);
848 $from_pathname = implode("/",$from_pathname_array);
849 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
850 if (file_exists($temp_url)) {
851 $url = $temp_url;
854 if ($_POST['process'] != "true") {
855 die("process is '" . $_POST['process'] . "', expected 'true'");
856 return;
859 $d = new Document( $document_id );
860 $current_hash = sha1_file( $url );
861 $messages = xl('Current Hash').": ".$current_hash."<br>";
862 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
863 if ( $d->get_hash() == '' ) {
864 $d->hash = $current_hash;
865 $d->persist();
866 $d->populate();
867 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
868 } else if ( $current_hash != $d->get_hash() ) {
869 $messages .= xl('Hash does not match. Data integrity has been compromised.');
870 } else {
871 $messages .= xl('Document passed integrity check.');
873 $this->_state = false;
874 $this->assign("messages", $messages);
875 if($d->couch_docid && $d->couch_revid){
876 //Removing the temporary file which is used to create the hash
877 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
879 return $this->view_action($patient_id, $document_id);
882 // Added by Rod for metadata update.
884 function update_action_process($patient_id="", $document_id) {
886 if ($_POST['process'] != "true") {
887 die("process is '" . $_POST['process'] . "', expected 'true'");
888 return;
891 $docdate = $_POST['docdate'];
892 $docname = $_POST['docname'];
893 $issue_id = $_POST['issue_id'];
895 if (is_numeric($document_id)) {
896 $messages = '';
897 $d = new Document( $document_id );
898 $file_name = $d->get_url_file();
899 if ( $docname != '' &&
900 $docname != $file_name ) {
901 $path = $d->get_url_filepath();
902 $path = str_replace( $file_name, "", $path );
903 $new_url = $this->_rename_file( $path.$docname );
904 if ( rename( $d->get_url(), $new_url ) ) {
905 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
906 $url = preg_replace("|^(.*)://|","",$d->get_url());
907 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
908 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
909 if ( file_exists( $url ) ) {
910 unlink( $url );
912 $d->url = $new_url;
913 $d->persist();
914 $d->populate();
915 $messages .= xl('Document successfully renamed.')."<br>";
916 } else {
917 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
921 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
922 $docdate = "'$docdate'";
923 } else {
924 $docdate = "NULL";
926 if (!is_numeric($issue_id)) {
927 $issue_id = 0;
929 $couch_docid = $d->get_couch_docid();
930 $couch_revid = $d->get_couch_revid();
931 if($couch_docid && $couch_revid ){
932 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
933 "list_id = '$issue_id' " .
934 "WHERE id = '$document_id'";
935 $this->tree->_db->Execute($sql);
938 else{
939 $sql = "UPDATE documents SET docdate = $docdate, " .
940 "list_id = '$issue_id' " .
941 "WHERE id = '$document_id'";
942 $this->tree->_db->Execute($sql);
944 $messages .= xl('Document date and issue updated successfully') . "<br>";
947 $this->_state = false;
948 $this->assign("messages", $messages);
949 return $this->view_action($patient_id, $document_id);
952 function list_action($patient_id = "") {
953 $this->_last_node = null;
954 $categories_list = $this->tree->_get_categories_array($patient_id);
955 //print_r($categories_list);
957 $menu = new HTML_TreeMenu();
958 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
959 $menu->addItem($rnode);
960 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
961 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
963 $this->assign("tree_html",$treeMenu->toHTML());
965 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
968 /* This is a recursive function to rename a file to something that doesn't already exist.
969 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
970 * at end) to ensure documents opened correctly by external browser viewers. If the
971 * counter is at the end of the file, then will use it (to continue to work with older
972 * files), however all new counters will be placed within filenames.
974 * Modified to only deal with base file name when renaming, to avoid issues with directory
975 * names with dots.
977 function _rename_file($fname) {
978 $path = dirname($fname);
979 $file = basename($fname);
981 $fparts = explode("\.",$file);
983 if (count($fparts) > 1) {
984 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
985 //increment the counter in filename
986 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
987 } elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
988 //increment counter at end of filename (so compatible with previous openemr version files
989 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
990 } elseif (is_numeric($fparts[count($fparts) -1])) {
991 //leave date at end and place counter in filename
992 array_splice($fparts, -1, 0, "1");
993 } else {
994 //add the counter to filename
995 array_splice($fparts, -1, 0, "1");
997 } else { // (count($fparts) == 1)
998 //place counter at end of filename
999 array_push($fparts, "1");
1002 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1004 if (file_exists($fname)) {
1005 return $this->_rename_file($fname);
1006 } else {
1007 return($fname);
1011 function &_array_recurse($array,$categories = array()) {
1012 if (!is_array($array)) {
1013 $array = array();
1015 $node = &$this->_last_node;
1016 $current_node = &$node;
1017 $expandedIcon = 'folder-expanded.gif';
1018 foreach($array as $id => $ar) {
1019 $icon = 'folder.gif';
1020 if (is_array($ar) || !empty($id)) {
1021 if ($node == null) {
1022 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1023 $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));
1024 $this->_last_node = &$rnode;
1025 $node = &$rnode;
1026 $current_node = &$rnode;
1028 else {
1029 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1030 $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)));
1031 $current_node = &$this->_last_node;
1034 $this->_array_recurse($ar,$categories);
1036 else {
1037 if ($id === 0 && !empty($ar)) {
1038 $info = $this->tree->get_node_info($id);
1039 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1040 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1042 else {
1043 //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
1044 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1045 if ($id !== 0 && is_object($node)) {
1046 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1047 $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)));
1053 // If there are documents in this document category, then add their
1054 // attributes to the current node.
1055 $icon = "file3.png";
1056 if (is_array($categories[$id])) {
1057 foreach ($categories[$id] as $doc) {
1058 if($this->tree->get_node_name($id) == "CCR"){
1059 $current_node->addItem(new HTML_TreeNode(array(
1060 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1061 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1062 'icon' => $icon,
1063 'expandedIcon' => $expandedIcon,
1064 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1065 )));
1066 }elseif($this->tree->get_node_name($id) == "CCD"){
1067 $current_node->addItem(new HTML_TreeNode(array(
1068 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1069 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1070 'icon' => $icon,
1071 'expandedIcon' => $expandedIcon,
1072 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1073 )));
1074 }else{
1075 $current_node->addItem(new HTML_TreeNode(array(
1076 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1077 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1078 'icon' => $icon,
1079 'expandedIcon' => $expandedIcon
1080 )));
1086 return $node;
1089 //function for logging the errors in writing file to CouchDB/Hard Disk
1090 function document_upload_download_log($patientid,$content){
1091 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1092 $log_file = 'log.txt';
1093 if(!is_dir($log_path))
1094 mkdir($log_path,0777,true);
1095 $LOG = fopen($log_path.$log_file,'a');
1096 fwrite($LOG,$content);
1097 fclose($LOG);
1100 function document_send($email,$body,$attfile,$pname) {
1101 if (empty($email)) {
1102 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1103 return;
1106 $desc = "Please check the attached patient document.\n Content:".attr($body);
1107 $mail = new MyMailer();
1108 $from_name = $GLOBALS["practice_return_email_path"];
1109 $from = $GLOBALS["practice_return_email_path"];
1110 $mail->AddReplyTo($from,$from_name);
1111 $mail->SetFrom($from,$from );
1112 $to = $email ; $to_name =$email;
1113 $mail->AddAddress($to, $to_name);
1114 $subject = "Patient documents";
1115 $mail->Subject = $subject;
1116 $mail->Body = $desc;
1117 $mail->AddAttachment($attfile);
1118 if ($mail->Send()) {
1119 $retstatus = "email_sent";
1120 } else {
1121 $email_status = $mail->ErrorInfo;
1122 //echo "EMAIL ERROR: ".$email_status;
1123 $retstatus = "email_fail";
1127 //place to hold optional code
1128 //$first_node = array_keys($t->tree);
1129 //$first_node = $first_node[0];
1130 //$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')"));
1132 //$this->_last_node = &$node1;
1134 // Function to tag a document to an encounter.
1135 function tag_action_process($patient_id="", $document_id) {
1136 if ($_POST['process'] != "true") {
1137 die("process is '" . text($_POST['process']) . "', expected 'true'");
1138 return;
1141 // Create Encounter and Tag it.
1142 $event_date = date('Y-m-d H:i:s');
1143 $encounter_id = $_POST['encounter_id'];
1144 $encounter_check = $_POST['encounter_check'];
1145 $visit_category_id = $_POST['visit_category_id'];
1147 if (is_numeric($document_id)) {
1148 $messages = '';
1149 $d = new Document( $document_id );
1150 $file_name = $d->get_url_file();
1151 if (!is_numeric($encounter_id)) {
1152 $encounter_id = 0;
1155 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1156 if ($encounter_check) {
1157 $provider_id = $_SESSION['authUserID'] ;
1159 // Get the logged in user's facility
1160 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1161 $username = $facilityRow['username'];
1162 $facility = $facilityRow['facility'];
1163 $facility_id = $facilityRow['facility_id'];
1164 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1165 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1166 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1168 $conn = $GLOBALS['adodb']['db'];
1169 $encounter = $conn->GenID("sequences");
1170 $query = "INSERT INTO form_encounter SET
1171 date = ?,
1172 reason = ?,
1173 facility = ?,
1174 sensitivity = 'normal',
1175 pc_catid = ?,
1176 facility_id = ?,
1177 billing_facility = ?,
1178 provider_id = ?,
1179 pid = ?,
1180 encounter = ?";
1181 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1182 $formID = sqlInsert($query,$bindArray);
1183 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1184 $d->set_encounter_id($encounter);
1186 } else {
1187 $d->set_encounter_id($encounter_id);
1189 $d->set_encounter_check($encounter_check);
1190 $d->persist();
1192 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1195 $this->_state = false;
1196 $this->assign("messages", $messages);
1198 return $this->view_action($patient_id, $document_id);