Added support for documents embedded in HL7 OBX results, and some other e-labs improv...
[openemr.git] / controllers / C_Document.class.php
blobe9801b3f744edf463b130958dc8c061e08c0e868
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");
14 class C_Document extends Controller {
16 var $template_mod;
17 var $documents;
18 var $document_categories;
19 var $tree;
20 var $_config;
21 var $manual_set_owner=false; // allows manual setting of a document owner/service
23 function C_Document($template_mod = "general") {
24 parent::Controller();
25 $this->documents = array();
26 $this->template_mod = $template_mod;
27 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
28 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
30 //get global config options for this namespace
31 $this->_config = $GLOBALS['oer_config']['documents'];
33 $this->_args = array("patient_id" => $_GET['patient_id']);
35 $this->assign("STYLE", $GLOBALS['style']);
36 $t = new CategoryTree(1);
37 //print_r($t->tree);
38 $this->tree = $t;
41 function upload_action($patient_id,$category_id) {
42 $category_name = $this->tree->get_node_name($category_id);
43 $this->assign("category_id", $category_id);
44 $this->assign("category_name", $category_name);
45 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
46 $this->assign("patient_id", $patient_id);
47 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
48 $this->assign("activity", $activity);
49 return $this->list_action($patient_id);
52 //Upload multiple files on single click
53 function upload_action_process() {
55 // Collect a manually set owner if this has been set
56 // Used when want to manually assign the owning user/service such as the Direct mechanism
57 $non_HTTP_owner=false;
58 if ($this->manual_set_owner) {
59 $non_HTTP_owner=$this->manual_set_owner;
62 $couchDB = false;
63 $harddisk = false;
64 if($GLOBALS['document_storage_method']==0){
65 $harddisk = true;
67 if($GLOBALS['document_storage_method']==1){
68 $couchDB = true;
71 if ($_POST['process'] != "true")
72 return;
74 $doDecryption = false;
75 $encrypted = $_POST['encrypted'];
76 $passphrase = $_POST['passphrase'];
77 if ( !$GLOBALS['hide_document_encryption'] &&
78 $encrypted && $passphrase ) {
79 $doDecryption = true;
82 if (is_numeric($_POST['category_id'])) {
83 $category_id = $_POST['category_id'];
86 $patient_id = 0;
87 if (isset($_GET['patient_id']) && !$couchDB) {
88 $patient_id = $_GET['patient_id'];
90 else if (is_numeric($_POST['patient_id'])) {
91 $patient_id = $_POST['patient_id'];
94 $sentUploadStatus = array();
95 if( count($_FILES['file']['name']) > 0){
96 $upl_inc = 0;
97 foreach($_FILES['file']['name'] as $key => $value){
98 $fname = $value;
99 $err = "";
100 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
101 $fname = $value;
102 if (empty($fname)) {
103 $fname = htmlentities("<empty>");
105 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
106 if ($_FILES['file']['size'][$key] == 0) {
107 $error .= "The system does not permit uploading files of with size 0.\n";
109 }else{
110 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
111 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
112 fclose($tmpfile);
113 if ($doDecryption) {
114 $filetext = $this->decrypt($filetext, $passphrase);
116 if ( $_POST['destination'] != '' ) {
117 $fname = $_POST['destination'];
119 $d = new Document();
120 $rc = $d->createDocument($patient_id, $category_id, $fname,
121 $_FILES['file']['type'][$key], $filetext,
122 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
123 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
124 $non_HTTP_owner);
125 if ($rc) {
126 $error .= $rc . "\n";
128 else {
129 $this->assign("upload_success", "true");
131 $sentUploadStatus[] = $d;
132 $this->assign("file", $sentUploadStatus);
137 $this->assign("error", nl2br($error));
138 //$this->_state = false;
139 $_POST['process'] = "";
140 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
143 function note_action_process($patient_id) {
145 if ($_POST['process'] != "true")
146 return;
148 $n = new Note();
149 $n->set_owner($_SESSION['authUserID']);
150 parent::populate_object($n);
151 $n->persist();
153 $this->_state = false;
154 $_POST['process'] = "";
155 return $this->view_action($patient_id,$n->get_foreign_id());
158 function default_action() {
159 return $this->list_action();
162 function view_action($patient_id="",$doc_id) {
163 // Added by Rod to support document delete:
164 global $gacl_object, $phpgacl_location;
165 global $ISSUE_TYPES;
167 require_once(dirname(__FILE__) . "/../library/acl.inc");
168 require_once(dirname(__FILE__) . "/../library/lists.inc");
170 $d = new Document($doc_id);
171 $n = new Note();
173 $notes = $n->notes_factory($doc_id);
175 $this->assign("file", $d);
176 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
177 $this->assign("NOTE_ACTION",$this->_link("note"));
178 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
179 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
181 // Added by Rod to support document delete:
182 $delete_string = '';
183 if (acl_check('admin', 'super')) {
184 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
185 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
187 $this->assign("delete_string", $delete_string);
188 $this->assign("REFRESH_ACTION",$this->_link("list"));
190 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
191 "document_id=" . $d->get_id() . "&process=true");
193 // Added by Rod to support document date update:
194 $this->assign("DOCDATE", $d->get_docdate());
195 $this->assign("UPDATE_ACTION",$this->_link("update") .
196 "document_id=" . $d->get_id() . "&process=true");
198 // Added by Rod to support document issue update:
199 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
200 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
201 "pid = $patient_id " . // AND enddate IS NULL " .
202 "ORDER BY type, begdate");
203 while ($irow = sqlFetchArray($ires)) {
204 $desc = $irow['type'];
205 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
206 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
207 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
208 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
210 $this->assign("ISSUES_LIST", $issues_options);
212 $this->assign("notes",$notes);
214 $this->_last_node = null;
216 $menu = new HTML_TreeMenu();
218 //pass an empty array because we don't want the documents for each category showing up in this list box
219 $rnode = $this->_array_recurse($this->tree->tree,array());
220 $menu->addItem($rnode);
221 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
223 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
225 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
226 $this->assign("activity", $activity);
228 return $this->list_action($patient_id);
231 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
233 $td = mcrypt_module_open( $cypher, '', $mode, '');
234 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
235 mcrypt_generic_init( $td, $key, $iv );
236 $crypttext = mcrypt_generic( $td, $plaintext );
237 mcrypt_generic_deinit( $td );
238 return $iv.$crypttext;
241 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
243 $plaintext = '';
244 $td = mcrypt_module_open( $cypher, '', $mode, '' );
245 $ivsize = mcrypt_enc_get_iv_size( $td) ;
246 $iv = substr( $crypttext, 0, $ivsize );
247 $crypttext = substr( $crypttext, $ivsize );
248 if( $iv )
250 mcrypt_generic_init( $td, $key, $iv );
251 $plaintext = mdecrypt_generic( $td, $crypttext );
253 return $plaintext;
257 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
259 $encrypted = $_POST['encrypted'];
260 $passphrase = $_POST['passphrase'];
261 $doEncryption = false;
262 if ( !$GLOBALS['hide_document_encryption'] &&
263 $encrypted == "true" &&
264 $passphrase ) {
265 $doEncryption = true;
268 //controller function ruins booleans, so need to manually re-convert to booleans
269 if ($as_file == "true") {
270 $as_file=true;
272 else if ($as_file == "false") {
273 $as_file=false;
275 if ($original_file == "true") {
276 $original_file=true;
278 else if ($original_file == "false") {
279 $original_file=false;
282 $d = new Document($document_id);
283 $url = $d->get_url();
284 $storagemethod = $d->get_storagemethod();
285 $couch_docid = $d->get_couch_docid();
286 $couch_revid = $d->get_couch_revid();
288 if($couch_docid && $couch_revid && $original_file){
289 $couch = new CouchDB();
290 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
291 $resp = $couch->retrieve_doc($data);
292 $content = $resp->data;
293 if($content=='' && $GLOBALS['couchdb_log']==1){
294 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
295 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
296 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
297 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
298 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
299 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
300 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
301 die(xl("File retrieval from CouchDB failed"));
303 header('Content-Description: File Transfer');
304 header('Content-Transfer-Encoding: binary');
305 header('Expires: 0');
306 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
307 header('Pragma: public');
308 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
309 $fh = fopen($tmpcouchpath,"w");
310 fwrite($fh,base64_decode($content));
311 fclose($fh);
312 $f = fopen($tmpcouchpath,"r");
313 if ( $doEncryption ) {
314 $filetext = fread( $f, filesize($tmpcouchpath) );
315 $ciphertext = $this->encrypt( $filetext, $passphrase );
316 $tmpfilepath = $GLOBALS['temporary_files_dir'];
317 $tmpfilename = "/encrypted_".$d->get_url_file();
318 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
319 fwrite( $tmpfile, $ciphertext );
320 fclose( $tmpfile );
321 header('Content-Disposition: attachment; filename='.$tmpfilename );
322 header("Content-Type: application/octet-stream" );
323 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
324 ob_clean();
325 flush();
326 readfile( $tmpfilepath.$tmpfilename );
327 unlink( $tmpfilepath.$tmpfilename );
328 } else {
329 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
330 header("Content-Type: " . $d->get_mimetype());
331 header("Content-Length: " . filesize($tmpcouchpath));
332 fpassthru($f);
334 fclose($f);
335 if($content!='')
336 unlink($tmpcouchpath);
337 exit;//exits only if file download from CouchDB is successfull.
339 //strip url of protocol handler
340 $url = preg_replace("|^(.*)://|","",$url);
342 //change full path to current webroot. this is for documents that may have
343 //been moved from a different filesystem and the full path in the database
344 //is not current. this is also for documents that may of been moved to
345 //different patients. Note that the path_depth is used to see how far down
346 //the path to go. For example, originally the path_depth was always 1, which
347 //only allowed things like documents/1/<file>, but now can have more structured
348 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
349 // etc.
350 // NOTE that $from_filename and basename($url) are the same thing
351 $from_all = explode("/",$url);
352 $from_filename = array_pop($from_all);
353 $from_pathname_array = array();
354 for ($i=0;$i<$d->get_path_depth();$i++) {
355 $from_pathname_array[] = array_pop($from_all);
357 $from_pathname_array = array_reverse($from_pathname_array);
358 $from_pathname = implode("/",$from_pathname_array);
359 if($couch_docid && $couch_revid){
360 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
361 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
364 else{
365 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
368 if (file_exists($temp_url)) {
369 $url = $temp_url;
373 if (!file_exists($url)) {
374 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;
377 else {
378 if ($original_file) {
379 //normal case when serving the file referenced in database
380 header('Content-Description: File Transfer');
381 header('Content-Transfer-Encoding: binary');
382 header('Expires: 0');
383 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
384 header('Pragma: public');
385 $f = fopen($url,"r");
386 if ( $doEncryption ) {
387 $filetext = fread( $f, filesize($url) );
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($url));
405 fpassthru($f);
407 exit;
409 else {
410 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
411 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
412 if($couch_docid && $couch_revid){
413 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
415 else{
416 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
418 header("Pragma: public");
419 header("Expires: 0");
420 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
421 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
422 header("Content-Type: image/jpeg");
423 header("Content-Length: " . filesize($url));
424 $f = fopen($url,"r");
425 fpassthru($f);
426 if($couch_docid && $couch_revid){
427 fclose($f);
428 unlink($url);
429 $url=str_replace("_converted.jpg",'.pdf',$url);
430 unlink($url);
432 exit;
437 function queue_action($patient_id="") {
438 $messages = $this->_tpl_vars['messages'];
439 $queue_files = array();
441 //see if the repository exists and it is a directory else error
442 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
443 $dir = opendir($this->_config['repository']);
444 //read each entry in the directory
445 while (($file = readdir($dir)) !== false) {
446 //concat the filename and path
447 $file = $this->_config['repository'] .$file;
448 $file_info = array();
449 //if the filename is a file get its info and put into a tmp array
450 if (is_file($file) && strpos(basename($file),".") !== 0) {
451 $file_info['filename'] = basename($file);
452 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
453 $d = Document::document_factory_url("file://" . $file);
454 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
455 $file_info['patient_id'] = $patient_match[1];
456 $file_info['document_id'] = $d->get_id();
457 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
459 //merge the tmp array into the larger array
460 $queue_files[] = $file_info;
463 closedir($dir);
465 else {
466 $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";
470 $this->assign("queue_files",$queue_files);
471 $this->_last_node = null;
473 $menu = new HTML_TreeMenu();
475 //pass an empty array because we don't want the documents for each category showing up in this list box
476 $rnode = $this->_array_recurse($this->tree->tree,array());
477 $menu->addItem($rnode);
478 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
480 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
482 $this->assign("messages",nl2br($messages));
483 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
486 function queue_action_process() {
487 if ($_POST['process'] != "true")
488 return;
490 $messages = $this->_tpl_vars['messages'];
492 //build a category tree so we can have a list of category ids that are valid
493 $ct = new CategoryTree(1);
494 $categories = $ct->_id_name;
496 //see if there were and posted files and assign them
497 $files = null;
498 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
500 //loop through posted files
501 foreach($files as $doc_id=> $file) {
502 //only operate on files checked as active
503 if (!$file['active']) continue;
505 //run basic validation checks
506 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
507 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
508 continue;
511 //validate that the pod exists
512 $d = new Document($doc_id);
513 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
514 $result = $d->_db->Execute($sql);
516 if (!$result || $result->EOF) {
517 //patient id does not exist
518 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
519 continue;
522 //validate that the category id exists
523 if (!isset($categories[$file['category_id']])) {
524 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
525 continue;
528 //now do the work of moving the file
529 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
531 //see if the patient dir exists in the repository and create if not
532 if (!file_exists($new_path)) {
533 if (!mkdir($new_path,0700)) {
534 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
535 continue;
539 //fname is the name of the file after it is moved
540 $fname = $file['name'];
542 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
543 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
544 if ($patient_match[1] == $file['patient_id']) {
545 $fname = preg_replace("/^([0-9]+)_/","",$fname);
548 //filenames should not have funny chars
549 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
551 //see if there is an existing file with the same name and rename as necessary
552 if (file_exists($new_path.$file['name'])) {
553 $messages .= "File with same name already exists at location: " . $new_path . "\n";
554 $fname = basename($this->_rename_file($new_path.$file['name']));
555 $messages .= "Current file name was changed to " . $fname ."\n";
558 //now move the file
559 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
560 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
561 $d->url = "file://" .$new_path.$fname;
562 $d->set_foreign_id($file['patient_id']);
563 $d->set_mimetype($mimetype);
564 $d->persist();
565 $d->populate();
567 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
568 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
569 $d->_db->Execute($sql);
572 else {
573 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
576 $this->assign("messages",$messages);
577 $_POST['process'] = "";
580 function move_action_process($patient_id="",$document_id) {
581 if ($_POST['process'] != "true")
582 return;
584 $new_category_id = $_POST['new_category_id'];
585 $new_patient_id = $_POST['new_patient_id'];
587 //move to new category
588 if (is_numeric($new_category_id) && is_numeric($document_id)) {
589 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
590 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
591 //echo $sql;
592 $this->tree->_db->Execute($sql);
595 //move to new patient
596 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
597 $d = new Document($document_id);
598 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
599 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
600 $result = $d->_db->Execute($sql);
602 if (!$result || $result->EOF) {
603 //patient id does not exist
604 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
606 else {
607 $couchsavefailed = !$d->change_patient($new_patient_id);
609 $this->_state = false;
610 if(!$couchsavefailed){
612 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
614 else{
616 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
618 $this->assign("messages",$messages);
619 return $this->list_action($patient_id);
622 //in this case return the document to the queue instead of moving it
623 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
624 $d = new Document($document_id);
625 $new_path = $this->_config['repository'];
626 $fname = $d->get_url_file();
628 //see if there is an existing file with the same name and rename as necessary
629 if (file_exists($new_path.$d->get_url_file())) {
630 $messages .= "File with same name already exists in the queue.\n";
631 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
632 $messages .= "Current file name was changed to " . $fname ."\n";
635 //now move the file
636 if (rename($d->get_url_filepath(),$new_path.$fname)) {
637 $d->url = "file://" .$new_path.$fname;
638 $d->set_foreign_id("");
639 $d->persist();
640 $d->persist();
641 $d->populate();
643 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
644 $d->_db->Execute($sql);
645 $messages .= "Document returned to queue successfully.\n";
648 else {
649 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
652 $this->_state = false;
653 $this->assign("messages",$messages);
654 return $this->list_action($patient_id);
657 $this->_state = false;
658 $this->assign("messages",$messages);
659 return $this->view_action($patient_id,$document_id);
662 function validate_action_process($patient_id="", $document_id) {
664 $d = new Document($document_id);
665 if($d->couch_docid && $d->couch_revid){
666 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
667 $url = $file_path.$d->get_url();
668 $couch = new CouchDB();
669 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
670 $resp = $couch->retrieve_doc($data);
671 $content = $resp->data;
672 //--------Temporarily writing the file for calculating the hash--------//
673 //-----------Will be removed after calculating the hash value----------//
674 $temp_file = fopen($url,"w");
675 fwrite($temp_file,base64_decode($content));
676 fclose($temp_file);
678 else{
679 $url = $d->get_url();
681 //strip url of protocol handler
682 $url = preg_replace("|^(.*)://|","",$url);
684 //change full path to current webroot. this is for documents that may have
685 //been moved from a different filesystem and the full path in the database
686 //is not current. this is also for documents that may of been moved to
687 //different patients. Note that the path_depth is used to see how far down
688 //the path to go. For example, originally the path_depth was always 1, which
689 //only allowed things like documents/1/<file>, but now can have more structured
690 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
691 // etc.
692 // NOTE that $from_filename and basename($url) are the same thing
693 $from_all = explode("/",$url);
694 $from_filename = array_pop($from_all);
695 $from_pathname_array = array();
696 for ($i=0;$i<$d->get_path_depth();$i++) {
697 $from_pathname_array[] = array_pop($from_all);
699 $from_pathname_array = array_reverse($from_pathname_array);
700 $from_pathname = implode("/",$from_pathname_array);
701 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
702 if (file_exists($temp_url)) {
703 $url = $temp_url;
706 if ($_POST['process'] != "true") {
707 die("process is '" . $_POST['process'] . "', expected 'true'");
708 return;
711 $d = new Document( $document_id );
712 $current_hash = sha1_file( $url );
713 $messages = xl('Current Hash').": ".$current_hash."<br>";
714 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
715 if ( $d->get_hash() == '' ) {
716 $d->hash = $current_hash;
717 $d->persist();
718 $d->populate();
719 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
720 } else if ( $current_hash != $d->get_hash() ) {
721 $messages .= xl('Hash does not match. Data integrity has been compromised.');
722 } else {
723 $messages .= xl('Document passed integrity check.');
725 $this->_state = false;
726 $this->assign("messages", $messages);
727 if($d->couch_docid && $d->couch_revid){
728 //Removing the temporary file which is used to create the hash
729 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
731 return $this->view_action($patient_id, $document_id);
734 // Added by Rod for metadata update.
736 function update_action_process($patient_id="", $document_id) {
738 if ($_POST['process'] != "true") {
739 die("process is '" . $_POST['process'] . "', expected 'true'");
740 return;
743 $docdate = $_POST['docdate'];
744 $docname = $_POST['docname'];
745 $issue_id = $_POST['issue_id'];
747 if (is_numeric($document_id)) {
748 $messages = '';
749 $d = new Document( $document_id );
750 $file_name = $d->get_url_file();
751 if ( $docname != '' &&
752 $docname != $file_name ) {
753 $path = $d->get_url_filepath();
754 $path = str_replace( $file_name, "", $path );
755 $new_url = $this->_rename_file( $path.$docname );
756 if ( rename( $d->get_url(), $new_url ) ) {
757 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
758 $url = preg_replace("|^(.*)://|","",$d->get_url());
759 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
760 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
761 if ( file_exists( $url ) ) {
762 unlink( $url );
764 $d->url = $new_url;
765 $d->persist();
766 $d->populate();
767 $messages .= xl('Document successfully renamed.')."<br>";
768 } else {
769 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
773 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
774 $docdate = "'$docdate'";
775 } else {
776 $docdate = "NULL";
778 if (!is_numeric($issue_id)) {
779 $issue_id = 0;
781 $couch_docid = $d->get_couch_docid();
782 $couch_revid = $d->get_couch_revid();
783 if($couch_docid && $couch_revid ){
784 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
785 "list_id = '$issue_id' " .
786 "WHERE id = '$document_id'";
787 $this->tree->_db->Execute($sql);
790 else{
791 $sql = "UPDATE documents SET docdate = $docdate, " .
792 "list_id = '$issue_id' " .
793 "WHERE id = '$document_id'";
794 $this->tree->_db->Execute($sql);
796 $messages .= xl('Document date and issue updated successfully') . "<br>";
799 $this->_state = false;
800 $this->assign("messages", $messages);
801 return $this->view_action($patient_id, $document_id);
804 function list_action($patient_id = "") {
805 $this->_last_node = null;
806 $categories_list = $this->tree->_get_categories_array($patient_id);
807 //print_r($categories_list);
809 $menu = new HTML_TreeMenu();
810 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
811 $menu->addItem($rnode);
812 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
813 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
815 $this->assign("tree_html",$treeMenu->toHTML());
817 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
821 * This is a recursive function to rename a file to something that doesn't already exist.
822 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
823 * to ensure documents opened correctly by external browser viewers. If the counter is at the
824 * end of the file, then will use it (to continue to work with older files), however all new
825 * counters will be placed within filenames.
827 function _rename_file($fname) {
828 $file = basename($fname);
829 $fparts = split("\.",$fname);
830 $path = dirname($fname);
831 if (count($fparts) > 1) {
832 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
833 //increment the counter in filename
834 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
835 $fname = join(".",$fparts);
837 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
838 //increment counter at end of filename (so compatible with previous openemr version files
839 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
840 $fname = join(".",$fparts);
842 elseif (is_numeric($fparts[count($fparts) -1])) {
843 //leave date at end and place counter in filename
844 array_splice($fparts, -1, 0, "1");
845 $fname = join(".",$fparts);
847 else {
848 //add the counter to filename
849 array_splice($fparts, -1, 0, "1");
850 $fname = join(".",$fparts);
853 else { // (count($fparts) == 1)
854 //place counter at end of filename
855 array_push($fparts,"1");
856 $fname = join(".",$fparts);
859 if (file_exists($fname)) {
860 return $this->_rename_file($fname);
862 else {
863 return($fname);
867 function &_array_recurse($array,$categories = array()) {
868 if (!is_array($array)) {
869 $array = array();
871 $node = &$this->_last_node;
872 $current_node = &$node;
873 $expandedIcon = 'folder-expanded.gif';
874 foreach($array as $id => $ar) {
875 $icon = 'folder.gif';
876 if (is_array($ar) || !empty($id)) {
877 if ($node == null) {
878 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
879 $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));
880 $this->_last_node = &$rnode;
881 $node = &$rnode;
882 $current_node = &$rnode;
884 else {
885 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
886 $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)));
887 $current_node = &$this->_last_node;
890 $this->_array_recurse($ar,$categories);
892 else {
893 if ($id === 0 && !empty($ar)) {
894 $info = $this->tree->get_node_info($id);
895 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
896 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
898 else {
899 //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
900 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
901 if ($id !== 0 && is_object($node)) {
902 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
903 $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)));
909 // If there are documents in this document category, then add their
910 // attributes to the current node.
911 $icon = "file3.png";
912 if (is_array($categories[$id])) {
913 foreach ($categories[$id] as $doc) {
914 if($this->tree->get_node_name($id) == "CCR"){
915 $current_node->addItem(new HTML_TreeNode(array(
916 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
917 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
918 'icon' => $icon,
919 'expandedIcon' => $expandedIcon,
920 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
921 )));
922 }elseif($this->tree->get_node_name($id) == "CCD"){
923 $current_node->addItem(new HTML_TreeNode(array(
924 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
925 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
926 'icon' => $icon,
927 'expandedIcon' => $expandedIcon,
928 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
929 )));
930 }else{
931 $current_node->addItem(new HTML_TreeNode(array(
932 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
933 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
934 'icon' => $icon,
935 'expandedIcon' => $expandedIcon
936 )));
942 return $node;
945 //function for logging the errors in writing file to CouchDB/Hard Disk
946 function document_upload_download_log($patientid,$content){
947 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
948 $log_file = 'log.txt';
949 if(!is_dir($log_path))
950 mkdir($log_path,0777,true);
951 $LOG = fopen($log_path.$log_file,'a');
952 fwrite($LOG,$content);
953 fclose($LOG);
957 //place to hold optional code
958 //$first_node = array_keys($t->tree);
959 //$first_node = $first_node[0];
960 //$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')"));
962 //$this->_last_node = &$node1;