c032eab0021433a7cc8a877884210519d95fa8db
[openemr.git] / controllers / C_Document.class.php
blobc032eab0021433a7cc8a877884210519d95fa8db
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 unlink( $_FILES['file']['tmp_name'][$key] );
126 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
127 fwrite( $tmpfile, $plaintext );
128 fclose( $tmpfile );
129 $_FILES['file']['size'][$key] = filesize( $tmpfilepath.$tmpfilename );
132 $docid = '';
133 $resp = '';
134 if($couchDB == true){
135 $couch = new CouchDB();
136 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
137 $docid = $couch->stringToId($docname);
138 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "rb" );
139 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
140 fclose( $tmpfile );
141 //--------Temporarily writing the file for calculating the hash--------//
142 //-----------Will be removed after calculating the hash value----------//
143 $temp_file = fopen($this->file_path.$fname,"w");
144 fwrite($temp_file,$filetext);
145 fclose($temp_file);
146 //---------------------------------------------------------------------//
148 $json = json_encode(base64_encode($filetext));
149 $db = $GLOBALS['couchdb_dbase'];
150 $data = array($db,$docid,$patient_id,$encounter,$_FILES['file']['type'][$key],$json);
151 $resp = $couch->check_saveDOC($data);
152 if(!$resp->id || !$resp->_rev){
153 $data = array($db,$docid,$patient_id,$encounter);
154 $resp = $couch->retrieve_doc($data);
155 $docid = $resp->_id;
156 $revid = $resp->_rev;
158 else{
159 $docid = $resp->id;
160 $revid = $resp->rev;
162 if(!$docid && !$revid){ //if couchdb save failed
163 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
164 if($GLOBALS['couchdb_log']==1){
165 ob_start();
166 var_dump($resp);
167 $couchError=ob_get_clean();
168 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
169 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
170 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
171 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
172 $log_content .= $couchError;
173 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
178 if($harddisk == true){
179 $uploadSuccess = false;
180 if(move_uploaded_file($_FILES['file']['tmp_name'][$key],$this->file_path.$fname)){
181 $uploadSuccess = true;
183 else{
184 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
188 $this->assign("upload_success", "true");
189 $d = new Document();
190 $d->storagemethod = $GLOBALS['document_storage_method'];
191 if($harddisk == true)
192 $d->url = "file://" .$this->file_path.$fname;
193 else
194 $d->url = $fname;
195 if($couchDB == true){
196 $d->couch_docid = $docid;
197 $d->couch_revid = $revid;
199 if ($_FILES['file']['type'][$key] == 'text/xml') {
200 $d->mimetype = 'application/xml';
202 else {
203 $d->mimetype = $_FILES['file']['type'][$key];
205 $d->size = $_FILES['file']['size'][$key];
206 $d->owner = $_SESSION['authUserID'];
207 $sha1Hash = sha1_file( $this->file_path.$fname );
208 if($couchDB == true){
209 //Removing the temporary file which is used to create the hash
210 unlink($this->file_path.$fname);
212 $d->hash = $sha1Hash;
213 $d->type = $d->type_array['file_url'];
214 $d->set_foreign_id($patient_id);
215 if($harddisk == true || ($couchDB == true && $docid && $revid)){
216 $d->persist();
217 $d->populate();
219 $sentUploadStatus[] = $d;
220 $this->assign("file",$sentUploadStatus);
222 if (is_numeric($d->get_id()) && is_numeric($category_id)){
223 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
224 $d->_db->Execute($sql);
226 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
227 $log_content .= "\r\n\r\n";
228 $this->document_upload_download_log($patient_id,$log_content);
234 $this->assign("error", nl2br($error));
235 //$this->_state = false;
236 $_POST['process'] = "";
237 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
240 function note_action_process($patient_id) {
242 if ($_POST['process'] != "true")
243 return;
245 $n = new Note();
246 parent::populate_object($n);
247 $n->persist();
249 $this->_state = false;
250 $_POST['process'] = "";
251 return $this->view_action($patient_id,$n->get_foreign_id());
254 function default_action() {
255 return $this->list_action();
258 function view_action($patient_id="",$doc_id) {
259 // Added by Rod to support document delete:
260 global $gacl_object, $phpgacl_location;
261 global $ISSUE_TYPES;
263 require_once(dirname(__FILE__) . "/../library/acl.inc");
264 require_once(dirname(__FILE__) . "/../library/lists.inc");
266 $d = new Document($doc_id);
267 $n = new Note();
269 $notes = $n->notes_factory($doc_id);
271 $this->assign("file", $d);
272 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
273 $this->assign("NOTE_ACTION",$this->_link("note"));
274 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
275 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
277 // Added by Rod to support document delete:
278 $delete_string = '';
279 if (acl_check('admin', 'super')) {
280 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
281 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
283 $this->assign("delete_string", $delete_string);
284 $this->assign("REFRESH_ACTION",$this->_link("list"));
286 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
287 "document_id=" . $d->get_id() . "&process=true");
289 // Added by Rod to support document date update:
290 $this->assign("DOCDATE", $d->get_docdate());
291 $this->assign("UPDATE_ACTION",$this->_link("update") .
292 "document_id=" . $d->get_id() . "&process=true");
294 // Added by Rod to support document issue update:
295 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
296 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
297 "pid = $patient_id " . // AND enddate IS NULL " .
298 "ORDER BY type, begdate");
299 while ($irow = sqlFetchArray($ires)) {
300 $desc = $irow['type'];
301 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
302 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
303 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
304 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
306 $this->assign("ISSUES_LIST", $issues_options);
308 $this->assign("notes",$notes);
310 $this->_last_node = null;
312 $menu = new HTML_TreeMenu();
314 //pass an empty array because we don't want the documents for each category showing up in this list box
315 $rnode = $this->_array_recurse($this->tree->tree,array());
316 $menu->addItem($rnode);
317 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
319 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
321 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
322 $this->assign("activity", $activity);
324 return $this->list_action($patient_id);
327 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
329 $td = mcrypt_module_open( $cypher, '', $mode, '');
330 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
331 mcrypt_generic_init( $td, $key, $iv );
332 $crypttext = mcrypt_generic( $td, $plaintext );
333 mcrypt_generic_deinit( $td );
334 return $iv.$crypttext;
337 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
339 $plaintext = '';
340 $td = mcrypt_module_open( $cypher, '', $mode, '' );
341 $ivsize = mcrypt_enc_get_iv_size( $td) ;
342 $iv = substr( $crypttext, 0, $ivsize );
343 $crypttext = substr( $crypttext, $ivsize );
344 if( $iv )
346 mcrypt_generic_init( $td, $key, $iv );
347 $plaintext = mdecrypt_generic( $td, $crypttext );
349 return $plaintext;
353 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
355 $encrypted = $_POST['encrypted'];
356 $passphrase = $_POST['passphrase'];
357 $doEncryption = false;
358 if ( !$GLOBALS['hide_document_encryption'] &&
359 $encrypted == "true" &&
360 $passphrase ) {
361 $doEncryption = true;
364 //controller function ruins booleans, so need to manually re-convert to booleans
365 if ($as_file == "true") {
366 $as_file=true;
368 else if ($as_file == "false") {
369 $as_file=false;
371 if ($original_file == "true") {
372 $original_file=true;
374 else if ($original_file == "false") {
375 $original_file=false;
378 $d = new Document($document_id);
379 $url = $d->get_url();
380 $storagemethod = $d->get_storagemethod();
381 $couch_docid = $d->get_couch_docid();
382 $couch_revid = $d->get_couch_revid();
384 if($couch_docid && $couch_revid && $original_file){
385 $couch = new CouchDB();
386 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
387 $resp = $couch->retrieve_doc($data);
388 $content = $resp->data;
389 if($content=='' && $GLOBALS['couchdb_log']==1){
390 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
391 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
392 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
393 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
394 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
395 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
396 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
397 die(xl("File retrieval from CouchDB failed"));
399 header('Content-Description: File Transfer');
400 header('Content-Transfer-Encoding: binary');
401 header('Expires: 0');
402 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
403 header('Pragma: public');
404 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
405 $fh = fopen($tmpcouchpath,"w");
406 fwrite($fh,base64_decode($content));
407 fclose($fh);
408 $f = fopen($tmpcouchpath,"r");
409 if ( $doEncryption ) {
410 $filetext = fread( $f, filesize($tmpcouchpath) );
411 $ciphertext = $this->encrypt( $filetext, $passphrase );
412 $tmpfilepath = $GLOBALS['temporary_files_dir'];
413 $tmpfilename = "/encrypted_".$d->get_url_file();
414 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
415 fwrite( $tmpfile, $ciphertext );
416 fclose( $tmpfile );
417 header('Content-Disposition: attachment; filename='.$tmpfilename );
418 header("Content-Type: application/octet-stream" );
419 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
420 ob_clean();
421 flush();
422 readfile( $tmpfilepath.$tmpfilename );
423 unlink( $tmpfilepath.$tmpfilename );
424 } else {
425 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
426 header("Content-Type: " . $d->get_mimetype());
427 header("Content-Length: " . filesize($tmpcouchpath));
428 fpassthru($f);
430 fclose($f);
431 if($content!='')
432 unlink($tmpcouchpath);
433 exit;//exits only if file download from CouchDB is successfull.
435 //strip url of protocol handler
436 $url = preg_replace("|^(.*)://|","",$url);
438 //change full path to current webroot. this is for documents that may have
439 //been moved from a different filesystem and the full path in the database
440 //is not current. this is also for documents that may of been moved to
441 //different patients
442 // NOTE that $from_filename and basename($url) are the same thing
443 $from_all = explode("/",$url);
444 $from_filename = array_pop($from_all);
445 $from_patientid = array_pop($from_all);
446 if($couch_docid && $couch_revid){
447 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
448 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
451 else{
452 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
455 if (file_exists($temp_url)) {
456 $url = $temp_url;
460 if (!file_exists($url)) {
461 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;
464 else {
465 if ($original_file) {
466 //normal case when serving the file referenced in database
467 header('Content-Description: File Transfer');
468 header('Content-Transfer-Encoding: binary');
469 header('Expires: 0');
470 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
471 header('Pragma: public');
472 $f = fopen($url,"r");
473 if ( $doEncryption ) {
474 $filetext = fread( $f, filesize($url) );
475 $ciphertext = $this->encrypt( $filetext, $passphrase );
476 $tmpfilepath = $GLOBALS['temporary_files_dir'];
477 $tmpfilename = "/encrypted_".$d->get_url_file();
478 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
479 fwrite( $tmpfile, $ciphertext );
480 fclose( $tmpfile );
481 header('Content-Disposition: attachment; filename='.$tmpfilename );
482 header("Content-Type: application/octet-stream" );
483 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
484 ob_clean();
485 flush();
486 readfile( $tmpfilepath.$tmpfilename );
487 unlink( $tmpfilepath.$tmpfilename );
488 } else {
489 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
490 header("Content-Type: " . $d->get_mimetype());
491 header("Content-Length: " . filesize($url));
492 fpassthru($f);
494 exit;
496 else {
497 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
498 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
499 if($couch_docid && $couch_revid){
500 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
502 else{
503 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
505 header("Pragma: public");
506 header("Expires: 0");
507 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
508 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
509 header("Content-Type: image/jpeg");
510 header("Content-Length: " . filesize($url));
511 $f = fopen($url,"r");
512 fpassthru($f);
513 if($couch_docid && $couch_revid){
514 fclose($f);
515 unlink($url);
516 $url=str_replace("_converted.jpg",'.pdf',$url);
517 unlink($url);
519 exit;
524 function queue_action($patient_id="") {
525 $messages = $this->_tpl_vars['messages'];
526 $queue_files = array();
528 //see if the repository exists and it is a directory else error
529 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
530 $dir = opendir($this->_config['repository']);
531 //read each entry in the directory
532 while (($file = readdir($dir)) !== false) {
533 //concat the filename and path
534 $file = $this->_config['repository'] .$file;
535 $file_info = array();
536 //if the filename is a file get its info and put into a tmp array
537 if (is_file($file) && strpos(basename($file),".") !== 0) {
538 $file_info['filename'] = basename($file);
539 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
540 $d = Document::document_factory_url("file://" . $file);
541 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
542 $file_info['patient_id'] = $patient_match[1];
543 $file_info['document_id'] = $d->get_id();
544 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
546 //merge the tmp array into the larger array
547 $queue_files[] = $file_info;
550 closedir($dir);
552 else {
553 $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";
557 $this->assign("queue_files",$queue_files);
558 $this->_last_node = null;
560 $menu = new HTML_TreeMenu();
562 //pass an empty array because we don't want the documents for each category showing up in this list box
563 $rnode = $this->_array_recurse($this->tree->tree,array());
564 $menu->addItem($rnode);
565 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
567 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
569 $this->assign("messages",nl2br($messages));
570 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
573 function queue_action_process() {
574 if ($_POST['process'] != "true")
575 return;
577 $messages = $this->_tpl_vars['messages'];
579 //build a category tree so we can have a list of category ids that are valid
580 $ct = new CategoryTree(1);
581 $categories = $ct->_id_name;
583 //see if there were and posted files and assign them
584 $files = null;
585 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
587 //loop through posted files
588 foreach($files as $doc_id=> $file) {
589 //only operate on files checked as active
590 if (!$file['active']) continue;
592 //run basic validation checks
593 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
594 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
595 continue;
598 //validate that the pod exists
599 $d = new Document($doc_id);
600 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
601 $result = $d->_db->Execute($sql);
603 if (!$result || $result->EOF) {
604 //patient id does not exist
605 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
606 continue;
609 //validate that the category id exists
610 if (!isset($categories[$file['category_id']])) {
611 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
612 continue;
615 //now do the work of moving the file
616 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
618 //see if the patient dir exists in the repository and create if not
619 if (!file_exists($new_path)) {
620 if (!mkdir($new_path,0700)) {
621 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
622 continue;
626 //fname is the name of the file after it is moved
627 $fname = $file['name'];
629 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
630 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
631 if ($patient_match[1] == $file['patient_id']) {
632 $fname = preg_replace("/^([0-9]+)_/","",$fname);
635 //filenames should not have funny chars
636 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
638 //see if there is an existing file with the same name and rename as necessary
639 if (file_exists($new_path.$file['name'])) {
640 $messages .= "File with same name already exists at location: " . $new_path . "\n";
641 $fname = basename($this->_rename_file($new_path.$file['name']));
642 $messages .= "Current file name was changed to " . $fname ."\n";
645 //now move the file
646 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
647 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
648 $d->url = "file://" .$new_path.$fname;
649 $d->set_foreign_id($file['patient_id']);
650 $d->set_mimetype($mimetype);
651 $d->persist();
652 $d->populate();
654 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
655 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
656 $d->_db->Execute($sql);
659 else {
660 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
663 $this->assign("messages",$messages);
664 $_POST['process'] = "";
667 function move_action_process($patient_id="",$document_id) {
668 if ($_POST['process'] != "true")
669 return;
671 $new_category_id = $_POST['new_category_id'];
672 $new_patient_id = $_POST['new_patient_id'];
674 //move to new category
675 if (is_numeric($new_category_id) && is_numeric($document_id)) {
676 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
677 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
678 //echo $sql;
679 $this->tree->_db->Execute($sql);
682 //move to new patient
683 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
684 $d = new Document($document_id);
685 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
686 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
687 $result = $d->_db->Execute($sql);
689 if (!$result || $result->EOF) {
690 //patient id does not exist
691 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
693 else {
695 $couch_docid = $d->get_couch_docid();
696 $couch_revid = $d->get_couch_revid();
697 //set the new patient in CouchDB
698 $couchsavefailed=false;
699 if($couch_docid && $couch_revid){
700 $couch = new CouchDB();
701 $db = $GLOBALS['couchdb_dbase'];
702 $data=array($db,$couch_docid);
703 $couchresp=$couch->retrieve_doc($data);
704 //CouchDB doesnot support updating a single value in a document.
705 //Have to retrieve the entire document,update the necessary value and save again
706 list($db,$docid,$revid,$patient_id,$encounter,$type,$json) = $data;
707 $data=array($db,$couch_docid,$couch_revid,$new_patient_id,$couchresp->encounter,$couchresp->mimetype,json_encode($couchresp->data));
708 $resp = $couch->update_doc($data);
709 //Sometimes the response from CouchDB is not available
710 //still it would have saved in the DB. Hence check one more time
711 if(!$resp->_id || !$resp->_rev){
712 $data = array($db,$couch_docid,$new_patient_id,$couchresp->encounter);
713 $resp = $couch->retrieve_doc($data);
717 if($resp->_rev ==$couch_revid){
718 $couchsavefailed=true;
720 else{
721 $d->set_couch_revid($resp->_rev);
726 //set the new patient in mysql
727 $d->set_foreign_id($new_patient_id);
728 $d->persist();
729 $this->_state = false;
730 if(!$couchsavefailed){
732 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
734 else{
736 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
738 $this->assign("messages",$messages);
739 return $this->list_action($patient_id);
742 //in this case return the document to the queue instead of moving it
743 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
744 $d = new Document($document_id);
745 $new_path = $this->_config['repository'];
746 $fname = $d->get_url_file();
748 //see if there is an existing file with the same name and rename as necessary
749 if (file_exists($new_path.$d->get_url_file())) {
750 $messages .= "File with same name already exists in the queue.\n";
751 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
752 $messages .= "Current file name was changed to " . $fname ."\n";
755 //now move the file
756 if (rename($d->get_url_filepath(),$new_path.$fname)) {
757 $d->url = "file://" .$new_path.$fname;
758 $d->set_foreign_id("");
759 $d->persist();
760 $d->persist();
761 $d->populate();
763 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
764 $d->_db->Execute($sql);
765 $messages .= "Document returned to queue successfully.\n";
768 else {
769 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
772 $this->_state = false;
773 $this->assign("messages",$messages);
774 return $this->list_action($patient_id);
777 $this->_state = false;
778 $this->assign("messages",$messages);
779 return $this->view_action($patient_id,$document_id);
782 function validate_action_process($patient_id="", $document_id) {
784 $d = new Document($document_id);
785 if($d->couch_docid && $d->couch_revid){
786 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
787 $url = $file_path.$d->get_url();
788 $couch = new CouchDB();
789 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
790 $resp = $couch->retrieve_doc($data);
791 $content = $resp->data;
792 //--------Temporarily writing the file for calculating the hash--------//
793 //-----------Will be removed after calculating the hash value----------//
794 $temp_file = fopen($url,"w");
795 fwrite($temp_file,base64_decode($content));
796 fclose($temp_file);
798 else{
799 $url = $d->get_url();
801 //strip url of protocol handler
802 $url = preg_replace("|^(.*)://|","",$url);
804 //change full path to current webroot. this is for documents that may have
805 //been moved from a different filesystem and the full path in the database
806 //is not current. this is also for documents that may of been moved to
807 //different patients
808 // NOTE that $from_filename and basename($url) are the same thing
809 $from_all = explode("/",$url);
810 $from_filename = array_pop($from_all);
811 $from_patientid = array_pop($from_all);
812 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
813 if (file_exists($temp_url)) {
814 $url = $temp_url;
817 if ($_POST['process'] != "true") {
818 die("process is '" . $_POST['process'] . "', expected 'true'");
819 return;
822 $d = new Document( $document_id );
823 $current_hash = sha1_file( $url );
824 $messages = xl('Current Hash').": ".$current_hash."<br>";
825 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
826 if ( $d->get_hash() == '' ) {
827 $d->hash = $current_hash;
828 $d->persist();
829 $d->populate();
830 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
831 } else if ( $current_hash != $d->get_hash() ) {
832 $messages .= xl('Hash does not match. Data integrity has been compromised.');
833 } else {
834 $messages .= xl('Document passed integrity check.');
836 $this->_state = false;
837 $this->assign("messages", $messages);
838 if($d->couch_docid && $d->couch_revid){
839 //Removing the temporary file which is used to create the hash
840 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
842 return $this->view_action($patient_id, $document_id);
845 // Added by Rod for metadata update.
847 function update_action_process($patient_id="", $document_id) {
849 if ($_POST['process'] != "true") {
850 die("process is '" . $_POST['process'] . "', expected 'true'");
851 return;
854 $docdate = $_POST['docdate'];
855 $docname = $_POST['docname'];
856 $issue_id = $_POST['issue_id'];
858 if (is_numeric($document_id)) {
859 $messages = '';
860 $d = new Document( $document_id );
861 $file_name = $d->get_url_file();
862 if ( $docname != '' &&
863 $docname != $file_name ) {
864 $path = $d->get_url_filepath();
865 $path = str_replace( $file_name, "", $path );
866 $new_url = $this->_rename_file( $path.$docname );
867 if ( rename( $d->get_url(), $new_url ) ) {
868 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
869 $url = preg_replace("|^(.*)://|","",$d->get_url());
870 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
871 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
872 if ( file_exists( $url ) ) {
873 unlink( $url );
875 $d->url = $new_url;
876 $d->persist();
877 $d->populate();
878 $messages .= xl('Document successfully renamed.')."<br>";
879 } else {
880 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
884 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
885 $docdate = "'$docdate'";
886 } else {
887 $docdate = "NULL";
889 if (!is_numeric($issue_id)) {
890 $issue_id = 0;
892 $couch_docid = $d->get_couch_docid();
893 $couch_revid = $d->get_couch_revid();
894 if($couch_docid && $couch_revid ){
895 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
896 "list_id = '$issue_id' " .
897 "WHERE id = '$document_id'";
898 $this->tree->_db->Execute($sql);
901 else{
902 $sql = "UPDATE documents SET docdate = $docdate, " .
903 "list_id = '$issue_id' " .
904 "WHERE id = '$document_id'";
905 $this->tree->_db->Execute($sql);
907 $messages .= xl('Document date and issue updated successfully') . "<br>";
910 $this->_state = false;
911 $this->assign("messages", $messages);
912 return $this->view_action($patient_id, $document_id);
915 function list_action($patient_id = "") {
916 $this->_last_node = null;
917 $categories_list = $this->tree->_get_categories_array($patient_id);
918 //print_r($categories_list);
920 $menu = new HTML_TreeMenu();
921 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
922 $menu->addItem($rnode);
923 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
924 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
926 $this->assign("tree_html",$treeMenu->toHTML());
928 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
932 * This is a recursive function to rename a file to something that doesn't already exist.
933 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
934 * to ensure documents opened correctly by external browser viewers. If the counter is at the
935 * end of the file, then will use it (to continue to work with older files), however all new
936 * counters will be placed within filenames.
938 function _rename_file($fname) {
939 $file = basename($fname);
940 $fparts = split("\.",$fname);
941 $path = dirname($fname);
942 if (count($fparts) > 1) {
943 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
944 //increment the counter in filename
945 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
946 $fname = join(".",$fparts);
948 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
949 //increment counter at end of filename (so compatible with previous openemr version files
950 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
951 $fname = join(".",$fparts);
953 elseif (is_numeric($fparts[count($fparts) -1])) {
954 //leave date at end and place counter in filename
955 array_splice($fparts, -1, 0, "1");
956 $fname = join(".",$fparts);
958 else {
959 //add the counter to filename
960 array_splice($fparts, -1, 0, "1");
961 $fname = join(".",$fparts);
964 else { // (count($fparts) == 1)
965 //place counter at end of filename
966 array_push($fparts,"1");
967 $fname = join(".",$fparts);
970 if (file_exists($fname)) {
971 return $this->_rename_file($fname);
973 else {
974 return($fname);
978 function &_array_recurse($array,$categories = array()) {
979 if (!is_array($array)) {
980 $array = array();
982 $node = &$this->_last_node;
983 $current_node = &$node;
984 $expandedIcon = 'folder-expanded.gif';
985 foreach($array as $id => $ar) {
986 $icon = 'folder.gif';
987 if (is_array($ar) || !empty($id)) {
988 if ($node == null) {
989 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
990 $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));
991 $this->_last_node = &$rnode;
992 $node = &$rnode;
993 $current_node =&$rnode;
995 else {
996 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
997 $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)));
998 $current_node =&$this->_last_node;
1001 $this->_array_recurse($ar,$categories);
1003 else {
1004 if ($id === 0 && !empty($ar)) {
1005 $info = $this->tree->get_node_info($id);
1006 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1007 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1009 else {
1010 //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
1011 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1012 if ($id !== 0 && is_object($node)) {
1013 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1014 $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)));
1020 // If there are documents in this document category, then add their
1021 // attributes to the current node.
1022 $icon = "file3.png";
1023 if (is_array($categories[$id])) {
1024 foreach ($categories[$id] as $doc) {
1025 if($this->tree->get_node_name($id) == "CCR"){
1026 $current_node->addItem(new HTML_TreeNode(array(
1027 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1028 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1029 'icon' => $icon,
1030 'expandedIcon' => $expandedIcon,
1031 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1032 )));
1033 }elseif($this->tree->get_node_name($id) == "CCD"){
1034 $current_node->addItem(new HTML_TreeNode(array(
1035 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1036 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1037 'icon' => $icon,
1038 'expandedIcon' => $expandedIcon,
1039 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1040 )));
1041 }else{
1042 $current_node->addItem(new HTML_TreeNode(array(
1043 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1044 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1045 'icon' => $icon,
1046 'expandedIcon' => $expandedIcon
1047 )));
1053 return $node;
1056 //function for logging the errors in writing file to CouchDB/Hard Disk
1057 function document_upload_download_log($patientid,$content){
1058 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1059 $log_file = 'log.txt';
1060 if(!is_dir($log_path))
1061 mkdir($log_path,0777,true);
1062 $LOG = fopen($log_path.$log_file,'a');
1063 fwrite($LOG,$content);
1064 fclose($LOG);
1068 //place to hold optional code
1069 //$first_node = array_keys($t->tree);
1070 //$first_node = $first_node[0];
1071 //$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')"));
1073 //$this->_last_node = &$node1;