Implemented the following functionality for MU2 - ยง170.314(a)(12) Image Results
[openemr.git] / controllers / C_Document.class.php
blob7b7d0ca3c598ba54403f409312bac7686faeeb9b
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");
16 class C_Document extends Controller {
18 var $template_mod;
19 var $documents;
20 var $document_categories;
21 var $tree;
22 var $_config;
23 var $manual_set_owner=false; // allows manual setting of a document owner/service
25 function C_Document($template_mod = "general") {
26 parent::Controller();
27 $this->documents = array();
28 $this->template_mod = $template_mod;
29 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
30 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
32 //get global config options for this namespace
33 $this->_config = $GLOBALS['oer_config']['documents'];
35 $this->_args = array("patient_id" => $_GET['patient_id']);
37 $this->assign("STYLE", $GLOBALS['style']);
38 $t = new CategoryTree(1);
39 //print_r($t->tree);
40 $this->tree = $t;
43 function upload_action($patient_id,$category_id) {
44 $category_name = $this->tree->get_node_name($category_id);
45 $this->assign("category_id", $category_id);
46 $this->assign("category_name", $category_name);
47 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
48 $this->assign("patient_id", $patient_id);
50 // Added by Rod to support document template download from general_upload.html.
51 // Cloned from similar stuff in manage_document_templates.php.
52 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
53 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
54 $dh = opendir($templatedir);
55 if ($dh) {
56 $templateslist = array();
57 while (false !== ($sfname = readdir($dh))) {
58 if (substr($sfname, 0, 1) == '.') continue;
59 $templateslist[$sfname] = $sfname;
61 closedir($dh);
62 ksort($templateslist);
63 foreach ($templateslist as $sfname) {
64 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
65 "'>" . htmlspecialchars($sfname) . "</option>";
68 $this->assign("TEMPLATES_LIST", $templates_options);
70 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
71 $this->assign("activity", $activity);
72 return $this->list_action($patient_id);
75 //Upload multiple files on single click
76 function upload_action_process() {
78 // Collect a manually set owner if this has been set
79 // Used when want to manually assign the owning user/service such as the Direct mechanism
80 $non_HTTP_owner=false;
81 if ($this->manual_set_owner) {
82 $non_HTTP_owner=$this->manual_set_owner;
85 $couchDB = false;
86 $harddisk = false;
87 if($GLOBALS['document_storage_method']==0){
88 $harddisk = true;
90 if($GLOBALS['document_storage_method']==1){
91 $couchDB = true;
94 if ($_POST['process'] != "true")
95 return;
97 $doDecryption = false;
98 $encrypted = $_POST['encrypted'];
99 $passphrase = $_POST['passphrase'];
100 if ( !$GLOBALS['hide_document_encryption'] &&
101 $encrypted && $passphrase ) {
102 $doDecryption = true;
105 if (is_numeric($_POST['category_id'])) {
106 $category_id = $_POST['category_id'];
109 $patient_id = 0;
110 if (isset($_GET['patient_id']) && !$couchDB) {
111 $patient_id = $_GET['patient_id'];
113 else if (is_numeric($_POST['patient_id'])) {
114 $patient_id = $_POST['patient_id'];
117 $sentUploadStatus = array();
118 if( count($_FILES['file']['name']) > 0){
119 $upl_inc = 0;
120 foreach($_FILES['file']['name'] as $key => $value){
121 $fname = $value;
122 $err = "";
123 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
124 $fname = $value;
125 if (empty($fname)) {
126 $fname = htmlentities("<empty>");
128 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
129 if ($_FILES['file']['size'][$key] == 0) {
130 $error .= "The system does not permit uploading files of with size 0.\n";
132 }else{
133 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
134 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
135 fclose($tmpfile);
136 if ($doDecryption) {
137 $filetext = $this->decrypt($filetext, $passphrase);
139 if ( $_POST['destination'] != '' ) {
140 $fname = $_POST['destination'];
142 $d = new Document();
143 $rc = $d->createDocument($patient_id, $category_id, $fname,
144 $_FILES['file']['type'][$key], $filetext,
145 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
146 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
147 $non_HTTP_owner);
148 if ($rc) {
149 $error .= $rc . "\n";
151 else {
152 $this->assign("upload_success", "true");
154 $sentUploadStatus[] = $d;
155 $this->assign("file", $sentUploadStatus);
158 // Option to run a custom plugin for each file upload.
159 // This was initially created to delete the original source file in a custom setting.
160 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
161 if (file_exists($upload_plugin)) {
162 include_once($upload_plugin);
164 $upload_plugin_pp = 'documentUploadPostProcess';
165 if (function_exists($upload_plugin_pp)) {
166 $tmp = call_user_func($upload_plugin_pp, $value, $d);
167 if ($tmp) {
168 $error = $tmp;
171 // Following is just an example of code in such a plugin file.
172 /*****************************************************
173 function documentUploadPostProcess($filename, &$d) {
174 $userid = $_SESSION['authUserID'];
175 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
176 $owner = strtolower($row['username']);
177 $dn = '1_' . ucfirst($owner);
178 $filepath = "/shared_network_directory/$dn/$filename";
179 if (@unlink($filepath)) return '';
180 return "Failed to delete '$filepath'.";
182 *****************************************************/
187 $this->assign("error", nl2br($error));
188 //$this->_state = false;
189 $_POST['process'] = "";
190 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
193 function note_action_process($patient_id) {
195 if ($_POST['process'] != "true")
196 return;
198 $n = new Note();
199 $n->set_owner($_SESSION['authUserID']);
200 parent::populate_object($n);
201 $n->persist();
203 $this->_state = false;
204 $_POST['process'] = "";
205 return $this->view_action($patient_id,$n->get_foreign_id());
208 function default_action() {
209 return $this->list_action();
212 function view_action($patient_id="",$doc_id) {
213 // Added by Rod to support document delete:
214 global $gacl_object, $phpgacl_location;
215 global $ISSUE_TYPES;
217 require_once(dirname(__FILE__) . "/../library/acl.inc");
218 require_once(dirname(__FILE__) . "/../library/lists.inc");
220 $d = new Document($doc_id);
221 $n = new Note();
223 $notes = $n->notes_factory($doc_id);
225 $this->assign("file", $d);
226 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
227 $this->assign("NOTE_ACTION",$this->_link("note"));
228 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
229 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
231 // Added by Rod to support document delete:
232 $delete_string = '';
233 if (acl_check('admin', 'super')) {
234 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
235 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
237 $this->assign("delete_string", $delete_string);
238 $this->assign("REFRESH_ACTION",$this->_link("list"));
240 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
241 "document_id=" . $d->get_id() . "&process=true");
243 // Added by Rod to support document date update:
244 $this->assign("DOCDATE", $d->get_docdate());
245 $this->assign("UPDATE_ACTION",$this->_link("update") .
246 "document_id=" . $d->get_id() . "&process=true");
248 // Added by Rod to support document issue update:
249 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
250 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
251 "pid = ? " . // AND enddate IS NULL " .
252 "ORDER BY type, begdate", array($patient_id) );
253 while ($irow = sqlFetchArray($ires)) {
254 $desc = $irow['type'];
255 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
256 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
257 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
258 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
260 $this->assign("ISSUES_LIST", $issues_options);
262 // For tagging to encounter
263 // Populate the dropdown with patient's encounter list
264 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
265 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
266 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
267 "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));
268 if ( sqlNumRows($result_docs) > 0)
269 while($row_result_docs = sqlFetchArray($result_docs)) {
270 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
271 $encOptions .= "<option value='" . $row_result_docs['encounter'] . "' $sel_enc>". oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date']))) . "-" . $row_result_docs['pc_catname']."</option>";
273 $this->assign("ENC_LIST", $encOptions);
275 //Populate the dropdown with category list
276 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
277 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
278 while ($crow = sqlFetchArray($cres)) {
279 $catid = $crow['pc_catid'];
280 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
281 $visit_category_list .="<option value='$catid'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
283 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
285 $this->assign("notes",$notes);
287 $this->_last_node = null;
289 $menu = new HTML_TreeMenu();
291 //pass an empty array because we don't want the documents for each category showing up in this list box
292 $rnode = $this->_array_recurse($this->tree->tree,array());
293 $menu->addItem($rnode);
294 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
296 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
298 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
299 $this->assign("activity", $activity);
301 return $this->list_action($patient_id);
304 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
306 $td = mcrypt_module_open( $cypher, '', $mode, '');
307 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
308 mcrypt_generic_init( $td, $key, $iv );
309 $crypttext = mcrypt_generic( $td, $plaintext );
310 mcrypt_generic_deinit( $td );
311 return $iv.$crypttext;
314 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
316 $plaintext = '';
317 $td = mcrypt_module_open( $cypher, '', $mode, '' );
318 $ivsize = mcrypt_enc_get_iv_size( $td) ;
319 $iv = substr( $crypttext, 0, $ivsize );
320 $crypttext = substr( $crypttext, $ivsize );
321 if( $iv )
323 mcrypt_generic_init( $td, $key, $iv );
324 $plaintext = mdecrypt_generic( $td, $crypttext );
326 return $plaintext;
330 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
332 $encrypted = $_POST['encrypted'];
333 $passphrase = $_POST['passphrase'];
334 $doEncryption = false;
335 if ( !$GLOBALS['hide_document_encryption'] &&
336 $encrypted == "true" &&
337 $passphrase ) {
338 $doEncryption = true;
341 //controller function ruins booleans, so need to manually re-convert to booleans
342 if ($as_file == "true") {
343 $as_file=true;
345 else if ($as_file == "false") {
346 $as_file=false;
348 if ($original_file == "true") {
349 $original_file=true;
351 else if ($original_file == "false") {
352 $original_file=false;
355 $d = new Document($document_id);
356 $url = $d->get_url();
357 $storagemethod = $d->get_storagemethod();
358 $couch_docid = $d->get_couch_docid();
359 $couch_revid = $d->get_couch_revid();
361 if($couch_docid && $couch_revid && $original_file){
362 $couch = new CouchDB();
363 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
364 $resp = $couch->retrieve_doc($data);
365 $content = $resp->data;
366 if($content=='' && $GLOBALS['couchdb_log']==1){
367 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
368 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
369 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
370 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
371 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
372 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
373 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
374 die(xl("File retrieval from CouchDB failed"));
376 header('Content-Description: File Transfer');
377 header('Content-Transfer-Encoding: binary');
378 header('Expires: 0');
379 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
380 header('Pragma: public');
381 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
382 $fh = fopen($tmpcouchpath,"w");
383 fwrite($fh,base64_decode($content));
384 fclose($fh);
385 $f = fopen($tmpcouchpath,"r");
386 if ( $doEncryption ) {
387 $filetext = fread( $f, filesize($tmpcouchpath) );
388 $ciphertext = $this->encrypt( $filetext, $passphrase );
389 $tmpfilepath = $GLOBALS['temporary_files_dir'];
390 $tmpfilename = "/encrypted_".$d->get_url_file();
391 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
392 fwrite( $tmpfile, $ciphertext );
393 fclose( $tmpfile );
394 header('Content-Disposition: attachment; filename='.$tmpfilename );
395 header("Content-Type: application/octet-stream" );
396 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
397 ob_clean();
398 flush();
399 readfile( $tmpfilepath.$tmpfilename );
400 unlink( $tmpfilepath.$tmpfilename );
401 } else {
402 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
403 header("Content-Type: " . $d->get_mimetype());
404 header("Content-Length: " . filesize($tmpcouchpath));
405 fpassthru($f);
407 fclose($f);
408 if($content!='')
409 unlink($tmpcouchpath);
410 exit;//exits only if file download from CouchDB is successfull.
412 //strip url of protocol handler
413 $url = preg_replace("|^(.*)://|","",$url);
415 //change full path to current webroot. this is for documents that may have
416 //been moved from a different filesystem and the full path in the database
417 //is not current. this is also for documents that may of been moved to
418 //different patients. Note that the path_depth is used to see how far down
419 //the path to go. For example, originally the path_depth was always 1, which
420 //only allowed things like documents/1/<file>, but now can have more structured
421 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
422 // etc.
423 // NOTE that $from_filename and basename($url) are the same thing
424 $from_all = explode("/",$url);
425 $from_filename = array_pop($from_all);
426 $from_pathname_array = array();
427 for ($i=0;$i<$d->get_path_depth();$i++) {
428 $from_pathname_array[] = array_pop($from_all);
430 $from_pathname_array = array_reverse($from_pathname_array);
431 $from_pathname = implode("/",$from_pathname_array);
432 if($couch_docid && $couch_revid){
433 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
434 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
437 else{
438 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
441 if (file_exists($temp_url)) {
442 $url = $temp_url;
446 if (!file_exists($url)) {
447 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;
450 else {
451 if ($original_file) {
452 //normal case when serving the file referenced in database
453 header('Content-Description: File Transfer');
454 header('Content-Transfer-Encoding: binary');
455 header('Expires: 0');
456 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
457 header('Pragma: public');
458 $f = fopen($url,"r");
459 if ( $doEncryption ) {
460 $filetext = fread( $f, filesize($url) );
461 $ciphertext = $this->encrypt( $filetext, $passphrase );
462 $tmpfilepath = $GLOBALS['temporary_files_dir'];
463 $tmpfilename = "/encrypted_".$d->get_url_file();
464 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
465 fwrite( $tmpfile, $ciphertext );
466 fclose( $tmpfile );
467 header('Content-Disposition: attachment; filename='.$tmpfilename );
468 header("Content-Type: application/octet-stream" );
469 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
470 ob_clean();
471 flush();
472 readfile( $tmpfilepath.$tmpfilename );
473 unlink( $tmpfilepath.$tmpfilename );
474 } else {
475 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
476 header("Content-Type: " . $d->get_mimetype());
477 header("Content-Length: " . filesize($url));
478 fpassthru($f);
480 exit;
482 else {
483 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
484 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
485 if($couch_docid && $couch_revid){
486 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
488 else{
489 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
491 header("Pragma: public");
492 header("Expires: 0");
493 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
494 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
495 header("Content-Type: image/jpeg");
496 header("Content-Length: " . filesize($url));
497 $f = fopen($url,"r");
498 fpassthru($f);
499 if($couch_docid && $couch_revid){
500 fclose($f);
501 unlink($url);
502 $url=str_replace("_converted.jpg",'.pdf',$url);
503 unlink($url);
505 exit;
510 function queue_action($patient_id="") {
511 $messages = $this->_tpl_vars['messages'];
512 $queue_files = array();
514 //see if the repository exists and it is a directory else error
515 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
516 $dir = opendir($this->_config['repository']);
517 //read each entry in the directory
518 while (($file = readdir($dir)) !== false) {
519 //concat the filename and path
520 $file = $this->_config['repository'] .$file;
521 $file_info = array();
522 //if the filename is a file get its info and put into a tmp array
523 if (is_file($file) && strpos(basename($file),".") !== 0) {
524 $file_info['filename'] = basename($file);
525 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
526 $d = Document::document_factory_url("file://" . $file);
527 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
528 $file_info['patient_id'] = $patient_match[1];
529 $file_info['document_id'] = $d->get_id();
530 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
532 //merge the tmp array into the larger array
533 $queue_files[] = $file_info;
536 closedir($dir);
538 else {
539 $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";
543 $this->assign("queue_files",$queue_files);
544 $this->_last_node = null;
546 $menu = new HTML_TreeMenu();
548 //pass an empty array because we don't want the documents for each category showing up in this list box
549 $rnode = $this->_array_recurse($this->tree->tree,array());
550 $menu->addItem($rnode);
551 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
553 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
555 $this->assign("messages",nl2br($messages));
556 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
559 function queue_action_process() {
560 if ($_POST['process'] != "true")
561 return;
563 $messages = $this->_tpl_vars['messages'];
565 //build a category tree so we can have a list of category ids that are valid
566 $ct = new CategoryTree(1);
567 $categories = $ct->_id_name;
569 //see if there were and posted files and assign them
570 $files = null;
571 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
573 //loop through posted files
574 foreach($files as $doc_id=> $file) {
575 //only operate on files checked as active
576 if (!$file['active']) continue;
578 //run basic validation checks
579 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
580 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
581 continue;
584 //validate that the pod exists
585 $d = new Document($doc_id);
586 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
587 $result = $d->_db->Execute($sql);
589 if (!$result || $result->EOF) {
590 //patient id does not exist
591 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
592 continue;
595 //validate that the category id exists
596 if (!isset($categories[$file['category_id']])) {
597 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
598 continue;
601 //now do the work of moving the file
602 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
604 //see if the patient dir exists in the repository and create if not
605 if (!file_exists($new_path)) {
606 if (!mkdir($new_path,0700)) {
607 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
608 continue;
612 //fname is the name of the file after it is moved
613 $fname = $file['name'];
615 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
616 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
617 if ($patient_match[1] == $file['patient_id']) {
618 $fname = preg_replace("/^([0-9]+)_/","",$fname);
621 //filenames should not have funny chars
622 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
624 //see if there is an existing file with the same name and rename as necessary
625 if (file_exists($new_path.$file['name'])) {
626 $messages .= "File with same name already exists at location: " . $new_path . "\n";
627 $fname = basename($this->_rename_file($new_path.$file['name']));
628 $messages .= "Current file name was changed to " . $fname ."\n";
631 //now move the file
632 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
633 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
634 $d->url = "file://" .$new_path.$fname;
635 $d->set_foreign_id($file['patient_id']);
636 $d->set_mimetype($mimetype);
637 $d->persist();
638 $d->populate();
640 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
641 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
642 $d->_db->Execute($sql);
645 else {
646 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
649 $this->assign("messages",$messages);
650 $_POST['process'] = "";
653 function move_action_process($patient_id="",$document_id) {
654 if ($_POST['process'] != "true")
655 return;
657 $new_category_id = $_POST['new_category_id'];
658 $new_patient_id = $_POST['new_patient_id'];
660 //move to new category
661 if (is_numeric($new_category_id) && is_numeric($document_id)) {
662 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
663 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
664 //echo $sql;
665 $this->tree->_db->Execute($sql);
668 //move to new patient
669 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
670 $d = new Document($document_id);
671 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
672 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
673 $result = $d->_db->Execute($sql);
675 if (!$result || $result->EOF) {
676 //patient id does not exist
677 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
679 else {
680 $couchsavefailed = !$d->change_patient($new_patient_id);
682 $this->_state = false;
683 if(!$couchsavefailed){
685 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
687 else{
689 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
691 $this->assign("messages",$messages);
692 return $this->list_action($patient_id);
695 //in this case return the document to the queue instead of moving it
696 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
697 $d = new Document($document_id);
698 $new_path = $this->_config['repository'];
699 $fname = $d->get_url_file();
701 //see if there is an existing file with the same name and rename as necessary
702 if (file_exists($new_path.$d->get_url_file())) {
703 $messages .= "File with same name already exists in the queue.\n";
704 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
705 $messages .= "Current file name was changed to " . $fname ."\n";
708 //now move the file
709 if (rename($d->get_url_filepath(),$new_path.$fname)) {
710 $d->url = "file://" .$new_path.$fname;
711 $d->set_foreign_id("");
712 $d->persist();
713 $d->persist();
714 $d->populate();
716 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
717 $d->_db->Execute($sql);
718 $messages .= "Document returned to queue successfully.\n";
721 else {
722 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
725 $this->_state = false;
726 $this->assign("messages",$messages);
727 return $this->list_action($patient_id);
730 $this->_state = false;
731 $this->assign("messages",$messages);
732 return $this->view_action($patient_id,$document_id);
735 function validate_action_process($patient_id="", $document_id) {
737 $d = new Document($document_id);
738 if($d->couch_docid && $d->couch_revid){
739 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
740 $url = $file_path.$d->get_url();
741 $couch = new CouchDB();
742 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
743 $resp = $couch->retrieve_doc($data);
744 $content = $resp->data;
745 //--------Temporarily writing the file for calculating the hash--------//
746 //-----------Will be removed after calculating the hash value----------//
747 $temp_file = fopen($url,"w");
748 fwrite($temp_file,base64_decode($content));
749 fclose($temp_file);
751 else{
752 $url = $d->get_url();
754 //strip url of protocol handler
755 $url = preg_replace("|^(.*)://|","",$url);
757 //change full path to current webroot. this is for documents that may have
758 //been moved from a different filesystem and the full path in the database
759 //is not current. this is also for documents that may of been moved to
760 //different patients. Note that the path_depth is used to see how far down
761 //the path to go. For example, originally the path_depth was always 1, which
762 //only allowed things like documents/1/<file>, but now can have more structured
763 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
764 // etc.
765 // NOTE that $from_filename and basename($url) are the same thing
766 $from_all = explode("/",$url);
767 $from_filename = array_pop($from_all);
768 $from_pathname_array = array();
769 for ($i=0;$i<$d->get_path_depth();$i++) {
770 $from_pathname_array[] = array_pop($from_all);
772 $from_pathname_array = array_reverse($from_pathname_array);
773 $from_pathname = implode("/",$from_pathname_array);
774 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
775 if (file_exists($temp_url)) {
776 $url = $temp_url;
779 if ($_POST['process'] != "true") {
780 die("process is '" . $_POST['process'] . "', expected 'true'");
781 return;
784 $d = new Document( $document_id );
785 $current_hash = sha1_file( $url );
786 $messages = xl('Current Hash').": ".$current_hash."<br>";
787 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
788 if ( $d->get_hash() == '' ) {
789 $d->hash = $current_hash;
790 $d->persist();
791 $d->populate();
792 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
793 } else if ( $current_hash != $d->get_hash() ) {
794 $messages .= xl('Hash does not match. Data integrity has been compromised.');
795 } else {
796 $messages .= xl('Document passed integrity check.');
798 $this->_state = false;
799 $this->assign("messages", $messages);
800 if($d->couch_docid && $d->couch_revid){
801 //Removing the temporary file which is used to create the hash
802 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
804 return $this->view_action($patient_id, $document_id);
807 // Added by Rod for metadata update.
809 function update_action_process($patient_id="", $document_id) {
811 if ($_POST['process'] != "true") {
812 die("process is '" . $_POST['process'] . "', expected 'true'");
813 return;
816 $docdate = $_POST['docdate'];
817 $docname = $_POST['docname'];
818 $issue_id = $_POST['issue_id'];
820 if (is_numeric($document_id)) {
821 $messages = '';
822 $d = new Document( $document_id );
823 $file_name = $d->get_url_file();
824 if ( $docname != '' &&
825 $docname != $file_name ) {
826 $path = $d->get_url_filepath();
827 $path = str_replace( $file_name, "", $path );
828 $new_url = $this->_rename_file( $path.$docname );
829 if ( rename( $d->get_url(), $new_url ) ) {
830 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
831 $url = preg_replace("|^(.*)://|","",$d->get_url());
832 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
833 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
834 if ( file_exists( $url ) ) {
835 unlink( $url );
837 $d->url = $new_url;
838 $d->persist();
839 $d->populate();
840 $messages .= xl('Document successfully renamed.')."<br>";
841 } else {
842 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
846 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
847 $docdate = "'$docdate'";
848 } else {
849 $docdate = "NULL";
851 if (!is_numeric($issue_id)) {
852 $issue_id = 0;
854 $couch_docid = $d->get_couch_docid();
855 $couch_revid = $d->get_couch_revid();
856 if($couch_docid && $couch_revid ){
857 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
858 "list_id = '$issue_id' " .
859 "WHERE id = '$document_id'";
860 $this->tree->_db->Execute($sql);
863 else{
864 $sql = "UPDATE documents SET docdate = $docdate, " .
865 "list_id = '$issue_id' " .
866 "WHERE id = '$document_id'";
867 $this->tree->_db->Execute($sql);
869 $messages .= xl('Document date and issue updated successfully') . "<br>";
872 $this->_state = false;
873 $this->assign("messages", $messages);
874 return $this->view_action($patient_id, $document_id);
877 function list_action($patient_id = "") {
878 $this->_last_node = null;
879 $categories_list = $this->tree->_get_categories_array($patient_id);
880 //print_r($categories_list);
882 $menu = new HTML_TreeMenu();
883 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
884 $menu->addItem($rnode);
885 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
886 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
888 $this->assign("tree_html",$treeMenu->toHTML());
890 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
894 * This is a recursive function to rename a file to something that doesn't already exist.
895 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
896 * to ensure documents opened correctly by external browser viewers. If the counter is at the
897 * end of the file, then will use it (to continue to work with older files), however all new
898 * counters will be placed within filenames.
900 function _rename_file($fname) {
901 $file = basename($fname);
902 $fparts = split("\.",$fname);
903 $path = dirname($fname);
904 if (count($fparts) > 1) {
905 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
906 //increment the counter in filename
907 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
908 $fname = join(".",$fparts);
910 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
911 //increment counter at end of filename (so compatible with previous openemr version files
912 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
913 $fname = join(".",$fparts);
915 elseif (is_numeric($fparts[count($fparts) -1])) {
916 //leave date at end and place counter in filename
917 array_splice($fparts, -1, 0, "1");
918 $fname = join(".",$fparts);
920 else {
921 //add the counter to filename
922 array_splice($fparts, -1, 0, "1");
923 $fname = join(".",$fparts);
926 else { // (count($fparts) == 1)
927 //place counter at end of filename
928 array_push($fparts,"1");
929 $fname = join(".",$fparts);
932 if (file_exists($fname)) {
933 return $this->_rename_file($fname);
935 else {
936 return($fname);
940 function &_array_recurse($array,$categories = array()) {
941 if (!is_array($array)) {
942 $array = array();
944 $node = &$this->_last_node;
945 $current_node = &$node;
946 $expandedIcon = 'folder-expanded.gif';
947 foreach($array as $id => $ar) {
948 $icon = 'folder.gif';
949 if (is_array($ar) || !empty($id)) {
950 if ($node == null) {
951 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
952 $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));
953 $this->_last_node = &$rnode;
954 $node = &$rnode;
955 $current_node = &$rnode;
957 else {
958 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
959 $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)));
960 $current_node = &$this->_last_node;
963 $this->_array_recurse($ar,$categories);
965 else {
966 if ($id === 0 && !empty($ar)) {
967 $info = $this->tree->get_node_info($id);
968 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
969 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
971 else {
972 //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
973 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
974 if ($id !== 0 && is_object($node)) {
975 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
976 $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)));
982 // If there are documents in this document category, then add their
983 // attributes to the current node.
984 $icon = "file3.png";
985 if (is_array($categories[$id])) {
986 foreach ($categories[$id] as $doc) {
987 if($this->tree->get_node_name($id) == "CCR"){
988 $current_node->addItem(new HTML_TreeNode(array(
989 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
990 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
991 'icon' => $icon,
992 'expandedIcon' => $expandedIcon,
993 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
994 )));
995 }elseif($this->tree->get_node_name($id) == "CCD"){
996 $current_node->addItem(new HTML_TreeNode(array(
997 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
998 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
999 'icon' => $icon,
1000 'expandedIcon' => $expandedIcon,
1001 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1002 )));
1003 }else{
1004 $current_node->addItem(new HTML_TreeNode(array(
1005 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1006 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1007 'icon' => $icon,
1008 'expandedIcon' => $expandedIcon
1009 )));
1015 return $node;
1018 //function for logging the errors in writing file to CouchDB/Hard Disk
1019 function document_upload_download_log($patientid,$content){
1020 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1021 $log_file = 'log.txt';
1022 if(!is_dir($log_path))
1023 mkdir($log_path,0777,true);
1024 $LOG = fopen($log_path.$log_file,'a');
1025 fwrite($LOG,$content);
1026 fclose($LOG);
1029 //place to hold optional code
1030 //$first_node = array_keys($t->tree);
1031 //$first_node = $first_node[0];
1032 //$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')"));
1034 //$this->_last_node = &$node1;
1036 // Function to tag a document to an encounter.
1037 function tag_action_process($patient_id="", $document_id) {
1038 if ($_POST['process'] != "true") {
1039 die("process is '" . $_POST['process'] . "', expected 'true'");
1040 return;
1043 // Create Encounter and Tag it.
1044 $event_date = date('Y-m-d H:i:s');
1045 $encounter_id = $_POST['encounter_id'];
1046 $encounter_check = $_POST['encounter_check'];
1047 $visit_category_id = $_POST['visit_category_id'];
1049 if (is_numeric($document_id)) {
1050 $messages = '';
1051 $d = new Document( $document_id );
1052 $file_name = $d->get_url_file();
1053 if (!is_numeric($encounter_id)) {
1054 $encounter_id = 0;
1057 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1058 if ($encounter_check) {
1059 $provider_id = $_SESSION['authUserID'] ;
1061 // Get the logged in user's facility
1062 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = '" . $provider_id . "'");
1063 $username = $facilityRow['username'];
1064 $facility = $facilityRow['facility'];
1065 $facility_id = $facilityRow['facility_id'];
1066 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1067 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1068 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1070 $conn = $GLOBALS['adodb']['db'];
1071 $encounter = $conn->GenID("sequences");
1072 $query = "INSERT INTO form_encounter SET
1073 date = ?,
1074 reason = ?,
1075 facility = ?,
1076 sensitivity = 'normal',
1077 pc_catid = ?,
1078 facility_id = ?,
1079 billing_facility = ?,
1080 provider_id = ?,
1081 pid = ?,
1082 encounter = ?";
1083 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1084 $formID = sqlInsert($query,$bindArray);
1085 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1086 $d->set_encounter_id($encounter);
1088 } else {
1089 $d->set_encounter_id($encounter_id);
1091 $d->set_encounter_check($encounter_check);
1092 $d->persist();
1094 $messages .= xl('Document tagged to Encounter successfully') . "<br>";
1097 $this->_state = false;
1098 $this->assign("messages", $messages);
1100 return $this->view_action($patient_id, $document_id);