Implement direct message receive and background services manager, take 1.
[openemr.git] / controllers / C_Document.class.php
blob993c034c1042a1f39d0c1afabd2cc797c72f632d
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 parent::populate_object($n);
251 $n->persist();
253 $this->_state = false;
254 $_POST['process'] = "";
255 return $this->view_action($patient_id,$n->get_foreign_id());
258 function default_action() {
259 return $this->list_action();
262 function view_action($patient_id="",$doc_id) {
263 // Added by Rod to support document delete:
264 global $gacl_object, $phpgacl_location;
265 global $ISSUE_TYPES;
267 require_once(dirname(__FILE__) . "/../library/acl.inc");
268 require_once(dirname(__FILE__) . "/../library/lists.inc");
270 $d = new Document($doc_id);
271 $n = new Note();
273 $notes = $n->notes_factory($doc_id);
275 $this->assign("file", $d);
276 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
277 $this->assign("NOTE_ACTION",$this->_link("note"));
278 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
279 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
281 // Added by Rod to support document delete:
282 $delete_string = '';
283 if (acl_check('admin', 'super')) {
284 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
285 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
287 $this->assign("delete_string", $delete_string);
288 $this->assign("REFRESH_ACTION",$this->_link("list"));
290 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
291 "document_id=" . $d->get_id() . "&process=true");
293 // Added by Rod to support document date update:
294 $this->assign("DOCDATE", $d->get_docdate());
295 $this->assign("UPDATE_ACTION",$this->_link("update") .
296 "document_id=" . $d->get_id() . "&process=true");
298 // Added by Rod to support document issue update:
299 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
300 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
301 "pid = $patient_id " . // AND enddate IS NULL " .
302 "ORDER BY type, begdate");
303 while ($irow = sqlFetchArray($ires)) {
304 $desc = $irow['type'];
305 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
306 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
307 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
308 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
310 $this->assign("ISSUES_LIST", $issues_options);
312 $this->assign("notes",$notes);
314 $this->_last_node = null;
316 $menu = new HTML_TreeMenu();
318 //pass an empty array because we don't want the documents for each category showing up in this list box
319 $rnode = $this->_array_recurse($this->tree->tree,array());
320 $menu->addItem($rnode);
321 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
323 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
325 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
326 $this->assign("activity", $activity);
328 return $this->list_action($patient_id);
331 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
333 $td = mcrypt_module_open( $cypher, '', $mode, '');
334 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
335 mcrypt_generic_init( $td, $key, $iv );
336 $crypttext = mcrypt_generic( $td, $plaintext );
337 mcrypt_generic_deinit( $td );
338 return $iv.$crypttext;
341 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
343 $plaintext = '';
344 $td = mcrypt_module_open( $cypher, '', $mode, '' );
345 $ivsize = mcrypt_enc_get_iv_size( $td) ;
346 $iv = substr( $crypttext, 0, $ivsize );
347 $crypttext = substr( $crypttext, $ivsize );
348 if( $iv )
350 mcrypt_generic_init( $td, $key, $iv );
351 $plaintext = mdecrypt_generic( $td, $crypttext );
353 return $plaintext;
357 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
359 $encrypted = $_POST['encrypted'];
360 $passphrase = $_POST['passphrase'];
361 $doEncryption = false;
362 if ( !$GLOBALS['hide_document_encryption'] &&
363 $encrypted == "true" &&
364 $passphrase ) {
365 $doEncryption = true;
368 //controller function ruins booleans, so need to manually re-convert to booleans
369 if ($as_file == "true") {
370 $as_file=true;
372 else if ($as_file == "false") {
373 $as_file=false;
375 if ($original_file == "true") {
376 $original_file=true;
378 else if ($original_file == "false") {
379 $original_file=false;
382 $d = new Document($document_id);
383 $url = $d->get_url();
384 $storagemethod = $d->get_storagemethod();
385 $couch_docid = $d->get_couch_docid();
386 $couch_revid = $d->get_couch_revid();
388 if($couch_docid && $couch_revid && $original_file){
389 $couch = new CouchDB();
390 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
391 $resp = $couch->retrieve_doc($data);
392 $content = $resp->data;
393 if($content=='' && $GLOBALS['couchdb_log']==1){
394 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
395 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
396 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
397 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
398 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
399 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
400 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
401 die(xl("File retrieval from CouchDB failed"));
403 header('Content-Description: File Transfer');
404 header('Content-Transfer-Encoding: binary');
405 header('Expires: 0');
406 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
407 header('Pragma: public');
408 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
409 $fh = fopen($tmpcouchpath,"w");
410 fwrite($fh,base64_decode($content));
411 fclose($fh);
412 $f = fopen($tmpcouchpath,"r");
413 if ( $doEncryption ) {
414 $filetext = fread( $f, filesize($tmpcouchpath) );
415 $ciphertext = $this->encrypt( $filetext, $passphrase );
416 $tmpfilepath = $GLOBALS['temporary_files_dir'];
417 $tmpfilename = "/encrypted_".$d->get_url_file();
418 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
419 fwrite( $tmpfile, $ciphertext );
420 fclose( $tmpfile );
421 header('Content-Disposition: attachment; filename='.$tmpfilename );
422 header("Content-Type: application/octet-stream" );
423 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
424 ob_clean();
425 flush();
426 readfile( $tmpfilepath.$tmpfilename );
427 unlink( $tmpfilepath.$tmpfilename );
428 } else {
429 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
430 header("Content-Type: " . $d->get_mimetype());
431 header("Content-Length: " . filesize($tmpcouchpath));
432 fpassthru($f);
434 fclose($f);
435 if($content!='')
436 unlink($tmpcouchpath);
437 exit;//exits only if file download from CouchDB is successfull.
439 //strip url of protocol handler
440 $url = preg_replace("|^(.*)://|","",$url);
442 //change full path to current webroot. this is for documents that may have
443 //been moved from a different filesystem and the full path in the database
444 //is not current. this is also for documents that may of been moved to
445 //different patients
446 // NOTE that $from_filename and basename($url) are the same thing
447 $from_all = explode("/",$url);
448 $from_filename = array_pop($from_all);
449 $from_patientid = array_pop($from_all);
450 if($couch_docid && $couch_revid){
451 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
452 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
455 else{
456 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
459 if (file_exists($temp_url)) {
460 $url = $temp_url;
464 if (!file_exists($url)) {
465 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;
468 else {
469 if ($original_file) {
470 //normal case when serving the file referenced in database
471 header('Content-Description: File Transfer');
472 header('Content-Transfer-Encoding: binary');
473 header('Expires: 0');
474 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
475 header('Pragma: public');
476 $f = fopen($url,"r");
477 if ( $doEncryption ) {
478 $filetext = fread( $f, filesize($url) );
479 $ciphertext = $this->encrypt( $filetext, $passphrase );
480 $tmpfilepath = $GLOBALS['temporary_files_dir'];
481 $tmpfilename = "/encrypted_".$d->get_url_file();
482 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
483 fwrite( $tmpfile, $ciphertext );
484 fclose( $tmpfile );
485 header('Content-Disposition: attachment; filename='.$tmpfilename );
486 header("Content-Type: application/octet-stream" );
487 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
488 ob_clean();
489 flush();
490 readfile( $tmpfilepath.$tmpfilename );
491 unlink( $tmpfilepath.$tmpfilename );
492 } else {
493 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
494 header("Content-Type: " . $d->get_mimetype());
495 header("Content-Length: " . filesize($url));
496 fpassthru($f);
498 exit;
500 else {
501 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
502 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
503 if($couch_docid && $couch_revid){
504 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
506 else{
507 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
509 header("Pragma: public");
510 header("Expires: 0");
511 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
512 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
513 header("Content-Type: image/jpeg");
514 header("Content-Length: " . filesize($url));
515 $f = fopen($url,"r");
516 fpassthru($f);
517 if($couch_docid && $couch_revid){
518 fclose($f);
519 unlink($url);
520 $url=str_replace("_converted.jpg",'.pdf',$url);
521 unlink($url);
523 exit;
528 function queue_action($patient_id="") {
529 $messages = $this->_tpl_vars['messages'];
530 $queue_files = array();
532 //see if the repository exists and it is a directory else error
533 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
534 $dir = opendir($this->_config['repository']);
535 //read each entry in the directory
536 while (($file = readdir($dir)) !== false) {
537 //concat the filename and path
538 $file = $this->_config['repository'] .$file;
539 $file_info = array();
540 //if the filename is a file get its info and put into a tmp array
541 if (is_file($file) && strpos(basename($file),".") !== 0) {
542 $file_info['filename'] = basename($file);
543 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
544 $d = Document::document_factory_url("file://" . $file);
545 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
546 $file_info['patient_id'] = $patient_match[1];
547 $file_info['document_id'] = $d->get_id();
548 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
550 //merge the tmp array into the larger array
551 $queue_files[] = $file_info;
554 closedir($dir);
556 else {
557 $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";
561 $this->assign("queue_files",$queue_files);
562 $this->_last_node = null;
564 $menu = new HTML_TreeMenu();
566 //pass an empty array because we don't want the documents for each category showing up in this list box
567 $rnode = $this->_array_recurse($this->tree->tree,array());
568 $menu->addItem($rnode);
569 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
571 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
573 $this->assign("messages",nl2br($messages));
574 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
577 function queue_action_process() {
578 if ($_POST['process'] != "true")
579 return;
581 $messages = $this->_tpl_vars['messages'];
583 //build a category tree so we can have a list of category ids that are valid
584 $ct = new CategoryTree(1);
585 $categories = $ct->_id_name;
587 //see if there were and posted files and assign them
588 $files = null;
589 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
591 //loop through posted files
592 foreach($files as $doc_id=> $file) {
593 //only operate on files checked as active
594 if (!$file['active']) continue;
596 //run basic validation checks
597 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
598 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
599 continue;
602 //validate that the pod exists
603 $d = new Document($doc_id);
604 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
605 $result = $d->_db->Execute($sql);
607 if (!$result || $result->EOF) {
608 //patient id does not exist
609 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
610 continue;
613 //validate that the category id exists
614 if (!isset($categories[$file['category_id']])) {
615 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
616 continue;
619 //now do the work of moving the file
620 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
622 //see if the patient dir exists in the repository and create if not
623 if (!file_exists($new_path)) {
624 if (!mkdir($new_path,0700)) {
625 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
626 continue;
630 //fname is the name of the file after it is moved
631 $fname = $file['name'];
633 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
634 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
635 if ($patient_match[1] == $file['patient_id']) {
636 $fname = preg_replace("/^([0-9]+)_/","",$fname);
639 //filenames should not have funny chars
640 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
642 //see if there is an existing file with the same name and rename as necessary
643 if (file_exists($new_path.$file['name'])) {
644 $messages .= "File with same name already exists at location: " . $new_path . "\n";
645 $fname = basename($this->_rename_file($new_path.$file['name']));
646 $messages .= "Current file name was changed to " . $fname ."\n";
649 //now move the file
650 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
651 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
652 $d->url = "file://" .$new_path.$fname;
653 $d->set_foreign_id($file['patient_id']);
654 $d->set_mimetype($mimetype);
655 $d->persist();
656 $d->populate();
658 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
659 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
660 $d->_db->Execute($sql);
663 else {
664 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
667 $this->assign("messages",$messages);
668 $_POST['process'] = "";
671 function move_action_process($patient_id="",$document_id) {
672 if ($_POST['process'] != "true")
673 return;
675 $new_category_id = $_POST['new_category_id'];
676 $new_patient_id = $_POST['new_patient_id'];
678 //move to new category
679 if (is_numeric($new_category_id) && is_numeric($document_id)) {
680 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
681 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
682 //echo $sql;
683 $this->tree->_db->Execute($sql);
686 //move to new patient
687 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
688 $d = new Document($document_id);
689 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
690 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
691 $result = $d->_db->Execute($sql);
693 if (!$result || $result->EOF) {
694 //patient id does not exist
695 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
697 else {
699 $couch_docid = $d->get_couch_docid();
700 $couch_revid = $d->get_couch_revid();
701 //set the new patient in CouchDB
702 $couchsavefailed=false;
703 if($couch_docid && $couch_revid){
704 $couch = new CouchDB();
705 $db = $GLOBALS['couchdb_dbase'];
706 $data=array($db,$couch_docid);
707 $couchresp=$couch->retrieve_doc($data);
708 //CouchDB doesnot support updating a single value in a document.
709 //Have to retrieve the entire document,update the necessary value and save again
710 list($db,$docid,$revid,$patient_id,$encounter,$type,$json) = $data;
711 $data=array($db,$couch_docid,$couch_revid,$new_patient_id,$couchresp->encounter,$couchresp->mimetype,json_encode($couchresp->data));
712 $resp = $couch->update_doc($data);
713 //Sometimes the response from CouchDB is not available
714 //still it would have saved in the DB. Hence check one more time
715 if(!$resp->_id || !$resp->_rev){
716 $data = array($db,$couch_docid,$new_patient_id,$couchresp->encounter);
717 $resp = $couch->retrieve_doc($data);
721 if($resp->_rev ==$couch_revid){
722 $couchsavefailed=true;
724 else{
725 $d->set_couch_revid($resp->_rev);
730 //set the new patient in mysql
731 $d->set_foreign_id($new_patient_id);
732 $d->persist();
733 $this->_state = false;
734 if(!$couchsavefailed){
736 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
738 else{
740 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
742 $this->assign("messages",$messages);
743 return $this->list_action($patient_id);
746 //in this case return the document to the queue instead of moving it
747 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
748 $d = new Document($document_id);
749 $new_path = $this->_config['repository'];
750 $fname = $d->get_url_file();
752 //see if there is an existing file with the same name and rename as necessary
753 if (file_exists($new_path.$d->get_url_file())) {
754 $messages .= "File with same name already exists in the queue.\n";
755 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
756 $messages .= "Current file name was changed to " . $fname ."\n";
759 //now move the file
760 if (rename($d->get_url_filepath(),$new_path.$fname)) {
761 $d->url = "file://" .$new_path.$fname;
762 $d->set_foreign_id("");
763 $d->persist();
764 $d->persist();
765 $d->populate();
767 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
768 $d->_db->Execute($sql);
769 $messages .= "Document returned to queue successfully.\n";
772 else {
773 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
776 $this->_state = false;
777 $this->assign("messages",$messages);
778 return $this->list_action($patient_id);
781 $this->_state = false;
782 $this->assign("messages",$messages);
783 return $this->view_action($patient_id,$document_id);
786 function validate_action_process($patient_id="", $document_id) {
788 $d = new Document($document_id);
789 if($d->couch_docid && $d->couch_revid){
790 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
791 $url = $file_path.$d->get_url();
792 $couch = new CouchDB();
793 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
794 $resp = $couch->retrieve_doc($data);
795 $content = $resp->data;
796 //--------Temporarily writing the file for calculating the hash--------//
797 //-----------Will be removed after calculating the hash value----------//
798 $temp_file = fopen($url,"w");
799 fwrite($temp_file,base64_decode($content));
800 fclose($temp_file);
802 else{
803 $url = $d->get_url();
805 //strip url of protocol handler
806 $url = preg_replace("|^(.*)://|","",$url);
808 //change full path to current webroot. this is for documents that may have
809 //been moved from a different filesystem and the full path in the database
810 //is not current. this is also for documents that may of been moved to
811 //different patients
812 // NOTE that $from_filename and basename($url) are the same thing
813 $from_all = explode("/",$url);
814 $from_filename = array_pop($from_all);
815 $from_patientid = array_pop($from_all);
816 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
817 if (file_exists($temp_url)) {
818 $url = $temp_url;
821 if ($_POST['process'] != "true") {
822 die("process is '" . $_POST['process'] . "', expected 'true'");
823 return;
826 $d = new Document( $document_id );
827 $current_hash = sha1_file( $url );
828 $messages = xl('Current Hash').": ".$current_hash."<br>";
829 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
830 if ( $d->get_hash() == '' ) {
831 $d->hash = $current_hash;
832 $d->persist();
833 $d->populate();
834 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
835 } else if ( $current_hash != $d->get_hash() ) {
836 $messages .= xl('Hash does not match. Data integrity has been compromised.');
837 } else {
838 $messages .= xl('Document passed integrity check.');
840 $this->_state = false;
841 $this->assign("messages", $messages);
842 if($d->couch_docid && $d->couch_revid){
843 //Removing the temporary file which is used to create the hash
844 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
846 return $this->view_action($patient_id, $document_id);
849 // Added by Rod for metadata update.
851 function update_action_process($patient_id="", $document_id) {
853 if ($_POST['process'] != "true") {
854 die("process is '" . $_POST['process'] . "', expected 'true'");
855 return;
858 $docdate = $_POST['docdate'];
859 $docname = $_POST['docname'];
860 $issue_id = $_POST['issue_id'];
862 if (is_numeric($document_id)) {
863 $messages = '';
864 $d = new Document( $document_id );
865 $file_name = $d->get_url_file();
866 if ( $docname != '' &&
867 $docname != $file_name ) {
868 $path = $d->get_url_filepath();
869 $path = str_replace( $file_name, "", $path );
870 $new_url = $this->_rename_file( $path.$docname );
871 if ( rename( $d->get_url(), $new_url ) ) {
872 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
873 $url = preg_replace("|^(.*)://|","",$d->get_url());
874 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
875 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
876 if ( file_exists( $url ) ) {
877 unlink( $url );
879 $d->url = $new_url;
880 $d->persist();
881 $d->populate();
882 $messages .= xl('Document successfully renamed.')."<br>";
883 } else {
884 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
888 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
889 $docdate = "'$docdate'";
890 } else {
891 $docdate = "NULL";
893 if (!is_numeric($issue_id)) {
894 $issue_id = 0;
896 $couch_docid = $d->get_couch_docid();
897 $couch_revid = $d->get_couch_revid();
898 if($couch_docid && $couch_revid ){
899 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
900 "list_id = '$issue_id' " .
901 "WHERE id = '$document_id'";
902 $this->tree->_db->Execute($sql);
905 else{
906 $sql = "UPDATE documents SET docdate = $docdate, " .
907 "list_id = '$issue_id' " .
908 "WHERE id = '$document_id'";
909 $this->tree->_db->Execute($sql);
911 $messages .= xl('Document date and issue updated successfully') . "<br>";
914 $this->_state = false;
915 $this->assign("messages", $messages);
916 return $this->view_action($patient_id, $document_id);
919 function list_action($patient_id = "") {
920 $this->_last_node = null;
921 $categories_list = $this->tree->_get_categories_array($patient_id);
922 //print_r($categories_list);
924 $menu = new HTML_TreeMenu();
925 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
926 $menu->addItem($rnode);
927 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
928 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
930 $this->assign("tree_html",$treeMenu->toHTML());
932 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
936 * This is a recursive function to rename a file to something that doesn't already exist.
937 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
938 * to ensure documents opened correctly by external browser viewers. If the counter is at the
939 * end of the file, then will use it (to continue to work with older files), however all new
940 * counters will be placed within filenames.
942 function _rename_file($fname) {
943 $file = basename($fname);
944 $fparts = split("\.",$fname);
945 $path = dirname($fname);
946 if (count($fparts) > 1) {
947 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
948 //increment the counter in filename
949 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
950 $fname = join(".",$fparts);
952 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
953 //increment counter at end of filename (so compatible with previous openemr version files
954 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
955 $fname = join(".",$fparts);
957 elseif (is_numeric($fparts[count($fparts) -1])) {
958 //leave date at end and place counter in filename
959 array_splice($fparts, -1, 0, "1");
960 $fname = join(".",$fparts);
962 else {
963 //add the counter to filename
964 array_splice($fparts, -1, 0, "1");
965 $fname = join(".",$fparts);
968 else { // (count($fparts) == 1)
969 //place counter at end of filename
970 array_push($fparts,"1");
971 $fname = join(".",$fparts);
974 if (file_exists($fname)) {
975 return $this->_rename_file($fname);
977 else {
978 return($fname);
982 function &_array_recurse($array,$categories = array()) {
983 if (!is_array($array)) {
984 $array = array();
986 $node = &$this->_last_node;
987 $current_node = &$node;
988 $expandedIcon = 'folder-expanded.gif';
989 foreach($array as $id => $ar) {
990 $icon = 'folder.gif';
991 if (is_array($ar) || !empty($id)) {
992 if ($node == null) {
993 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
994 $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));
995 $this->_last_node = &$rnode;
996 $node = &$rnode;
997 $current_node =&$rnode;
999 else {
1000 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1001 $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)));
1002 $current_node =&$this->_last_node;
1005 $this->_array_recurse($ar,$categories);
1007 else {
1008 if ($id === 0 && !empty($ar)) {
1009 $info = $this->tree->get_node_info($id);
1010 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1011 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1013 else {
1014 //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
1015 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1016 if ($id !== 0 && is_object($node)) {
1017 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1018 $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)));
1024 // If there are documents in this document category, then add their
1025 // attributes to the current node.
1026 $icon = "file3.png";
1027 if (is_array($categories[$id])) {
1028 foreach ($categories[$id] as $doc) {
1029 if($this->tree->get_node_name($id) == "CCR"){
1030 $current_node->addItem(new HTML_TreeNode(array(
1031 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1032 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1033 'icon' => $icon,
1034 'expandedIcon' => $expandedIcon,
1035 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1036 )));
1037 }elseif($this->tree->get_node_name($id) == "CCD"){
1038 $current_node->addItem(new HTML_TreeNode(array(
1039 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1040 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1041 'icon' => $icon,
1042 'expandedIcon' => $expandedIcon,
1043 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1044 )));
1045 }else{
1046 $current_node->addItem(new HTML_TreeNode(array(
1047 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1048 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1049 'icon' => $icon,
1050 'expandedIcon' => $expandedIcon
1051 )));
1057 return $node;
1060 //function for logging the errors in writing file to CouchDB/Hard Disk
1061 function document_upload_download_log($patientid,$content){
1062 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1063 $log_file = 'log.txt';
1064 if(!is_dir($log_path))
1065 mkdir($log_path,0777,true);
1066 $LOG = fopen($log_path.$log_file,'a');
1067 fwrite($LOG,$content);
1068 fclose($LOG);
1072 //place to hold optional code
1073 //$first_node = array_keys($t->tree);
1074 //$first_node = $first_node[0];
1075 //$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')"));
1077 //$this->_last_node = &$node1;