Fix for previous commit to work when uploading encrypted files to couchdb
[openemr.git] / controllers / C_Document.class.php
blobb5d4049706389ffead8351af5cba329f6e0b40aa
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 function upload_action_process() {
60 $couchDB = false;
61 $harddisk = false;
62 if($GLOBALS['document_storage_method']==0){
63 $harddisk = true;
65 if($GLOBALS['document_storage_method']==1){
66 $couchDB = true;
69 if ($_POST['process'] != "true")
70 return;
72 $doDecryption = false;
73 $encrypted = $_POST['encrypted'];
74 $passphrase = $_POST['passphrase'];
75 if ( !$GLOBALS['hide_document_encryption'] &&
76 $encrypted && $passphrase ) {
77 $doDecryption = true;
80 if (is_numeric($_POST['category_id'])) {
81 $category_id = $_POST['category_id'];
83 if (is_numeric($_POST['patient_id'])) {
84 $patient_id = $_POST['patient_id'];
87 $sentUploadStatus = array();
88 if( count($_FILES['file']['name']) > 0){
89 $upl_inc = 0;
90 foreach($_FILES['file']['name'] as $key => $value){
91 $fname = $value;
92 $err = "";
93 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
94 $fname = $value;
95 if (empty($fname)) {
96 $fname = htmlentities("<empty>");
98 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
99 if ($_FILES['file']['size'][$key] == 0) {
100 $error .= "The system does not permit uploading files of with size 0.\n";
102 }else{
104 if (!file_exists($this->file_path)) {
105 if (!mkdir($this->file_path,0700)) {
106 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
110 if ( $_POST['destination'] != '' ) {
111 $fname = $_POST['destination'];
113 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
114 if (file_exists($this->file_path.$fname)) {
115 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
116 $fname = basename($this->_rename_file($this->file_path.$fname));
117 $_FILES['file']['name'][$key] = $fname;
118 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
121 if ( $doDecryption ) {
122 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key] , "r" );
123 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
124 $plaintext = $this->decrypt( $filetext, $passphrase );
125 fclose($tmpfile);
126 unlink( $_FILES['file']['tmp_name'][$key] );
127 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
128 fwrite( $tmpfile, $plaintext );
129 fclose( $tmpfile );
130 $_FILES['file']['size'][$key] = filesize( $_FILES['file']['tmp_name'][$key] );
133 $docid = '';
134 $resp = '';
135 if($couchDB == true){
136 $couch = new CouchDB();
137 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
138 $docid = $couch->stringToId($docname);
139 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "rb" );
140 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
141 fclose( $tmpfile );
142 //--------Temporarily writing the file for calculating the hash--------//
143 //-----------Will be removed after calculating the hash value----------//
144 $temp_file = fopen($this->file_path.$fname,"w");
145 fwrite($temp_file,$filetext);
146 fclose($temp_file);
147 //---------------------------------------------------------------------//
149 $json = json_encode(base64_encode($filetext));
150 $db = $GLOBALS['couchdb_dbase'];
151 $data = array($db,$docid,$patient_id,$encounter,$_FILES['file']['type'][$key],$json);
152 $resp = $couch->check_saveDOC($data);
153 if(!$resp->id || !$resp->_rev){
154 $data = array($db,$docid,$patient_id,$encounter);
155 $resp = $couch->retrieve_doc($data);
156 $docid = $resp->_id;
157 $revid = $resp->_rev;
159 else{
160 $docid = $resp->id;
161 $revid = $resp->rev;
163 if(!$docid && !$revid){ //if couchdb save failed
164 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
165 if($GLOBALS['couchdb_log']==1){
166 ob_start();
167 var_dump($resp);
168 $couchError=ob_get_clean();
169 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
170 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
171 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
172 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
173 $log_content .= $couchError;
174 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
179 if($harddisk == true){
180 $uploadSuccess = false;
181 if(move_uploaded_file($_FILES['file']['tmp_name'][$key],$this->file_path.$fname)){
182 $uploadSuccess = true;
184 else{
185 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
189 $this->assign("upload_success", "true");
190 $d = new Document();
191 $d->storagemethod = $GLOBALS['document_storage_method'];
192 if($harddisk == true)
193 $d->url = "file://" .$this->file_path.$fname;
194 else
195 $d->url = $fname;
196 if($couchDB == true){
197 $d->couch_docid = $docid;
198 $d->couch_revid = $revid;
200 if ($_FILES['file']['type'][$key] == 'text/xml') {
201 $d->mimetype = 'application/xml';
203 else {
204 $d->mimetype = $_FILES['file']['type'][$key];
206 $d->size = $_FILES['file']['size'][$key];
207 $d->owner = $_SESSION['authUserID'];
208 $sha1Hash = sha1_file( $this->file_path.$fname );
209 if($couchDB == true){
210 //Removing the temporary file which is used to create the hash
211 unlink($this->file_path.$fname);
213 $d->hash = $sha1Hash;
214 $d->type = $d->type_array['file_url'];
215 $d->set_foreign_id($patient_id);
216 if($harddisk == true || ($couchDB == true && $docid && $revid)){
217 $d->persist();
218 $d->populate();
220 $sentUploadStatus[] = $d;
221 $this->assign("file",$sentUploadStatus);
223 if (is_numeric($d->get_id()) && is_numeric($category_id)){
224 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
225 $d->_db->Execute($sql);
227 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
228 $log_content .= "\r\n\r\n";
229 $this->document_upload_download_log($patient_id,$log_content);
235 $this->assign("error", nl2br($error));
236 //$this->_state = false;
237 $_POST['process'] = "";
238 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
241 function note_action_process($patient_id) {
243 if ($_POST['process'] != "true")
244 return;
246 $n = new Note();
247 parent::populate_object($n);
248 $n->persist();
250 $this->_state = false;
251 $_POST['process'] = "";
252 return $this->view_action($patient_id,$n->get_foreign_id());
255 function default_action() {
256 return $this->list_action();
259 function view_action($patient_id="",$doc_id) {
260 // Added by Rod to support document delete:
261 global $gacl_object, $phpgacl_location;
262 global $ISSUE_TYPES;
264 require_once(dirname(__FILE__) . "/../library/acl.inc");
265 require_once(dirname(__FILE__) . "/../library/lists.inc");
267 $d = new Document($doc_id);
268 $n = new Note();
270 $notes = $n->notes_factory($doc_id);
272 $this->assign("file", $d);
273 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
274 $this->assign("NOTE_ACTION",$this->_link("note"));
275 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
276 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
278 // Added by Rod to support document delete:
279 $delete_string = '';
280 if (acl_check('admin', 'super')) {
281 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
282 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
284 $this->assign("delete_string", $delete_string);
285 $this->assign("REFRESH_ACTION",$this->_link("list"));
287 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
288 "document_id=" . $d->get_id() . "&process=true");
290 // Added by Rod to support document date update:
291 $this->assign("DOCDATE", $d->get_docdate());
292 $this->assign("UPDATE_ACTION",$this->_link("update") .
293 "document_id=" . $d->get_id() . "&process=true");
295 // Added by Rod to support document issue update:
296 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
297 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
298 "pid = $patient_id " . // AND enddate IS NULL " .
299 "ORDER BY type, begdate");
300 while ($irow = sqlFetchArray($ires)) {
301 $desc = $irow['type'];
302 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
303 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
304 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
305 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
307 $this->assign("ISSUES_LIST", $issues_options);
309 $this->assign("notes",$notes);
311 $this->_last_node = null;
313 $menu = new HTML_TreeMenu();
315 //pass an empty array because we don't want the documents for each category showing up in this list box
316 $rnode = $this->_array_recurse($this->tree->tree,array());
317 $menu->addItem($rnode);
318 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
320 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
322 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
323 $this->assign("activity", $activity);
325 return $this->list_action($patient_id);
328 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
330 $td = mcrypt_module_open( $cypher, '', $mode, '');
331 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
332 mcrypt_generic_init( $td, $key, $iv );
333 $crypttext = mcrypt_generic( $td, $plaintext );
334 mcrypt_generic_deinit( $td );
335 return $iv.$crypttext;
338 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
340 $plaintext = '';
341 $td = mcrypt_module_open( $cypher, '', $mode, '' );
342 $ivsize = mcrypt_enc_get_iv_size( $td) ;
343 $iv = substr( $crypttext, 0, $ivsize );
344 $crypttext = substr( $crypttext, $ivsize );
345 if( $iv )
347 mcrypt_generic_init( $td, $key, $iv );
348 $plaintext = mdecrypt_generic( $td, $crypttext );
350 return $plaintext;
354 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
356 $encrypted = $_POST['encrypted'];
357 $passphrase = $_POST['passphrase'];
358 $doEncryption = false;
359 if ( !$GLOBALS['hide_document_encryption'] &&
360 $encrypted == "true" &&
361 $passphrase ) {
362 $doEncryption = true;
365 //controller function ruins booleans, so need to manually re-convert to booleans
366 if ($as_file == "true") {
367 $as_file=true;
369 else if ($as_file == "false") {
370 $as_file=false;
372 if ($original_file == "true") {
373 $original_file=true;
375 else if ($original_file == "false") {
376 $original_file=false;
379 $d = new Document($document_id);
380 $url = $d->get_url();
381 $storagemethod = $d->get_storagemethod();
382 $couch_docid = $d->get_couch_docid();
383 $couch_revid = $d->get_couch_revid();
385 if($couch_docid && $couch_revid && $original_file){
386 $couch = new CouchDB();
387 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
388 $resp = $couch->retrieve_doc($data);
389 $content = $resp->data;
390 if($content=='' && $GLOBALS['couchdb_log']==1){
391 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
392 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
393 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
394 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
395 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
396 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
397 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
398 die(xl("File retrieval from CouchDB failed"));
400 header('Content-Description: File Transfer');
401 header('Content-Transfer-Encoding: binary');
402 header('Expires: 0');
403 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
404 header('Pragma: public');
405 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
406 $fh = fopen($tmpcouchpath,"w");
407 fwrite($fh,base64_decode($content));
408 fclose($fh);
409 $f = fopen($tmpcouchpath,"r");
410 if ( $doEncryption ) {
411 $filetext = fread( $f, filesize($tmpcouchpath) );
412 $ciphertext = $this->encrypt( $filetext, $passphrase );
413 $tmpfilepath = $GLOBALS['temporary_files_dir'];
414 $tmpfilename = "/encrypted_".$d->get_url_file();
415 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
416 fwrite( $tmpfile, $ciphertext );
417 fclose( $tmpfile );
418 header('Content-Disposition: attachment; filename='.$tmpfilename );
419 header("Content-Type: application/octet-stream" );
420 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
421 ob_clean();
422 flush();
423 readfile( $tmpfilepath.$tmpfilename );
424 unlink( $tmpfilepath.$tmpfilename );
425 } else {
426 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
427 header("Content-Type: " . $d->get_mimetype());
428 header("Content-Length: " . filesize($tmpcouchpath));
429 fpassthru($f);
431 fclose($f);
432 if($content!='')
433 unlink($tmpcouchpath);
434 exit;//exits only if file download from CouchDB is successfull.
436 //strip url of protocol handler
437 $url = preg_replace("|^(.*)://|","",$url);
439 //change full path to current webroot. this is for documents that may have
440 //been moved from a different filesystem and the full path in the database
441 //is not current. this is also for documents that may of been moved to
442 //different patients
443 // NOTE that $from_filename and basename($url) are the same thing
444 $from_all = explode("/",$url);
445 $from_filename = array_pop($from_all);
446 $from_patientid = array_pop($from_all);
447 if($couch_docid && $couch_revid){
448 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
449 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
452 else{
453 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
456 if (file_exists($temp_url)) {
457 $url = $temp_url;
461 if (!file_exists($url)) {
462 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;
465 else {
466 if ($original_file) {
467 //normal case when serving the file referenced in database
468 header('Content-Description: File Transfer');
469 header('Content-Transfer-Encoding: binary');
470 header('Expires: 0');
471 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
472 header('Pragma: public');
473 $f = fopen($url,"r");
474 if ( $doEncryption ) {
475 $filetext = fread( $f, filesize($url) );
476 $ciphertext = $this->encrypt( $filetext, $passphrase );
477 $tmpfilepath = $GLOBALS['temporary_files_dir'];
478 $tmpfilename = "/encrypted_".$d->get_url_file();
479 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
480 fwrite( $tmpfile, $ciphertext );
481 fclose( $tmpfile );
482 header('Content-Disposition: attachment; filename='.$tmpfilename );
483 header("Content-Type: application/octet-stream" );
484 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
485 ob_clean();
486 flush();
487 readfile( $tmpfilepath.$tmpfilename );
488 unlink( $tmpfilepath.$tmpfilename );
489 } else {
490 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
491 header("Content-Type: " . $d->get_mimetype());
492 header("Content-Length: " . filesize($url));
493 fpassthru($f);
495 exit;
497 else {
498 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
499 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
500 if($couch_docid && $couch_revid){
501 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
503 else{
504 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
506 header("Pragma: public");
507 header("Expires: 0");
508 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
509 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
510 header("Content-Type: image/jpeg");
511 header("Content-Length: " . filesize($url));
512 $f = fopen($url,"r");
513 fpassthru($f);
514 if($couch_docid && $couch_revid){
515 fclose($f);
516 unlink($url);
517 $url=str_replace("_converted.jpg",'.pdf',$url);
518 unlink($url);
520 exit;
525 function queue_action($patient_id="") {
526 $messages = $this->_tpl_vars['messages'];
527 $queue_files = array();
529 //see if the repository exists and it is a directory else error
530 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
531 $dir = opendir($this->_config['repository']);
532 //read each entry in the directory
533 while (($file = readdir($dir)) !== false) {
534 //concat the filename and path
535 $file = $this->_config['repository'] .$file;
536 $file_info = array();
537 //if the filename is a file get its info and put into a tmp array
538 if (is_file($file) && strpos(basename($file),".") !== 0) {
539 $file_info['filename'] = basename($file);
540 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
541 $d = Document::document_factory_url("file://" . $file);
542 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
543 $file_info['patient_id'] = $patient_match[1];
544 $file_info['document_id'] = $d->get_id();
545 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
547 //merge the tmp array into the larger array
548 $queue_files[] = $file_info;
551 closedir($dir);
553 else {
554 $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";
558 $this->assign("queue_files",$queue_files);
559 $this->_last_node = null;
561 $menu = new HTML_TreeMenu();
563 //pass an empty array because we don't want the documents for each category showing up in this list box
564 $rnode = $this->_array_recurse($this->tree->tree,array());
565 $menu->addItem($rnode);
566 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
568 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
570 $this->assign("messages",nl2br($messages));
571 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
574 function queue_action_process() {
575 if ($_POST['process'] != "true")
576 return;
578 $messages = $this->_tpl_vars['messages'];
580 //build a category tree so we can have a list of category ids that are valid
581 $ct = new CategoryTree(1);
582 $categories = $ct->_id_name;
584 //see if there were and posted files and assign them
585 $files = null;
586 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
588 //loop through posted files
589 foreach($files as $doc_id=> $file) {
590 //only operate on files checked as active
591 if (!$file['active']) continue;
593 //run basic validation checks
594 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
595 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
596 continue;
599 //validate that the pod exists
600 $d = new Document($doc_id);
601 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
602 $result = $d->_db->Execute($sql);
604 if (!$result || $result->EOF) {
605 //patient id does not exist
606 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
607 continue;
610 //validate that the category id exists
611 if (!isset($categories[$file['category_id']])) {
612 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
613 continue;
616 //now do the work of moving the file
617 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
619 //see if the patient dir exists in the repository and create if not
620 if (!file_exists($new_path)) {
621 if (!mkdir($new_path,0700)) {
622 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
623 continue;
627 //fname is the name of the file after it is moved
628 $fname = $file['name'];
630 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
631 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
632 if ($patient_match[1] == $file['patient_id']) {
633 $fname = preg_replace("/^([0-9]+)_/","",$fname);
636 //filenames should not have funny chars
637 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
639 //see if there is an existing file with the same name and rename as necessary
640 if (file_exists($new_path.$file['name'])) {
641 $messages .= "File with same name already exists at location: " . $new_path . "\n";
642 $fname = basename($this->_rename_file($new_path.$file['name']));
643 $messages .= "Current file name was changed to " . $fname ."\n";
646 //now move the file
647 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
648 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
649 $d->url = "file://" .$new_path.$fname;
650 $d->set_foreign_id($file['patient_id']);
651 $d->set_mimetype($mimetype);
652 $d->persist();
653 $d->populate();
655 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
656 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
657 $d->_db->Execute($sql);
660 else {
661 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
664 $this->assign("messages",$messages);
665 $_POST['process'] = "";
668 function move_action_process($patient_id="",$document_id) {
669 if ($_POST['process'] != "true")
670 return;
672 $new_category_id = $_POST['new_category_id'];
673 $new_patient_id = $_POST['new_patient_id'];
675 //move to new category
676 if (is_numeric($new_category_id) && is_numeric($document_id)) {
677 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
678 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
679 //echo $sql;
680 $this->tree->_db->Execute($sql);
683 //move to new patient
684 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
685 $d = new Document($document_id);
686 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
687 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
688 $result = $d->_db->Execute($sql);
690 if (!$result || $result->EOF) {
691 //patient id does not exist
692 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
694 else {
696 $couch_docid = $d->get_couch_docid();
697 $couch_revid = $d->get_couch_revid();
698 //set the new patient in CouchDB
699 $couchsavefailed=false;
700 if($couch_docid && $couch_revid){
701 $couch = new CouchDB();
702 $db = $GLOBALS['couchdb_dbase'];
703 $data=array($db,$couch_docid);
704 $couchresp=$couch->retrieve_doc($data);
705 //CouchDB doesnot support updating a single value in a document.
706 //Have to retrieve the entire document,update the necessary value and save again
707 list($db,$docid,$revid,$patient_id,$encounter,$type,$json) = $data;
708 $data=array($db,$couch_docid,$couch_revid,$new_patient_id,$couchresp->encounter,$couchresp->mimetype,json_encode($couchresp->data));
709 $resp = $couch->update_doc($data);
710 //Sometimes the response from CouchDB is not available
711 //still it would have saved in the DB. Hence check one more time
712 if(!$resp->_id || !$resp->_rev){
713 $data = array($db,$couch_docid,$new_patient_id,$couchresp->encounter);
714 $resp = $couch->retrieve_doc($data);
718 if($resp->_rev ==$couch_revid){
719 $couchsavefailed=true;
721 else{
722 $d->set_couch_revid($resp->_rev);
727 //set the new patient in mysql
728 $d->set_foreign_id($new_patient_id);
729 $d->persist();
730 $this->_state = false;
731 if(!$couchsavefailed){
733 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
735 else{
737 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
739 $this->assign("messages",$messages);
740 return $this->list_action($patient_id);
743 //in this case return the document to the queue instead of moving it
744 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
745 $d = new Document($document_id);
746 $new_path = $this->_config['repository'];
747 $fname = $d->get_url_file();
749 //see if there is an existing file with the same name and rename as necessary
750 if (file_exists($new_path.$d->get_url_file())) {
751 $messages .= "File with same name already exists in the queue.\n";
752 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
753 $messages .= "Current file name was changed to " . $fname ."\n";
756 //now move the file
757 if (rename($d->get_url_filepath(),$new_path.$fname)) {
758 $d->url = "file://" .$new_path.$fname;
759 $d->set_foreign_id("");
760 $d->persist();
761 $d->persist();
762 $d->populate();
764 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
765 $d->_db->Execute($sql);
766 $messages .= "Document returned to queue successfully.\n";
769 else {
770 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
773 $this->_state = false;
774 $this->assign("messages",$messages);
775 return $this->list_action($patient_id);
778 $this->_state = false;
779 $this->assign("messages",$messages);
780 return $this->view_action($patient_id,$document_id);
783 function validate_action_process($patient_id="", $document_id) {
785 $d = new Document($document_id);
786 if($d->couch_docid && $d->couch_revid){
787 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
788 $url = $file_path.$d->get_url();
789 $couch = new CouchDB();
790 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
791 $resp = $couch->retrieve_doc($data);
792 $content = $resp->data;
793 //--------Temporarily writing the file for calculating the hash--------//
794 //-----------Will be removed after calculating the hash value----------//
795 $temp_file = fopen($url,"w");
796 fwrite($temp_file,base64_decode($content));
797 fclose($temp_file);
799 else{
800 $url = $d->get_url();
802 //strip url of protocol handler
803 $url = preg_replace("|^(.*)://|","",$url);
805 //change full path to current webroot. this is for documents that may have
806 //been moved from a different filesystem and the full path in the database
807 //is not current. this is also for documents that may of been moved to
808 //different patients
809 // NOTE that $from_filename and basename($url) are the same thing
810 $from_all = explode("/",$url);
811 $from_filename = array_pop($from_all);
812 $from_patientid = array_pop($from_all);
813 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
814 if (file_exists($temp_url)) {
815 $url = $temp_url;
818 if ($_POST['process'] != "true") {
819 die("process is '" . $_POST['process'] . "', expected 'true'");
820 return;
823 $d = new Document( $document_id );
824 $current_hash = sha1_file( $url );
825 $messages = xl('Current Hash').": ".$current_hash."<br>";
826 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
827 if ( $d->get_hash() == '' ) {
828 $d->hash = $current_hash;
829 $d->persist();
830 $d->populate();
831 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
832 } else if ( $current_hash != $d->get_hash() ) {
833 $messages .= xl('Hash does not match. Data integrity has been compromised.');
834 } else {
835 $messages .= xl('Document passed integrity check.');
837 $this->_state = false;
838 $this->assign("messages", $messages);
839 if($d->couch_docid && $d->couch_revid){
840 //Removing the temporary file which is used to create the hash
841 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
843 return $this->view_action($patient_id, $document_id);
846 // Added by Rod for metadata update.
848 function update_action_process($patient_id="", $document_id) {
850 if ($_POST['process'] != "true") {
851 die("process is '" . $_POST['process'] . "', expected 'true'");
852 return;
855 $docdate = $_POST['docdate'];
856 $docname = $_POST['docname'];
857 $issue_id = $_POST['issue_id'];
859 if (is_numeric($document_id)) {
860 $messages = '';
861 $d = new Document( $document_id );
862 $file_name = $d->get_url_file();
863 if ( $docname != '' &&
864 $docname != $file_name ) {
865 $path = $d->get_url_filepath();
866 $path = str_replace( $file_name, "", $path );
867 $new_url = $this->_rename_file( $path.$docname );
868 if ( rename( $d->get_url(), $new_url ) ) {
869 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
870 $url = preg_replace("|^(.*)://|","",$d->get_url());
871 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
872 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
873 if ( file_exists( $url ) ) {
874 unlink( $url );
876 $d->url = $new_url;
877 $d->persist();
878 $d->populate();
879 $messages .= xl('Document successfully renamed.')."<br>";
880 } else {
881 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
885 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
886 $docdate = "'$docdate'";
887 } else {
888 $docdate = "NULL";
890 if (!is_numeric($issue_id)) {
891 $issue_id = 0;
893 $couch_docid = $d->get_couch_docid();
894 $couch_revid = $d->get_couch_revid();
895 if($couch_docid && $couch_revid ){
896 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
897 "list_id = '$issue_id' " .
898 "WHERE id = '$document_id'";
899 $this->tree->_db->Execute($sql);
902 else{
903 $sql = "UPDATE documents SET docdate = $docdate, " .
904 "list_id = '$issue_id' " .
905 "WHERE id = '$document_id'";
906 $this->tree->_db->Execute($sql);
908 $messages .= xl('Document date and issue updated successfully') . "<br>";
911 $this->_state = false;
912 $this->assign("messages", $messages);
913 return $this->view_action($patient_id, $document_id);
916 function list_action($patient_id = "") {
917 $this->_last_node = null;
918 $categories_list = $this->tree->_get_categories_array($patient_id);
919 //print_r($categories_list);
921 $menu = new HTML_TreeMenu();
922 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
923 $menu->addItem($rnode);
924 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
925 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
927 $this->assign("tree_html",$treeMenu->toHTML());
929 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
933 * This is a recursive function to rename a file to something that doesn't already exist.
934 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
935 * to ensure documents opened correctly by external browser viewers. If the counter is at the
936 * end of the file, then will use it (to continue to work with older files), however all new
937 * counters will be placed within filenames.
939 function _rename_file($fname) {
940 $file = basename($fname);
941 $fparts = split("\.",$fname);
942 $path = dirname($fname);
943 if (count($fparts) > 1) {
944 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
945 //increment the counter in filename
946 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
947 $fname = join(".",$fparts);
949 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
950 //increment counter at end of filename (so compatible with previous openemr version files
951 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
952 $fname = join(".",$fparts);
954 elseif (is_numeric($fparts[count($fparts) -1])) {
955 //leave date at end and place counter in filename
956 array_splice($fparts, -1, 0, "1");
957 $fname = join(".",$fparts);
959 else {
960 //add the counter to filename
961 array_splice($fparts, -1, 0, "1");
962 $fname = join(".",$fparts);
965 else { // (count($fparts) == 1)
966 //place counter at end of filename
967 array_push($fparts,"1");
968 $fname = join(".",$fparts);
971 if (file_exists($fname)) {
972 return $this->_rename_file($fname);
974 else {
975 return($fname);
979 function &_array_recurse($array,$categories = array()) {
980 if (!is_array($array)) {
981 $array = array();
983 $node = &$this->_last_node;
984 $current_node = &$node;
985 $expandedIcon = 'folder-expanded.gif';
986 foreach($array as $id => $ar) {
987 $icon = 'folder.gif';
988 if (is_array($ar) || !empty($id)) {
989 if ($node == null) {
990 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
991 $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));
992 $this->_last_node = &$rnode;
993 $node = &$rnode;
994 $current_node =&$rnode;
996 else {
997 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
998 $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)));
999 $current_node =&$this->_last_node;
1002 $this->_array_recurse($ar,$categories);
1004 else {
1005 if ($id === 0 && !empty($ar)) {
1006 $info = $this->tree->get_node_info($id);
1007 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1008 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1010 else {
1011 //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
1012 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1013 if ($id !== 0 && is_object($node)) {
1014 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1015 $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)));
1021 // If there are documents in this document category, then add their
1022 // attributes to the current node.
1023 $icon = "file3.png";
1024 if (is_array($categories[$id])) {
1025 foreach ($categories[$id] as $doc) {
1026 if($this->tree->get_node_name($id) == "CCR"){
1027 $current_node->addItem(new HTML_TreeNode(array(
1028 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1029 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1030 'icon' => $icon,
1031 'expandedIcon' => $expandedIcon,
1032 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1033 )));
1034 }elseif($this->tree->get_node_name($id) == "CCD"){
1035 $current_node->addItem(new HTML_TreeNode(array(
1036 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1037 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1038 'icon' => $icon,
1039 'expandedIcon' => $expandedIcon,
1040 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1041 )));
1042 }else{
1043 $current_node->addItem(new HTML_TreeNode(array(
1044 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1045 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1046 'icon' => $icon,
1047 'expandedIcon' => $expandedIcon
1048 )));
1054 return $node;
1057 //function for logging the errors in writing file to CouchDB/Hard Disk
1058 function document_upload_download_log($patientid,$content){
1059 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1060 $log_file = 'log.txt';
1061 if(!is_dir($log_path))
1062 mkdir($log_path,0777,true);
1063 $LOG = fopen($log_path.$log_file,'a');
1064 fwrite($LOG,$content);
1065 fclose($LOG);
1069 //place to hold optional code
1070 //$first_node = array_keys($t->tree);
1071 //$first_node = $first_node[0];
1072 //$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')"));
1074 //$this->_last_node = &$node1;