Deleter fix for physical exam form. Thanks to DataGroup for identifying the problem...
[openemr.git] / controllers / C_Document.class.php
blobfeb0e2b9c365c32bd1fe2c89cb8fdd714fa6547c
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 $file_path;
24 function C_Document($template_mod = "general") {
25 parent::Controller();
26 $this->documents = array();
27 $this->template_mod = $template_mod;
28 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
29 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
31 //get global config options for this namespace
32 $this->_config = $GLOBALS['oer_config']['documents'];
33 if($GLOBALS['document_storage_method']==1){
34 $this->file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
36 else{
37 $this->file_path = $this->_config['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
39 $this->_args = array("patient_id" => $_GET['patient_id']);
41 $this->assign("STYLE", $GLOBALS['style']);
42 $t = new CategoryTree(1);
43 //print_r($t->tree);
44 $this->tree = $t;
47 function upload_action($patient_id,$category_id) {
48 $category_name = $this->tree->get_node_name($category_id);
49 $this->assign("category_id", $category_id);
50 $this->assign("category_name", $category_name);
51 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
52 $this->assign("patient_id", $patient_id);
53 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
54 $this->assign("activity", $activity);
55 return $this->list_action($patient_id);
58 //Upload multiple files on single click
59 //2013-02-10 EMR Direct: added $non_HTTP_owner to allow storage of Direct Message attachments
60 //through this mechanism, and is set to the user_id for the background process adding the document
61 function upload_action_process($non_HTTP_owner=false) {
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'];
85 if (is_numeric($_POST['patient_id'])) {
86 $patient_id = $_POST['patient_id'];
89 $sentUploadStatus = array();
90 if( count($_FILES['file']['name']) > 0){
91 $upl_inc = 0;
92 foreach($_FILES['file']['name'] as $key => $value){
93 $fname = $value;
94 $err = "";
95 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
96 $fname = $value;
97 if (empty($fname)) {
98 $fname = htmlentities("<empty>");
100 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
101 if ($_FILES['file']['size'][$key] == 0) {
102 $error .= "The system does not permit uploading files of with size 0.\n";
104 }else{
106 if (!file_exists($this->file_path)) {
107 if (!mkdir($this->file_path,0700)) {
108 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
112 if ( $_POST['destination'] != '' ) {
113 $fname = $_POST['destination'];
115 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
116 if (file_exists($this->file_path.$fname)) {
117 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
118 $fname = basename($this->_rename_file($this->file_path.$fname));
119 $_FILES['file']['name'][$key] = $fname;
120 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
123 if ( $doDecryption ) {
124 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key] , "r" );
125 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
126 $plaintext = $this->decrypt( $filetext, $passphrase );
127 fclose($tmpfile);
128 unlink( $_FILES['file']['tmp_name'][$key] );
129 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
130 fwrite( $tmpfile, $plaintext );
131 fclose( $tmpfile );
132 $_FILES['file']['size'][$key] = filesize( $_FILES['file']['tmp_name'][$key] );
135 $docid = '';
136 $resp = '';
137 if($couchDB == true){
138 $couch = new CouchDB();
139 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
140 $docid = $couch->stringToId($docname);
141 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "rb" );
142 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
143 fclose( $tmpfile );
144 //--------Temporarily writing the file for calculating the hash--------//
145 //-----------Will be removed after calculating the hash value----------//
146 $temp_file = fopen($this->file_path.$fname,"w");
147 fwrite($temp_file,$filetext);
148 fclose($temp_file);
149 //---------------------------------------------------------------------//
151 $json = json_encode(base64_encode($filetext));
152 $db = $GLOBALS['couchdb_dbase'];
153 $data = array($db,$docid,$patient_id,$encounter,$_FILES['file']['type'][$key],$json);
154 $resp = $couch->check_saveDOC($data);
155 if(!$resp->id || !$resp->_rev){
156 $data = array($db,$docid,$patient_id,$encounter);
157 $resp = $couch->retrieve_doc($data);
158 $docid = $resp->_id;
159 $revid = $resp->_rev;
161 else{
162 $docid = $resp->id;
163 $revid = $resp->rev;
165 if(!$docid && !$revid){ //if couchdb save failed
166 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
167 if($GLOBALS['couchdb_log']==1){
168 ob_start();
169 var_dump($resp);
170 $couchError=ob_get_clean();
171 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
172 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
173 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
174 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
175 $log_content .= $couchError;
176 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
181 if($harddisk == true){
182 $uploadSuccess = false;
183 $move_cmd = ($non_HTTP_owner ? "rename" : "move_uploaded_file");
184 if($move_cmd($_FILES['file']['tmp_name'][$key],$this->file_path.$fname)){
185 $uploadSuccess = true;
187 else{
188 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
192 $this->assign("upload_success", "true");
193 $d = new Document();
194 $d->storagemethod = $GLOBALS['document_storage_method'];
195 if($harddisk == true)
196 $d->url = "file://" .$this->file_path.$fname;
197 else
198 $d->url = $fname;
199 if($couchDB == true){
200 $d->couch_docid = $docid;
201 $d->couch_revid = $revid;
203 if ($_FILES['file']['type'][$key] == 'text/xml') {
204 $d->mimetype = 'application/xml';
206 else {
207 $d->mimetype = $_FILES['file']['type'][$key];
209 $d->size = $_FILES['file']['size'][$key];
210 $d->owner = $non_HTTP_owner ? $non_HTTP_owner : $_SESSION['authUserID'];
211 $sha1Hash = sha1_file( $this->file_path.$fname );
212 if($couchDB == true){
213 //Removing the temporary file which is used to create the hash
214 unlink($this->file_path.$fname);
216 $d->hash = $sha1Hash;
217 $d->type = $d->type_array['file_url'];
218 $d->set_foreign_id($patient_id);
219 if($harddisk == true || ($couchDB == true && $docid && $revid)){
220 $d->persist();
221 $d->populate();
223 $sentUploadStatus[] = $d;
224 $this->assign("file",$sentUploadStatus);
226 if (is_numeric($d->get_id()) && is_numeric($category_id)){
227 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
228 $d->_db->Execute($sql);
230 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
231 $log_content .= "\r\n\r\n";
232 $this->document_upload_download_log($patient_id,$log_content);
238 $this->assign("error", nl2br($error));
239 //$this->_state = false;
240 $_POST['process'] = "";
241 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
244 function note_action_process($patient_id) {
246 if ($_POST['process'] != "true")
247 return;
249 $n = new Note();
250 $n->set_owner($_SESSION['authUserID']);
251 parent::populate_object($n);
252 $n->persist();
254 $this->_state = false;
255 $_POST['process'] = "";
256 return $this->view_action($patient_id,$n->get_foreign_id());
259 function default_action() {
260 return $this->list_action();
263 function view_action($patient_id="",$doc_id) {
264 // Added by Rod to support document delete:
265 global $gacl_object, $phpgacl_location;
266 global $ISSUE_TYPES;
268 require_once(dirname(__FILE__) . "/../library/acl.inc");
269 require_once(dirname(__FILE__) . "/../library/lists.inc");
271 $d = new Document($doc_id);
272 $n = new Note();
274 $notes = $n->notes_factory($doc_id);
276 $this->assign("file", $d);
277 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
278 $this->assign("NOTE_ACTION",$this->_link("note"));
279 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
280 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
282 // Added by Rod to support document delete:
283 $delete_string = '';
284 if (acl_check('admin', 'super')) {
285 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
286 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
288 $this->assign("delete_string", $delete_string);
289 $this->assign("REFRESH_ACTION",$this->_link("list"));
291 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
292 "document_id=" . $d->get_id() . "&process=true");
294 // Added by Rod to support document date update:
295 $this->assign("DOCDATE", $d->get_docdate());
296 $this->assign("UPDATE_ACTION",$this->_link("update") .
297 "document_id=" . $d->get_id() . "&process=true");
299 // Added by Rod to support document issue update:
300 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
301 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
302 "pid = $patient_id " . // AND enddate IS NULL " .
303 "ORDER BY type, begdate");
304 while ($irow = sqlFetchArray($ires)) {
305 $desc = $irow['type'];
306 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
307 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
308 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
309 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
311 $this->assign("ISSUES_LIST", $issues_options);
313 $this->assign("notes",$notes);
315 $this->_last_node = null;
317 $menu = new HTML_TreeMenu();
319 //pass an empty array because we don't want the documents for each category showing up in this list box
320 $rnode = $this->_array_recurse($this->tree->tree,array());
321 $menu->addItem($rnode);
322 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
324 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
326 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
327 $this->assign("activity", $activity);
329 return $this->list_action($patient_id);
332 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
334 $td = mcrypt_module_open( $cypher, '', $mode, '');
335 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
336 mcrypt_generic_init( $td, $key, $iv );
337 $crypttext = mcrypt_generic( $td, $plaintext );
338 mcrypt_generic_deinit( $td );
339 return $iv.$crypttext;
342 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
344 $plaintext = '';
345 $td = mcrypt_module_open( $cypher, '', $mode, '' );
346 $ivsize = mcrypt_enc_get_iv_size( $td) ;
347 $iv = substr( $crypttext, 0, $ivsize );
348 $crypttext = substr( $crypttext, $ivsize );
349 if( $iv )
351 mcrypt_generic_init( $td, $key, $iv );
352 $plaintext = mdecrypt_generic( $td, $crypttext );
354 return $plaintext;
358 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
360 $encrypted = $_POST['encrypted'];
361 $passphrase = $_POST['passphrase'];
362 $doEncryption = false;
363 if ( !$GLOBALS['hide_document_encryption'] &&
364 $encrypted == "true" &&
365 $passphrase ) {
366 $doEncryption = true;
369 //controller function ruins booleans, so need to manually re-convert to booleans
370 if ($as_file == "true") {
371 $as_file=true;
373 else if ($as_file == "false") {
374 $as_file=false;
376 if ($original_file == "true") {
377 $original_file=true;
379 else if ($original_file == "false") {
380 $original_file=false;
383 $d = new Document($document_id);
384 $url = $d->get_url();
385 $storagemethod = $d->get_storagemethod();
386 $couch_docid = $d->get_couch_docid();
387 $couch_revid = $d->get_couch_revid();
389 if($couch_docid && $couch_revid && $original_file){
390 $couch = new CouchDB();
391 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
392 $resp = $couch->retrieve_doc($data);
393 $content = $resp->data;
394 if($content=='' && $GLOBALS['couchdb_log']==1){
395 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
396 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
397 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
398 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
399 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
400 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
401 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
402 die(xl("File retrieval from CouchDB failed"));
404 header('Content-Description: File Transfer');
405 header('Content-Transfer-Encoding: binary');
406 header('Expires: 0');
407 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
408 header('Pragma: public');
409 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
410 $fh = fopen($tmpcouchpath,"w");
411 fwrite($fh,base64_decode($content));
412 fclose($fh);
413 $f = fopen($tmpcouchpath,"r");
414 if ( $doEncryption ) {
415 $filetext = fread( $f, filesize($tmpcouchpath) );
416 $ciphertext = $this->encrypt( $filetext, $passphrase );
417 $tmpfilepath = $GLOBALS['temporary_files_dir'];
418 $tmpfilename = "/encrypted_".$d->get_url_file();
419 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
420 fwrite( $tmpfile, $ciphertext );
421 fclose( $tmpfile );
422 header('Content-Disposition: attachment; filename='.$tmpfilename );
423 header("Content-Type: application/octet-stream" );
424 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
425 ob_clean();
426 flush();
427 readfile( $tmpfilepath.$tmpfilename );
428 unlink( $tmpfilepath.$tmpfilename );
429 } else {
430 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
431 header("Content-Type: " . $d->get_mimetype());
432 header("Content-Length: " . filesize($tmpcouchpath));
433 fpassthru($f);
435 fclose($f);
436 if($content!='')
437 unlink($tmpcouchpath);
438 exit;//exits only if file download from CouchDB is successfull.
440 //strip url of protocol handler
441 $url = preg_replace("|^(.*)://|","",$url);
443 //change full path to current webroot. this is for documents that may have
444 //been moved from a different filesystem and the full path in the database
445 //is not current. this is also for documents that may of been moved to
446 //different patients
447 // NOTE that $from_filename and basename($url) are the same thing
448 $from_all = explode("/",$url);
449 $from_filename = array_pop($from_all);
450 $from_patientid = array_pop($from_all);
451 if($couch_docid && $couch_revid){
452 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
453 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
456 else{
457 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
460 if (file_exists($temp_url)) {
461 $url = $temp_url;
465 if (!file_exists($url)) {
466 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;
469 else {
470 if ($original_file) {
471 //normal case when serving the file referenced in database
472 header('Content-Description: File Transfer');
473 header('Content-Transfer-Encoding: binary');
474 header('Expires: 0');
475 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
476 header('Pragma: public');
477 $f = fopen($url,"r");
478 if ( $doEncryption ) {
479 $filetext = fread( $f, filesize($url) );
480 $ciphertext = $this->encrypt( $filetext, $passphrase );
481 $tmpfilepath = $GLOBALS['temporary_files_dir'];
482 $tmpfilename = "/encrypted_".$d->get_url_file();
483 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
484 fwrite( $tmpfile, $ciphertext );
485 fclose( $tmpfile );
486 header('Content-Disposition: attachment; filename='.$tmpfilename );
487 header("Content-Type: application/octet-stream" );
488 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
489 ob_clean();
490 flush();
491 readfile( $tmpfilepath.$tmpfilename );
492 unlink( $tmpfilepath.$tmpfilename );
493 } else {
494 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
495 header("Content-Type: " . $d->get_mimetype());
496 header("Content-Length: " . filesize($url));
497 fpassthru($f);
499 exit;
501 else {
502 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
503 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
504 if($couch_docid && $couch_revid){
505 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
507 else{
508 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
510 header("Pragma: public");
511 header("Expires: 0");
512 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
513 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
514 header("Content-Type: image/jpeg");
515 header("Content-Length: " . filesize($url));
516 $f = fopen($url,"r");
517 fpassthru($f);
518 if($couch_docid && $couch_revid){
519 fclose($f);
520 unlink($url);
521 $url=str_replace("_converted.jpg",'.pdf',$url);
522 unlink($url);
524 exit;
529 function queue_action($patient_id="") {
530 $messages = $this->_tpl_vars['messages'];
531 $queue_files = array();
533 //see if the repository exists and it is a directory else error
534 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
535 $dir = opendir($this->_config['repository']);
536 //read each entry in the directory
537 while (($file = readdir($dir)) !== false) {
538 //concat the filename and path
539 $file = $this->_config['repository'] .$file;
540 $file_info = array();
541 //if the filename is a file get its info and put into a tmp array
542 if (is_file($file) && strpos(basename($file),".") !== 0) {
543 $file_info['filename'] = basename($file);
544 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
545 $d = Document::document_factory_url("file://" . $file);
546 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
547 $file_info['patient_id'] = $patient_match[1];
548 $file_info['document_id'] = $d->get_id();
549 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
551 //merge the tmp array into the larger array
552 $queue_files[] = $file_info;
555 closedir($dir);
557 else {
558 $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";
562 $this->assign("queue_files",$queue_files);
563 $this->_last_node = null;
565 $menu = new HTML_TreeMenu();
567 //pass an empty array because we don't want the documents for each category showing up in this list box
568 $rnode = $this->_array_recurse($this->tree->tree,array());
569 $menu->addItem($rnode);
570 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
572 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
574 $this->assign("messages",nl2br($messages));
575 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
578 function queue_action_process() {
579 if ($_POST['process'] != "true")
580 return;
582 $messages = $this->_tpl_vars['messages'];
584 //build a category tree so we can have a list of category ids that are valid
585 $ct = new CategoryTree(1);
586 $categories = $ct->_id_name;
588 //see if there were and posted files and assign them
589 $files = null;
590 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
592 //loop through posted files
593 foreach($files as $doc_id=> $file) {
594 //only operate on files checked as active
595 if (!$file['active']) continue;
597 //run basic validation checks
598 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
599 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
600 continue;
603 //validate that the pod exists
604 $d = new Document($doc_id);
605 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
606 $result = $d->_db->Execute($sql);
608 if (!$result || $result->EOF) {
609 //patient id does not exist
610 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
611 continue;
614 //validate that the category id exists
615 if (!isset($categories[$file['category_id']])) {
616 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
617 continue;
620 //now do the work of moving the file
621 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
623 //see if the patient dir exists in the repository and create if not
624 if (!file_exists($new_path)) {
625 if (!mkdir($new_path,0700)) {
626 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
627 continue;
631 //fname is the name of the file after it is moved
632 $fname = $file['name'];
634 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
635 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
636 if ($patient_match[1] == $file['patient_id']) {
637 $fname = preg_replace("/^([0-9]+)_/","",$fname);
640 //filenames should not have funny chars
641 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
643 //see if there is an existing file with the same name and rename as necessary
644 if (file_exists($new_path.$file['name'])) {
645 $messages .= "File with same name already exists at location: " . $new_path . "\n";
646 $fname = basename($this->_rename_file($new_path.$file['name']));
647 $messages .= "Current file name was changed to " . $fname ."\n";
650 //now move the file
651 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
652 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
653 $d->url = "file://" .$new_path.$fname;
654 $d->set_foreign_id($file['patient_id']);
655 $d->set_mimetype($mimetype);
656 $d->persist();
657 $d->populate();
659 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
660 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
661 $d->_db->Execute($sql);
664 else {
665 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
668 $this->assign("messages",$messages);
669 $_POST['process'] = "";
672 function move_action_process($patient_id="",$document_id) {
673 if ($_POST['process'] != "true")
674 return;
676 $new_category_id = $_POST['new_category_id'];
677 $new_patient_id = $_POST['new_patient_id'];
679 //move to new category
680 if (is_numeric($new_category_id) && is_numeric($document_id)) {
681 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
682 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
683 //echo $sql;
684 $this->tree->_db->Execute($sql);
687 //move to new patient
688 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
689 $d = new Document($document_id);
690 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
691 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
692 $result = $d->_db->Execute($sql);
694 if (!$result || $result->EOF) {
695 //patient id does not exist
696 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
698 else {
700 $couch_docid = $d->get_couch_docid();
701 $couch_revid = $d->get_couch_revid();
702 //set the new patient in CouchDB
703 $couchsavefailed=false;
704 if($couch_docid && $couch_revid){
705 $couch = new CouchDB();
706 $db = $GLOBALS['couchdb_dbase'];
707 $data=array($db,$couch_docid);
708 $couchresp=$couch->retrieve_doc($data);
709 //CouchDB doesnot support updating a single value in a document.
710 //Have to retrieve the entire document,update the necessary value and save again
711 list($db,$docid,$revid,$patient_id,$encounter,$type,$json) = $data;
712 $data=array($db,$couch_docid,$couch_revid,$new_patient_id,$couchresp->encounter,$couchresp->mimetype,json_encode($couchresp->data));
713 $resp = $couch->update_doc($data);
714 //Sometimes the response from CouchDB is not available
715 //still it would have saved in the DB. Hence check one more time
716 if(!$resp->_id || !$resp->_rev){
717 $data = array($db,$couch_docid,$new_patient_id,$couchresp->encounter);
718 $resp = $couch->retrieve_doc($data);
722 if($resp->_rev ==$couch_revid){
723 $couchsavefailed=true;
725 else{
726 $d->set_couch_revid($resp->_rev);
731 //set the new patient in mysql
732 $d->set_foreign_id($new_patient_id);
733 $d->persist();
734 $this->_state = false;
735 if(!$couchsavefailed){
737 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
739 else{
741 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
743 $this->assign("messages",$messages);
744 return $this->list_action($patient_id);
747 //in this case return the document to the queue instead of moving it
748 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
749 $d = new Document($document_id);
750 $new_path = $this->_config['repository'];
751 $fname = $d->get_url_file();
753 //see if there is an existing file with the same name and rename as necessary
754 if (file_exists($new_path.$d->get_url_file())) {
755 $messages .= "File with same name already exists in the queue.\n";
756 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
757 $messages .= "Current file name was changed to " . $fname ."\n";
760 //now move the file
761 if (rename($d->get_url_filepath(),$new_path.$fname)) {
762 $d->url = "file://" .$new_path.$fname;
763 $d->set_foreign_id("");
764 $d->persist();
765 $d->persist();
766 $d->populate();
768 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
769 $d->_db->Execute($sql);
770 $messages .= "Document returned to queue successfully.\n";
773 else {
774 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
777 $this->_state = false;
778 $this->assign("messages",$messages);
779 return $this->list_action($patient_id);
782 $this->_state = false;
783 $this->assign("messages",$messages);
784 return $this->view_action($patient_id,$document_id);
787 function validate_action_process($patient_id="", $document_id) {
789 $d = new Document($document_id);
790 if($d->couch_docid && $d->couch_revid){
791 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
792 $url = $file_path.$d->get_url();
793 $couch = new CouchDB();
794 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
795 $resp = $couch->retrieve_doc($data);
796 $content = $resp->data;
797 //--------Temporarily writing the file for calculating the hash--------//
798 //-----------Will be removed after calculating the hash value----------//
799 $temp_file = fopen($url,"w");
800 fwrite($temp_file,base64_decode($content));
801 fclose($temp_file);
803 else{
804 $url = $d->get_url();
806 //strip url of protocol handler
807 $url = preg_replace("|^(.*)://|","",$url);
809 //change full path to current webroot. this is for documents that may have
810 //been moved from a different filesystem and the full path in the database
811 //is not current. this is also for documents that may of been moved to
812 //different patients
813 // NOTE that $from_filename and basename($url) are the same thing
814 $from_all = explode("/",$url);
815 $from_filename = array_pop($from_all);
816 $from_patientid = array_pop($from_all);
817 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
818 if (file_exists($temp_url)) {
819 $url = $temp_url;
822 if ($_POST['process'] != "true") {
823 die("process is '" . $_POST['process'] . "', expected 'true'");
824 return;
827 $d = new Document( $document_id );
828 $current_hash = sha1_file( $url );
829 $messages = xl('Current Hash').": ".$current_hash."<br>";
830 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
831 if ( $d->get_hash() == '' ) {
832 $d->hash = $current_hash;
833 $d->persist();
834 $d->populate();
835 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
836 } else if ( $current_hash != $d->get_hash() ) {
837 $messages .= xl('Hash does not match. Data integrity has been compromised.');
838 } else {
839 $messages .= xl('Document passed integrity check.');
841 $this->_state = false;
842 $this->assign("messages", $messages);
843 if($d->couch_docid && $d->couch_revid){
844 //Removing the temporary file which is used to create the hash
845 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
847 return $this->view_action($patient_id, $document_id);
850 // Added by Rod for metadata update.
852 function update_action_process($patient_id="", $document_id) {
854 if ($_POST['process'] != "true") {
855 die("process is '" . $_POST['process'] . "', expected 'true'");
856 return;
859 $docdate = $_POST['docdate'];
860 $docname = $_POST['docname'];
861 $issue_id = $_POST['issue_id'];
863 if (is_numeric($document_id)) {
864 $messages = '';
865 $d = new Document( $document_id );
866 $file_name = $d->get_url_file();
867 if ( $docname != '' &&
868 $docname != $file_name ) {
869 $path = $d->get_url_filepath();
870 $path = str_replace( $file_name, "", $path );
871 $new_url = $this->_rename_file( $path.$docname );
872 if ( rename( $d->get_url(), $new_url ) ) {
873 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
874 $url = preg_replace("|^(.*)://|","",$d->get_url());
875 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
876 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
877 if ( file_exists( $url ) ) {
878 unlink( $url );
880 $d->url = $new_url;
881 $d->persist();
882 $d->populate();
883 $messages .= xl('Document successfully renamed.')."<br>";
884 } else {
885 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
889 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
890 $docdate = "'$docdate'";
891 } else {
892 $docdate = "NULL";
894 if (!is_numeric($issue_id)) {
895 $issue_id = 0;
897 $couch_docid = $d->get_couch_docid();
898 $couch_revid = $d->get_couch_revid();
899 if($couch_docid && $couch_revid ){
900 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
901 "list_id = '$issue_id' " .
902 "WHERE id = '$document_id'";
903 $this->tree->_db->Execute($sql);
906 else{
907 $sql = "UPDATE documents SET docdate = $docdate, " .
908 "list_id = '$issue_id' " .
909 "WHERE id = '$document_id'";
910 $this->tree->_db->Execute($sql);
912 $messages .= xl('Document date and issue updated successfully') . "<br>";
915 $this->_state = false;
916 $this->assign("messages", $messages);
917 return $this->view_action($patient_id, $document_id);
920 function list_action($patient_id = "") {
921 $this->_last_node = null;
922 $categories_list = $this->tree->_get_categories_array($patient_id);
923 //print_r($categories_list);
925 $menu = new HTML_TreeMenu();
926 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
927 $menu->addItem($rnode);
928 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
929 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
931 $this->assign("tree_html",$treeMenu->toHTML());
933 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
937 * This is a recursive function to rename a file to something that doesn't already exist.
938 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
939 * to ensure documents opened correctly by external browser viewers. If the counter is at the
940 * end of the file, then will use it (to continue to work with older files), however all new
941 * counters will be placed within filenames.
943 function _rename_file($fname) {
944 $file = basename($fname);
945 $fparts = split("\.",$fname);
946 $path = dirname($fname);
947 if (count($fparts) > 1) {
948 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
949 //increment the counter in filename
950 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
951 $fname = join(".",$fparts);
953 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
954 //increment counter at end of filename (so compatible with previous openemr version files
955 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
956 $fname = join(".",$fparts);
958 elseif (is_numeric($fparts[count($fparts) -1])) {
959 //leave date at end and place counter in filename
960 array_splice($fparts, -1, 0, "1");
961 $fname = join(".",$fparts);
963 else {
964 //add the counter to filename
965 array_splice($fparts, -1, 0, "1");
966 $fname = join(".",$fparts);
969 else { // (count($fparts) == 1)
970 //place counter at end of filename
971 array_push($fparts,"1");
972 $fname = join(".",$fparts);
975 if (file_exists($fname)) {
976 return $this->_rename_file($fname);
978 else {
979 return($fname);
983 function &_array_recurse($array,$categories = array()) {
984 if (!is_array($array)) {
985 $array = array();
987 $node = &$this->_last_node;
988 $current_node = &$node;
989 $expandedIcon = 'folder-expanded.gif';
990 foreach($array as $id => $ar) {
991 $icon = 'folder.gif';
992 if (is_array($ar) || !empty($id)) {
993 if ($node == null) {
994 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
995 $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));
996 $this->_last_node = &$rnode;
997 $node = &$rnode;
998 $current_node =&$rnode;
1000 else {
1001 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1002 $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)));
1003 $current_node =&$this->_last_node;
1006 $this->_array_recurse($ar,$categories);
1008 else {
1009 if ($id === 0 && !empty($ar)) {
1010 $info = $this->tree->get_node_info($id);
1011 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1012 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1014 else {
1015 //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
1016 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1017 if ($id !== 0 && is_object($node)) {
1018 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1019 $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)));
1025 // If there are documents in this document category, then add their
1026 // attributes to the current node.
1027 $icon = "file3.png";
1028 if (is_array($categories[$id])) {
1029 foreach ($categories[$id] as $doc) {
1030 if($this->tree->get_node_name($id) == "CCR"){
1031 $current_node->addItem(new HTML_TreeNode(array(
1032 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1033 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1034 'icon' => $icon,
1035 'expandedIcon' => $expandedIcon,
1036 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1037 )));
1038 }elseif($this->tree->get_node_name($id) == "CCD"){
1039 $current_node->addItem(new HTML_TreeNode(array(
1040 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1041 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1042 'icon' => $icon,
1043 'expandedIcon' => $expandedIcon,
1044 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1045 )));
1046 }else{
1047 $current_node->addItem(new HTML_TreeNode(array(
1048 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1049 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1050 'icon' => $icon,
1051 'expandedIcon' => $expandedIcon
1052 )));
1058 return $node;
1061 //function for logging the errors in writing file to CouchDB/Hard Disk
1062 function document_upload_download_log($patientid,$content){
1063 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1064 $log_file = 'log.txt';
1065 if(!is_dir($log_path))
1066 mkdir($log_path,0777,true);
1067 $LOG = fopen($log_path.$log_file,'a');
1068 fwrite($LOG,$content);
1069 fclose($LOG);
1073 //place to hold optional code
1074 //$first_node = array_keys($t->tree);
1075 //$first_node = $first_node[0];
1076 //$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')"));
1078 //$this->_last_node = &$node1;