PHP warning fixes
[openemr.git] / controllers / C_Document.class.php
blob56f4476cf28b7abf2102eea64d89bb591f835437
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 if (file_exists($templatedir)) {
57 $dh = opendir($templatedir);
59 if ($dh) {
60 $templateslist = array();
61 while (false !== ($sfname = readdir($dh))) {
62 if (substr($sfname, 0, 1) == '.') continue;
63 $templateslist[$sfname] = $sfname;
65 closedir($dh);
66 ksort($templateslist);
67 foreach ($templateslist as $sfname) {
68 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
69 "'>" . htmlspecialchars($sfname) . "</option>";
72 $this->assign("TEMPLATES_LIST", $templates_options);
74 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
75 $this->assign("activity", $activity);
76 return $this->list_action($patient_id);
79 //Upload multiple files on single click
80 function upload_action_process() {
82 // Collect a manually set owner if this has been set
83 // Used when want to manually assign the owning user/service such as the Direct mechanism
84 $non_HTTP_owner=false;
85 if ($this->manual_set_owner) {
86 $non_HTTP_owner=$this->manual_set_owner;
89 $couchDB = false;
90 $harddisk = false;
91 if($GLOBALS['document_storage_method']==0){
92 $harddisk = true;
94 if($GLOBALS['document_storage_method']==1){
95 $couchDB = true;
98 if ($_POST['process'] != "true")
99 return;
101 $doDecryption = false;
102 $encrypted = $_POST['encrypted'];
103 $passphrase = $_POST['passphrase'];
104 if ( !$GLOBALS['hide_document_encryption'] &&
105 $encrypted && $passphrase ) {
106 $doDecryption = true;
109 if (is_numeric($_POST['category_id'])) {
110 $category_id = $_POST['category_id'];
113 $patient_id = 0;
114 if (isset($_GET['patient_id']) && !$couchDB) {
115 $patient_id = $_GET['patient_id'];
117 else if (is_numeric($_POST['patient_id'])) {
118 $patient_id = $_POST['patient_id'];
121 $sentUploadStatus = array();
122 if( count($_FILES['file']['name']) > 0){
123 $upl_inc = 0;
124 foreach($_FILES['file']['name'] as $key => $value){
125 $fname = $value;
126 $err = "";
127 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
128 $fname = $value;
129 if (empty($fname)) {
130 $fname = htmlentities("<empty>");
132 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
133 if ($_FILES['file']['size'][$key] == 0) {
134 $error .= "The system does not permit uploading files of with size 0.\n";
136 }else{
137 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
138 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
139 fclose($tmpfile);
140 if ($doDecryption) {
141 $filetext = $this->decrypt($filetext, $passphrase);
143 if ( $_POST['destination'] != '' ) {
144 $fname = $_POST['destination'];
146 $d = new Document();
147 $rc = $d->createDocument($patient_id, $category_id, $fname,
148 $_FILES['file']['type'][$key], $filetext,
149 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
150 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
151 $non_HTTP_owner);
152 if ($rc) {
153 $error .= $rc . "\n";
155 else {
156 $this->assign("upload_success", "true");
158 $sentUploadStatus[] = $d;
159 $this->assign("file", $sentUploadStatus);
162 // Option to run a custom plugin for each file upload.
163 // This was initially created to delete the original source file in a custom setting.
164 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
165 if (file_exists($upload_plugin)) {
166 include_once($upload_plugin);
168 $upload_plugin_pp = 'documentUploadPostProcess';
169 if (function_exists($upload_plugin_pp)) {
170 $tmp = call_user_func($upload_plugin_pp, $value, $d);
171 if ($tmp) {
172 $error = $tmp;
175 // Following is just an example of code in such a plugin file.
176 /*****************************************************
177 function documentUploadPostProcess($filename, &$d) {
178 $userid = $_SESSION['authUserID'];
179 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
180 $owner = strtolower($row['username']);
181 $dn = '1_' . ucfirst($owner);
182 $filepath = "/shared_network_directory/$dn/$filename";
183 if (@unlink($filepath)) return '';
184 return "Failed to delete '$filepath'.";
186 *****************************************************/
191 $this->assign("error", nl2br($error));
192 //$this->_state = false;
193 $_POST['process'] = "";
194 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
197 function note_action_process($patient_id) {
198 // this function is a dual function that will set up a note associated with a document or send a document via email.
200 if ($_POST['process'] != "true")
201 return;
203 $n = new Note();
204 $n->set_owner($_SESSION['authUserID']);
205 parent::populate_object($n);
206 if ($_POST['identifier'] == "no"){
207 // associate a note with a document
208 $n->persist();
209 }elseif ($_POST['identifier'] == "yes"){
210 // send the document via email
211 $d = new Document($_POST['foreign_id']);
212 $url = $d->get_url();
213 $storagemethod = $d->get_storagemethod();
214 $couch_docid = $d->get_couch_docid();
215 $couch_revid = $d->get_couch_revid();
216 if($couch_docid && $couch_revid){
217 $couch = new CouchDB();
218 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
219 $resp = $couch->retrieve_doc($data);
220 $content = $resp->data;
221 if($content=='' && $GLOBALS['couchdb_log']==1){
222 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
223 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
224 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
225 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
226 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
227 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
228 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
229 die(xlt("File retrieval from CouchDB failed"));
231 // place it in a temporary file and will remove the file below after emailed
232 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
233 $fh = fopen($temp_couchdb_url,"w");
234 fwrite($fh,base64_decode($content));
235 fclose($fh);
236 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
237 } else {
238 $url = preg_replace("|^(.*)://|","",$url);
239 // Collect filename and path
240 $from_all = explode("/",$url);
241 $from_filename = array_pop($from_all);
242 $from_pathname_array = array();
243 for ($i=0;$i<$d->get_path_depth();$i++) {
244 $from_pathname_array[] = array_pop($from_all);
246 $from_pathname_array = array_reverse($from_pathname_array);
247 $from_pathname = implode("/",$from_pathname_array);
248 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
250 if (!file_exists($temp_url)) {
251 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;
253 $url = $temp_url;
254 $body_notes = attr($_POST['note']);
255 $pdetails = getPatientData($patient_id);
256 $pname = $pdetails['fname']." ".$pdetails['lname'];
257 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
258 if ($couch_docid && $couch_revid) {
259 // remove the temporary couchdb file
260 unlink($temp_couchdb_url);
263 $this->_state = false;
264 $_POST['process'] = "";
265 return $this->view_action($patient_id,$n->get_foreign_id());
268 function default_action() {
269 return $this->list_action();
272 function view_action($patient_id="",$doc_id) {
273 // Added by Rod to support document delete:
274 global $gacl_object, $phpgacl_location;
275 global $ISSUE_TYPES;
277 require_once(dirname(__FILE__) . "/../library/acl.inc");
278 require_once(dirname(__FILE__) . "/../library/lists.inc");
280 $d = new Document($doc_id);
281 $n = new Note();
283 $notes = $n->notes_factory($doc_id);
285 $this->assign("file", $d);
286 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
287 $this->assign("NOTE_ACTION",$this->_link("note"));
288 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
289 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
291 // Added by Rod to support document delete:
292 $delete_string = '';
293 if (acl_check('admin', 'super')) {
294 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
295 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
297 $this->assign("delete_string", $delete_string);
298 $this->assign("REFRESH_ACTION",$this->_link("list"));
300 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
301 "document_id=" . $d->get_id() . "&process=true");
303 // Added by Rod to support document date update:
304 $this->assign("DOCDATE", $d->get_docdate());
305 $this->assign("UPDATE_ACTION",$this->_link("update") .
306 "document_id=" . $d->get_id() . "&process=true");
308 // Added by Rod to support document issue update:
309 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
310 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
311 "pid = ? " . // AND enddate IS NULL " .
312 "ORDER BY type, begdate", array($patient_id) );
313 while ($irow = sqlFetchArray($ires)) {
314 $desc = $irow['type'];
315 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
316 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
317 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
318 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
320 $this->assign("ISSUES_LIST", $issues_options);
322 // For tagging to encounter
323 // Populate the dropdown with patient's encounter list
324 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
325 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
326 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
327 "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));
328 if ( sqlNumRows($result_docs) > 0)
329 while($row_result_docs = sqlFetchArray($result_docs)) {
330 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
331 $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>";
333 $this->assign("ENC_LIST", $encOptions);
335 //Populate the dropdown with category list
336 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
337 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
338 while ($crow = sqlFetchArray($cres)) {
339 $catid = $crow['pc_catid'];
340 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
341 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
343 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
345 $this->assign("notes",$notes);
347 $this->_last_node = null;
349 $menu = new HTML_TreeMenu();
351 //pass an empty array because we don't want the documents for each category showing up in this list box
352 $rnode = $this->_array_recurse($this->tree->tree,array());
353 $menu->addItem($rnode);
354 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
356 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
358 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
359 $this->assign("activity", $activity);
361 return $this->list_action($patient_id);
364 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
366 $td = mcrypt_module_open( $cypher, '', $mode, '');
367 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
368 mcrypt_generic_init( $td, $key, $iv );
369 $crypttext = mcrypt_generic( $td, $plaintext );
370 mcrypt_generic_deinit( $td );
371 return $iv.$crypttext;
374 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
376 $plaintext = '';
377 $td = mcrypt_module_open( $cypher, '', $mode, '' );
378 $ivsize = mcrypt_enc_get_iv_size( $td) ;
379 $iv = substr( $crypttext, 0, $ivsize );
380 $crypttext = substr( $crypttext, $ivsize );
381 if( $iv )
383 mcrypt_generic_init( $td, $key, $iv );
384 $plaintext = mdecrypt_generic( $td, $crypttext );
386 return $plaintext;
390 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false) {
392 $encrypted = $_POST['encrypted'];
393 $passphrase = $_POST['passphrase'];
394 $doEncryption = false;
395 if ( !$GLOBALS['hide_document_encryption'] &&
396 $encrypted == "true" &&
397 $passphrase ) {
398 $doEncryption = true;
401 //controller function ruins booleans, so need to manually re-convert to booleans
402 if ($as_file == "true") {
403 $as_file=true;
405 else if ($as_file == "false") {
406 $as_file=false;
408 if ($original_file == "true") {
409 $original_file=true;
411 else if ($original_file == "false") {
412 $original_file=false;
414 if ($disable_exit == "true") {
415 $disable_exit=true;
417 else if ($disable_exit == "false") {
418 $disable_exit=false;
421 $d = new Document($document_id);
422 $url = $d->get_url();
423 $storagemethod = $d->get_storagemethod();
424 $couch_docid = $d->get_couch_docid();
425 $couch_revid = $d->get_couch_revid();
427 if($couch_docid && $couch_revid && $original_file){
428 $couch = new CouchDB();
429 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
430 $resp = $couch->retrieve_doc($data);
431 $content = $resp->data;
432 if($content=='' && $GLOBALS['couchdb_log']==1){
433 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
434 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
435 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
436 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
437 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
438 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
439 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
440 die(xl("File retrieval from CouchDB failed"));
442 if($disable_exit == true) {
443 return base64_decode($content);
445 header('Content-Description: File Transfer');
446 header('Content-Transfer-Encoding: binary');
447 header('Expires: 0');
448 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
449 header('Pragma: public');
450 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
451 $fh = fopen($tmpcouchpath,"w");
452 fwrite($fh,base64_decode($content));
453 fclose($fh);
454 $f = fopen($tmpcouchpath,"r");
455 if ( $doEncryption ) {
456 $filetext = fread( $f, filesize($tmpcouchpath) );
457 $ciphertext = $this->encrypt( $filetext, $passphrase );
458 $tmpfilepath = $GLOBALS['temporary_files_dir'];
459 $tmpfilename = "/encrypted_".$d->get_url_file();
460 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
461 fwrite( $tmpfile, $ciphertext );
462 fclose( $tmpfile );
463 header('Content-Disposition: attachment; filename='.$tmpfilename );
464 header("Content-Type: application/octet-stream" );
465 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
466 ob_clean();
467 flush();
468 readfile( $tmpfilepath.$tmpfilename );
469 unlink( $tmpfilepath.$tmpfilename );
470 } else {
471 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
472 header("Content-Type: " . $d->get_mimetype());
473 header("Content-Length: " . filesize($tmpcouchpath));
474 fpassthru($f);
476 fclose($f);
477 if($content!='')
478 unlink($tmpcouchpath);
479 exit;//exits only if file download from CouchDB is successfull.
481 //strip url of protocol handler
482 $url = preg_replace("|^(.*)://|","",$url);
484 //change full path to current webroot. this is for documents that may have
485 //been moved from a different filesystem and the full path in the database
486 //is not current. this is also for documents that may of been moved to
487 //different patients. Note that the path_depth is used to see how far down
488 //the path to go. For example, originally the path_depth was always 1, which
489 //only allowed things like documents/1/<file>, but now can have more structured
490 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
491 // etc.
492 // NOTE that $from_filename and basename($url) are the same thing
493 $from_all = explode("/",$url);
494 $from_filename = array_pop($from_all);
495 $from_pathname_array = array();
496 for ($i=0;$i<$d->get_path_depth();$i++) {
497 $from_pathname_array[] = array_pop($from_all);
499 $from_pathname_array = array_reverse($from_pathname_array);
500 $from_pathname = implode("/",$from_pathname_array);
501 if($couch_docid && $couch_revid){
502 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
503 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
506 else{
507 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
510 if (file_exists($temp_url)) {
511 $url = $temp_url;
515 if (!file_exists($url)) {
516 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;
519 else {
520 if ($original_file) {
521 //normal case when serving the file referenced in database
522 if($disable_exit == true) {
523 $f = fopen($url,"r");
524 $filetext = fread( $f, filesize($url) );
525 return $filetext;
527 header('Content-Description: File Transfer');
528 header('Content-Transfer-Encoding: binary');
529 header('Expires: 0');
530 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
531 header('Pragma: public');
532 $f = fopen($url,"r");
533 if ( $doEncryption ) {
534 $filetext = fread( $f, filesize($url) );
535 $ciphertext = $this->encrypt( $filetext, $passphrase );
536 $tmpfilepath = $GLOBALS['temporary_files_dir'];
537 $tmpfilename = "/encrypted_".$d->get_url_file();
538 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
539 fwrite( $tmpfile, $ciphertext );
540 fclose( $tmpfile );
541 header('Content-Disposition: attachment; filename='.$tmpfilename );
542 header("Content-Type: application/octet-stream" );
543 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
544 ob_clean();
545 flush();
546 readfile( $tmpfilepath.$tmpfilename );
547 unlink( $tmpfilepath.$tmpfilename );
548 } else {
549 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
550 header("Content-Type: " . $d->get_mimetype());
551 header("Content-Length: " . filesize($url));
552 fpassthru($f);
554 exit;
556 else {
557 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
558 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
559 if($couch_docid && $couch_revid){
560 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
562 else{
563 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
565 if($disable_exit == true) {
566 return ;
568 header("Pragma: public");
569 header("Expires: 0");
570 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
571 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
572 header("Content-Type: image/jpeg");
573 header("Content-Length: " . filesize($url));
574 $f = fopen($url,"r");
575 fpassthru($f);
576 if($couch_docid && $couch_revid){
577 fclose($f);
578 unlink($url);
579 $url=str_replace("_converted.jpg",'.pdf',$url);
580 unlink($url);
582 exit;
587 function queue_action($patient_id="") {
588 $messages = $this->_tpl_vars['messages'];
589 $queue_files = array();
591 //see if the repository exists and it is a directory else error
592 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
593 $dir = opendir($this->_config['repository']);
594 //read each entry in the directory
595 while (($file = readdir($dir)) !== false) {
596 //concat the filename and path
597 $file = $this->_config['repository'] .$file;
598 $file_info = array();
599 //if the filename is a file get its info and put into a tmp array
600 if (is_file($file) && strpos(basename($file),".") !== 0) {
601 $file_info['filename'] = basename($file);
602 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
603 $d = $this->Document->document_factory_url("file://" . $file);
604 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
605 $file_info['patient_id'] = $patient_match[1];
606 $file_info['document_id'] = $d->get_id();
607 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
609 //merge the tmp array into the larger array
610 $queue_files[] = $file_info;
613 closedir($dir);
615 else {
616 $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";
620 $this->assign("queue_files",$queue_files);
621 $this->_last_node = null;
623 $menu = new HTML_TreeMenu();
625 //pass an empty array because we don't want the documents for each category showing up in this list box
626 $rnode = $this->_array_recurse($this->tree->tree,array());
627 $menu->addItem($rnode);
628 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
630 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
632 $this->assign("messages",nl2br($messages));
633 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
636 function queue_action_process() {
637 if ($_POST['process'] != "true")
638 return;
640 $messages = $this->_tpl_vars['messages'];
642 //build a category tree so we can have a list of category ids that are valid
643 $ct = new CategoryTree(1);
644 $categories = $ct->_id_name;
646 //see if there were and posted files and assign them
647 $files = null;
648 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
650 //loop through posted files
651 foreach($files as $doc_id=> $file) {
652 //only operate on files checked as active
653 if (!$file['active']) continue;
655 //run basic validation checks
656 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
657 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
658 continue;
661 //validate that the pod exists
662 $d = new Document($doc_id);
663 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
664 $result = $d->_db->Execute($sql);
666 if (!$result || $result->EOF) {
667 //patient id does not exist
668 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
669 continue;
672 //validate that the category id exists
673 if (!isset($categories[$file['category_id']])) {
674 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
675 continue;
678 //now do the work of moving the file
679 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
681 //see if the patient dir exists in the repository and create if not
682 if (!file_exists($new_path)) {
683 if (!mkdir($new_path,0700)) {
684 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
685 continue;
689 //fname is the name of the file after it is moved
690 $fname = $file['name'];
692 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
693 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
694 if ($patient_match[1] == $file['patient_id']) {
695 $fname = preg_replace("/^([0-9]+)_/","",$fname);
698 //filenames should not have funny chars
699 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
701 //see if there is an existing file with the same name and rename as necessary
702 if (file_exists($new_path.$file['name'])) {
703 $messages .= "File with same name already exists at location: " . $new_path . "\n";
704 $fname = basename($this->_rename_file($new_path.$file['name']));
705 $messages .= "Current file name was changed to " . $fname ."\n";
708 //now move the file
709 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
710 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
711 $d->url = "file://" .$new_path.$fname;
712 $d->set_foreign_id($file['patient_id']);
713 $d->set_mimetype($mimetype);
714 $d->persist();
715 $d->populate();
717 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
718 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
719 $d->_db->Execute($sql);
722 else {
723 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
726 $this->assign("messages",$messages);
727 $_POST['process'] = "";
730 function move_action_process($patient_id="",$document_id) {
731 if ($_POST['process'] != "true")
732 return;
734 $new_category_id = $_POST['new_category_id'];
735 $new_patient_id = $_POST['new_patient_id'];
737 //move to new category
738 if (is_numeric($new_category_id) && is_numeric($document_id)) {
739 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
740 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
741 //echo $sql;
742 $this->tree->_db->Execute($sql);
745 //move to new patient
746 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
747 $d = new Document($document_id);
748 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
749 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
750 $result = $d->_db->Execute($sql);
752 if (!$result || $result->EOF) {
753 //patient id does not exist
754 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
756 else {
757 $couchsavefailed = !$d->change_patient($new_patient_id);
759 $this->_state = false;
760 if(!$couchsavefailed){
762 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
764 else{
766 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
768 $this->assign("messages",$messages);
769 return $this->list_action($patient_id);
772 //in this case return the document to the queue instead of moving it
773 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
774 $d = new Document($document_id);
775 $new_path = $this->_config['repository'];
776 $fname = $d->get_url_file();
778 //see if there is an existing file with the same name and rename as necessary
779 if (file_exists($new_path.$d->get_url_file())) {
780 $messages .= "File with same name already exists in the queue.\n";
781 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
782 $messages .= "Current file name was changed to " . $fname ."\n";
785 //now move the file
786 if (rename($d->get_url_filepath(),$new_path.$fname)) {
787 $d->url = "file://" .$new_path.$fname;
788 $d->set_foreign_id("");
789 $d->persist();
790 $d->persist();
791 $d->populate();
793 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
794 $d->_db->Execute($sql);
795 $messages .= "Document returned to queue successfully.\n";
798 else {
799 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
802 $this->_state = false;
803 $this->assign("messages",$messages);
804 return $this->list_action($patient_id);
807 $this->_state = false;
808 $this->assign("messages",$messages);
809 return $this->view_action($patient_id,$document_id);
812 function validate_action_process($patient_id="", $document_id) {
814 $d = new Document($document_id);
815 if($d->couch_docid && $d->couch_revid){
816 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
817 $url = $file_path.$d->get_url();
818 $couch = new CouchDB();
819 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
820 $resp = $couch->retrieve_doc($data);
821 $content = $resp->data;
822 //--------Temporarily writing the file for calculating the hash--------//
823 //-----------Will be removed after calculating the hash value----------//
824 $temp_file = fopen($url,"w");
825 fwrite($temp_file,base64_decode($content));
826 fclose($temp_file);
828 else{
829 $url = $d->get_url();
831 //strip url of protocol handler
832 $url = preg_replace("|^(.*)://|","",$url);
834 //change full path to current webroot. this is for documents that may have
835 //been moved from a different filesystem and the full path in the database
836 //is not current. this is also for documents that may of been moved to
837 //different patients. Note that the path_depth is used to see how far down
838 //the path to go. For example, originally the path_depth was always 1, which
839 //only allowed things like documents/1/<file>, but now can have more structured
840 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
841 // etc.
842 // NOTE that $from_filename and basename($url) are the same thing
843 $from_all = explode("/",$url);
844 $from_filename = array_pop($from_all);
845 $from_pathname_array = array();
846 for ($i=0;$i<$d->get_path_depth();$i++) {
847 $from_pathname_array[] = array_pop($from_all);
849 $from_pathname_array = array_reverse($from_pathname_array);
850 $from_pathname = implode("/",$from_pathname_array);
851 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
852 if (file_exists($temp_url)) {
853 $url = $temp_url;
856 if ($_POST['process'] != "true") {
857 die("process is '" . $_POST['process'] . "', expected 'true'");
858 return;
861 $d = new Document( $document_id );
862 $current_hash = sha1_file( $url );
863 $messages = xl('Current Hash').": ".$current_hash."<br>";
864 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
865 if ( $d->get_hash() == '' ) {
866 $d->hash = $current_hash;
867 $d->persist();
868 $d->populate();
869 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
870 } else if ( $current_hash != $d->get_hash() ) {
871 $messages .= xl('Hash does not match. Data integrity has been compromised.');
872 } else {
873 $messages .= xl('Document passed integrity check.');
875 $this->_state = false;
876 $this->assign("messages", $messages);
877 if($d->couch_docid && $d->couch_revid){
878 //Removing the temporary file which is used to create the hash
879 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
881 return $this->view_action($patient_id, $document_id);
884 // Added by Rod for metadata update.
886 function update_action_process($patient_id="", $document_id) {
888 if ($_POST['process'] != "true") {
889 die("process is '" . $_POST['process'] . "', expected 'true'");
890 return;
893 $docdate = $_POST['docdate'];
894 $docname = $_POST['docname'];
895 $issue_id = $_POST['issue_id'];
897 if (is_numeric($document_id)) {
898 $messages = '';
899 $d = new Document( $document_id );
900 $file_name = $d->get_url_file();
901 if ( $docname != '' &&
902 $docname != $file_name ) {
903 $path = $d->get_url_filepath();
904 $path = str_replace( $file_name, "", $path );
905 $new_url = $this->_rename_file( $path.$docname );
906 if ( rename( $d->get_url(), $new_url ) ) {
907 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
908 $url = preg_replace("|^(.*)://|","",$d->get_url());
909 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
910 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
911 if ( file_exists( $url ) ) {
912 unlink( $url );
914 $d->url = $new_url;
915 $d->persist();
916 $d->populate();
917 $messages .= xl('Document successfully renamed.')."<br>";
918 } else {
919 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
923 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
924 $docdate = "'$docdate'";
925 } else {
926 $docdate = "NULL";
928 if (!is_numeric($issue_id)) {
929 $issue_id = 0;
931 $couch_docid = $d->get_couch_docid();
932 $couch_revid = $d->get_couch_revid();
933 if($couch_docid && $couch_revid ){
934 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
935 "list_id = '$issue_id' " .
936 "WHERE id = '$document_id'";
937 $this->tree->_db->Execute($sql);
940 else{
941 $sql = "UPDATE documents SET docdate = $docdate, " .
942 "list_id = '$issue_id' " .
943 "WHERE id = '$document_id'";
944 $this->tree->_db->Execute($sql);
946 $messages .= xl('Document date and issue updated successfully') . "<br>";
949 $this->_state = false;
950 $this->assign("messages", $messages);
951 return $this->view_action($patient_id, $document_id);
954 function list_action($patient_id = "") {
955 $this->_last_node = null;
956 $categories_list = $this->tree->_get_categories_array($patient_id);
957 //print_r($categories_list);
959 $menu = new HTML_TreeMenu();
960 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
961 $menu->addItem($rnode);
962 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
963 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
965 $this->assign("tree_html",$treeMenu->toHTML());
967 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
970 /* This is a recursive function to rename a file to something that doesn't already exist.
971 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
972 * at end) to ensure documents opened correctly by external browser viewers. If the
973 * counter is at the end of the file, then will use it (to continue to work with older
974 * files), however all new counters will be placed within filenames.
976 * Modified to only deal with base file name when renaming, to avoid issues with directory
977 * names with dots.
979 function _rename_file($fname) {
980 $path = dirname($fname);
981 $file = basename($fname);
983 $fparts = explode("\.",$file);
985 if (count($fparts) > 1) {
986 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
987 //increment the counter in filename
988 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
989 } elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
990 //increment counter at end of filename (so compatible with previous openemr version files
991 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
992 } elseif (is_numeric($fparts[count($fparts) -1])) {
993 //leave date at end and place counter in filename
994 array_splice($fparts, -1, 0, "1");
995 } else {
996 //add the counter to filename
997 array_splice($fparts, -1, 0, "1");
999 } else { // (count($fparts) == 1)
1000 //place counter at end of filename
1001 array_push($fparts, "1");
1004 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1006 if (file_exists($fname)) {
1007 return $this->_rename_file($fname);
1008 } else {
1009 return($fname);
1013 function &_array_recurse($array,$categories = array()) {
1014 if (!is_array($array)) {
1015 $array = array();
1017 $node = &$this->_last_node;
1018 $current_node = &$node;
1019 $expandedIcon = 'folder-expanded.gif';
1020 foreach($array as $id => $ar) {
1021 $icon = 'folder.gif';
1022 if (is_array($ar) || !empty($id)) {
1023 if ($node == null) {
1024 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1025 $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));
1026 $this->_last_node = &$rnode;
1027 $node = &$rnode;
1028 $current_node = &$rnode;
1030 else {
1031 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1032 $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)));
1033 $current_node = &$this->_last_node;
1036 $this->_array_recurse($ar,$categories);
1038 else {
1039 if ($id === 0 && !empty($ar)) {
1040 $info = $this->tree->get_node_info($id);
1041 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1042 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1044 else {
1045 //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
1046 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1047 if ($id !== 0 && is_object($node)) {
1048 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1049 $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)));
1055 // If there are documents in this document category, then add their
1056 // attributes to the current node.
1057 $icon = "file3.png";
1058 if (is_array($categories[$id])) {
1059 foreach ($categories[$id] as $doc) {
1060 if($this->tree->get_node_name($id) == "CCR"){
1061 $current_node->addItem(new HTML_TreeNode(array(
1062 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1063 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1064 'icon' => $icon,
1065 'expandedIcon' => $expandedIcon,
1066 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1067 )));
1068 }elseif($this->tree->get_node_name($id) == "CCD"){
1069 $current_node->addItem(new HTML_TreeNode(array(
1070 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1071 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1072 'icon' => $icon,
1073 'expandedIcon' => $expandedIcon,
1074 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1075 )));
1076 }else{
1077 $current_node->addItem(new HTML_TreeNode(array(
1078 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1079 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1080 'icon' => $icon,
1081 'expandedIcon' => $expandedIcon
1082 )));
1088 return $node;
1091 //function for logging the errors in writing file to CouchDB/Hard Disk
1092 function document_upload_download_log($patientid,$content){
1093 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1094 $log_file = 'log.txt';
1095 if(!is_dir($log_path))
1096 mkdir($log_path,0777,true);
1097 $LOG = fopen($log_path.$log_file,'a');
1098 fwrite($LOG,$content);
1099 fclose($LOG);
1102 function document_send($email,$body,$attfile,$pname) {
1103 if (empty($email)) {
1104 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1105 return;
1108 $desc = "Please check the attached patient document.\n Content:".attr($body);
1109 $mail = new MyMailer();
1110 $from_name = $GLOBALS["practice_return_email_path"];
1111 $from = $GLOBALS["practice_return_email_path"];
1112 $mail->AddReplyTo($from,$from_name);
1113 $mail->SetFrom($from,$from );
1114 $to = $email ; $to_name =$email;
1115 $mail->AddAddress($to, $to_name);
1116 $subject = "Patient documents";
1117 $mail->Subject = $subject;
1118 $mail->Body = $desc;
1119 $mail->AddAttachment($attfile);
1120 if ($mail->Send()) {
1121 $retstatus = "email_sent";
1122 } else {
1123 $email_status = $mail->ErrorInfo;
1124 //echo "EMAIL ERROR: ".$email_status;
1125 $retstatus = "email_fail";
1129 //place to hold optional code
1130 //$first_node = array_keys($t->tree);
1131 //$first_node = $first_node[0];
1132 //$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')"));
1134 //$this->_last_node = &$node1;
1136 // Function to tag a document to an encounter.
1137 function tag_action_process($patient_id="", $document_id) {
1138 if ($_POST['process'] != "true") {
1139 die("process is '" . text($_POST['process']) . "', expected 'true'");
1140 return;
1143 // Create Encounter and Tag it.
1144 $event_date = date('Y-m-d H:i:s');
1145 $encounter_id = $_POST['encounter_id'];
1146 $encounter_check = $_POST['encounter_check'];
1147 $visit_category_id = $_POST['visit_category_id'];
1149 if (is_numeric($document_id)) {
1150 $messages = '';
1151 $d = new Document( $document_id );
1152 $file_name = $d->get_url_file();
1153 if (!is_numeric($encounter_id)) {
1154 $encounter_id = 0;
1157 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1158 if ($encounter_check) {
1159 $provider_id = $_SESSION['authUserID'] ;
1161 // Get the logged in user's facility
1162 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1163 $username = $facilityRow['username'];
1164 $facility = $facilityRow['facility'];
1165 $facility_id = $facilityRow['facility_id'];
1166 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1167 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1168 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1170 $conn = $GLOBALS['adodb']['db'];
1171 $encounter = $conn->GenID("sequences");
1172 $query = "INSERT INTO form_encounter SET
1173 date = ?,
1174 reason = ?,
1175 facility = ?,
1176 sensitivity = 'normal',
1177 pc_catid = ?,
1178 facility_id = ?,
1179 billing_facility = ?,
1180 provider_id = ?,
1181 pid = ?,
1182 encounter = ?";
1183 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1184 $formID = sqlInsert($query,$bindArray);
1185 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1186 $d->set_encounter_id($encounter);
1188 } else {
1189 $d->set_encounter_id($encounter_id);
1191 $d->set_encounter_check($encounter_check);
1192 $d->persist();
1194 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1197 $this->_state = false;
1198 $this->assign("messages", $messages);
1200 return $this->view_action($patient_id, $document_id);