Changes to the Clients>Clinical report
[openemr.git] / controllers / C_Document.class.php
blobc0f29fc4ce682c395c491976c41ff5abc826ac04
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once(dirname(__FILE__) . "/../library/classes/Controller.class.php");
8 require_once(dirname(__FILE__) . "/../library/classes/Document.class.php");
9 require_once(dirname(__FILE__) . "/../library/classes/CategoryTree.class.php");
10 require_once(dirname(__FILE__) . "/../library/classes/TreeMenu.php");
11 require_once(dirname(__FILE__) . "/../library/classes/Note.class.php");
12 require_once(dirname(__FILE__) . "/../library/classes/CouchDB.class.php");
14 class C_Document extends Controller {
16 var $template_mod;
17 var $documents;
18 var $document_categories;
19 var $tree;
20 var $_config;
21 var $manual_set_owner=false; // allows manual setting of a document owner/service
23 function C_Document($template_mod = "general") {
24 parent::Controller();
25 $this->documents = array();
26 $this->template_mod = $template_mod;
27 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
28 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
30 //get global config options for this namespace
31 $this->_config = $GLOBALS['oer_config']['documents'];
33 $this->_args = array("patient_id" => $_GET['patient_id']);
35 $this->assign("STYLE", $GLOBALS['style']);
36 $t = new CategoryTree(1);
37 //print_r($t->tree);
38 $this->tree = $t;
41 function upload_action($patient_id,$category_id) {
42 $category_name = $this->tree->get_node_name($category_id);
43 $this->assign("category_id", $category_id);
44 $this->assign("category_name", $category_name);
45 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
46 $this->assign("patient_id", $patient_id);
48 // Added by Rod to support document template download from general_upload.html.
49 // Cloned from similar stuff in manage_document_templates.php.
50 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
51 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
52 $dh = opendir($templatedir);
53 if ($dh) {
54 $templateslist = array();
55 while (false !== ($sfname = readdir($dh))) {
56 if (substr($sfname, 0, 1) == '.') continue;
57 $templateslist[$sfname] = $sfname;
59 closedir($dh);
60 ksort($templateslist);
61 foreach ($templateslist as $sfname) {
62 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
63 "'>" . htmlspecialchars($sfname) . "</option>";
66 $this->assign("TEMPLATES_LIST", $templates_options);
68 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
69 $this->assign("activity", $activity);
70 return $this->list_action($patient_id);
73 //Upload multiple files on single click
74 function upload_action_process() {
76 // Collect a manually set owner if this has been set
77 // Used when want to manually assign the owning user/service such as the Direct mechanism
78 $non_HTTP_owner=false;
79 if ($this->manual_set_owner) {
80 $non_HTTP_owner=$this->manual_set_owner;
83 $couchDB = false;
84 $harddisk = false;
85 if($GLOBALS['document_storage_method']==0){
86 $harddisk = true;
88 if($GLOBALS['document_storage_method']==1){
89 $couchDB = true;
92 if ($_POST['process'] != "true")
93 return;
95 $doDecryption = false;
96 $encrypted = $_POST['encrypted'];
97 $passphrase = $_POST['passphrase'];
98 if ( !$GLOBALS['hide_document_encryption'] &&
99 $encrypted && $passphrase ) {
100 $doDecryption = true;
103 if (is_numeric($_POST['category_id'])) {
104 $category_id = $_POST['category_id'];
107 $patient_id = 0;
108 if (isset($_GET['patient_id']) && !$couchDB) {
109 $patient_id = $_GET['patient_id'];
111 else if (is_numeric($_POST['patient_id'])) {
112 $patient_id = $_POST['patient_id'];
115 $sentUploadStatus = array();
116 if( count($_FILES['file']['name']) > 0){
117 $upl_inc = 0;
118 foreach($_FILES['file']['name'] as $key => $value){
119 $fname = $value;
120 $err = "";
121 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
122 $fname = $value;
123 if (empty($fname)) {
124 $fname = htmlentities("<empty>");
126 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
127 if ($_FILES['file']['size'][$key] == 0) {
128 $error .= "The system does not permit uploading files of with size 0.\n";
130 }else{
131 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
132 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
133 fclose($tmpfile);
134 if ($doDecryption) {
135 $filetext = $this->decrypt($filetext, $passphrase);
137 if ( $_POST['destination'] != '' ) {
138 $fname = $_POST['destination'];
140 $d = new Document();
141 $rc = $d->createDocument($patient_id, $category_id, $fname,
142 $_FILES['file']['type'][$key], $filetext,
143 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
144 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
145 $non_HTTP_owner);
146 if ($rc) {
147 $error .= $rc . "\n";
149 else {
150 $this->assign("upload_success", "true");
152 $sentUploadStatus[] = $d;
153 $this->assign("file", $sentUploadStatus);
156 // Option to run a custom plugin for each file upload.
157 // This was initially created to delete the original source file in a custom setting.
158 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
159 if (file_exists($upload_plugin)) {
160 include_once($upload_plugin);
162 $upload_plugin_pp = 'documentUploadPostProcess';
163 if (function_exists($upload_plugin_pp)) {
164 $tmp = call_user_func($upload_plugin_pp, $value, $d);
165 if ($tmp) {
166 $error = $tmp;
169 // Following is just an example of code in such a plugin file.
170 /*****************************************************
171 function documentUploadPostProcess($filename, &$d) {
172 $userid = $_SESSION['authUserID'];
173 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
174 $owner = strtolower($row['username']);
175 $dn = '1_' . ucfirst($owner);
176 $filepath = "/shared_network_directory/$dn/$filename";
177 if (@unlink($filepath)) return '';
178 return "Failed to delete '$filepath'.";
180 *****************************************************/
185 $this->assign("error", nl2br($error));
186 //$this->_state = false;
187 $_POST['process'] = "";
188 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
191 function note_action_process($patient_id) {
193 if ($_POST['process'] != "true")
194 return;
196 $n = new Note();
197 $n->set_owner($_SESSION['authUserID']);
198 parent::populate_object($n);
199 $n->persist();
201 $this->_state = false;
202 $_POST['process'] = "";
203 return $this->view_action($patient_id,$n->get_foreign_id());
206 function default_action() {
207 return $this->list_action();
210 function view_action($patient_id="",$doc_id) {
211 // Added by Rod to support document delete:
212 global $gacl_object, $phpgacl_location;
213 global $ISSUE_TYPES;
215 require_once(dirname(__FILE__) . "/../library/acl.inc");
216 require_once(dirname(__FILE__) . "/../library/lists.inc");
218 $d = new Document($doc_id);
219 $n = new Note();
221 $notes = $n->notes_factory($doc_id);
223 $this->assign("file", $d);
224 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
225 $this->assign("NOTE_ACTION",$this->_link("note"));
226 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
227 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
229 // Added by Rod to support document delete:
230 $delete_string = '';
231 if (acl_check('admin', 'super')) {
232 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
233 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
235 $this->assign("delete_string", $delete_string);
236 $this->assign("REFRESH_ACTION",$this->_link("list"));
238 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
239 "document_id=" . $d->get_id() . "&process=true");
241 // Added by Rod to support document date update:
242 $this->assign("DOCDATE", $d->get_docdate());
243 $this->assign("UPDATE_ACTION",$this->_link("update") .
244 "document_id=" . $d->get_id() . "&process=true");
246 // Added by Rod to support document issue update:
247 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
248 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
249 "pid = ? " . // AND enddate IS NULL " .
250 "ORDER BY type, begdate", array($patient_id) );
251 while ($irow = sqlFetchArray($ires)) {
252 $desc = $irow['type'];
253 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
254 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
255 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
256 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
258 $this->assign("ISSUES_LIST", $issues_options);
260 $this->assign("notes",$notes);
262 $this->_last_node = null;
264 $menu = new HTML_TreeMenu();
266 //pass an empty array because we don't want the documents for each category showing up in this list box
267 $rnode = $this->_array_recurse($this->tree->tree,array());
268 $menu->addItem($rnode);
269 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
271 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
273 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
274 $this->assign("activity", $activity);
276 return $this->list_action($patient_id);
279 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
281 $td = mcrypt_module_open( $cypher, '', $mode, '');
282 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
283 mcrypt_generic_init( $td, $key, $iv );
284 $crypttext = mcrypt_generic( $td, $plaintext );
285 mcrypt_generic_deinit( $td );
286 return $iv.$crypttext;
289 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
291 $plaintext = '';
292 $td = mcrypt_module_open( $cypher, '', $mode, '' );
293 $ivsize = mcrypt_enc_get_iv_size( $td) ;
294 $iv = substr( $crypttext, 0, $ivsize );
295 $crypttext = substr( $crypttext, $ivsize );
296 if( $iv )
298 mcrypt_generic_init( $td, $key, $iv );
299 $plaintext = mdecrypt_generic( $td, $crypttext );
301 return $plaintext;
305 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
307 $encrypted = $_POST['encrypted'];
308 $passphrase = $_POST['passphrase'];
309 $doEncryption = false;
310 if ( !$GLOBALS['hide_document_encryption'] &&
311 $encrypted == "true" &&
312 $passphrase ) {
313 $doEncryption = true;
316 //controller function ruins booleans, so need to manually re-convert to booleans
317 if ($as_file == "true") {
318 $as_file=true;
320 else if ($as_file == "false") {
321 $as_file=false;
323 if ($original_file == "true") {
324 $original_file=true;
326 else if ($original_file == "false") {
327 $original_file=false;
330 $d = new Document($document_id);
331 $url = $d->get_url();
332 $storagemethod = $d->get_storagemethod();
333 $couch_docid = $d->get_couch_docid();
334 $couch_revid = $d->get_couch_revid();
336 if($couch_docid && $couch_revid && $original_file){
337 $couch = new CouchDB();
338 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
339 $resp = $couch->retrieve_doc($data);
340 $content = $resp->data;
341 if($content=='' && $GLOBALS['couchdb_log']==1){
342 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
343 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
344 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
345 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
346 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
347 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
348 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
349 die(xl("File retrieval from CouchDB failed"));
351 header('Content-Description: File Transfer');
352 header('Content-Transfer-Encoding: binary');
353 header('Expires: 0');
354 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
355 header('Pragma: public');
356 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
357 $fh = fopen($tmpcouchpath,"w");
358 fwrite($fh,base64_decode($content));
359 fclose($fh);
360 $f = fopen($tmpcouchpath,"r");
361 if ( $doEncryption ) {
362 $filetext = fread( $f, filesize($tmpcouchpath) );
363 $ciphertext = $this->encrypt( $filetext, $passphrase );
364 $tmpfilepath = $GLOBALS['temporary_files_dir'];
365 $tmpfilename = "/encrypted_".$d->get_url_file();
366 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
367 fwrite( $tmpfile, $ciphertext );
368 fclose( $tmpfile );
369 header('Content-Disposition: attachment; filename='.$tmpfilename );
370 header("Content-Type: application/octet-stream" );
371 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
372 ob_clean();
373 flush();
374 readfile( $tmpfilepath.$tmpfilename );
375 unlink( $tmpfilepath.$tmpfilename );
376 } else {
377 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
378 header("Content-Type: " . $d->get_mimetype());
379 header("Content-Length: " . filesize($tmpcouchpath));
380 fpassthru($f);
382 fclose($f);
383 if($content!='')
384 unlink($tmpcouchpath);
385 exit;//exits only if file download from CouchDB is successfull.
387 //strip url of protocol handler
388 $url = preg_replace("|^(.*)://|","",$url);
390 //change full path to current webroot. this is for documents that may have
391 //been moved from a different filesystem and the full path in the database
392 //is not current. this is also for documents that may of been moved to
393 //different patients. Note that the path_depth is used to see how far down
394 //the path to go. For example, originally the path_depth was always 1, which
395 //only allowed things like documents/1/<file>, but now can have more structured
396 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
397 // etc.
398 // NOTE that $from_filename and basename($url) are the same thing
399 $from_all = explode("/",$url);
400 $from_filename = array_pop($from_all);
401 $from_pathname_array = array();
402 for ($i=0;$i<$d->get_path_depth();$i++) {
403 $from_pathname_array[] = array_pop($from_all);
405 $from_pathname_array = array_reverse($from_pathname_array);
406 $from_pathname = implode("/",$from_pathname_array);
407 if($couch_docid && $couch_revid){
408 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
409 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
412 else{
413 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
416 if (file_exists($temp_url)) {
417 $url = $temp_url;
421 if (!file_exists($url)) {
422 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;
425 else {
426 if ($original_file) {
427 //normal case when serving the file referenced in database
428 header('Content-Description: File Transfer');
429 header('Content-Transfer-Encoding: binary');
430 header('Expires: 0');
431 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
432 header('Pragma: public');
433 $f = fopen($url,"r");
434 if ( $doEncryption ) {
435 $filetext = fread( $f, filesize($url) );
436 $ciphertext = $this->encrypt( $filetext, $passphrase );
437 $tmpfilepath = $GLOBALS['temporary_files_dir'];
438 $tmpfilename = "/encrypted_".$d->get_url_file();
439 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
440 fwrite( $tmpfile, $ciphertext );
441 fclose( $tmpfile );
442 header('Content-Disposition: attachment; filename='.$tmpfilename );
443 header("Content-Type: application/octet-stream" );
444 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
445 ob_clean();
446 flush();
447 readfile( $tmpfilepath.$tmpfilename );
448 unlink( $tmpfilepath.$tmpfilename );
449 } else {
450 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
451 header("Content-Type: " . $d->get_mimetype());
452 header("Content-Length: " . filesize($url));
453 fpassthru($f);
455 exit;
457 else {
458 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
459 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
460 if($couch_docid && $couch_revid){
461 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
463 else{
464 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
466 header("Pragma: public");
467 header("Expires: 0");
468 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
469 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
470 header("Content-Type: image/jpeg");
471 header("Content-Length: " . filesize($url));
472 $f = fopen($url,"r");
473 fpassthru($f);
474 if($couch_docid && $couch_revid){
475 fclose($f);
476 unlink($url);
477 $url=str_replace("_converted.jpg",'.pdf',$url);
478 unlink($url);
480 exit;
485 function queue_action($patient_id="") {
486 $messages = $this->_tpl_vars['messages'];
487 $queue_files = array();
489 //see if the repository exists and it is a directory else error
490 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
491 $dir = opendir($this->_config['repository']);
492 //read each entry in the directory
493 while (($file = readdir($dir)) !== false) {
494 //concat the filename and path
495 $file = $this->_config['repository'] .$file;
496 $file_info = array();
497 //if the filename is a file get its info and put into a tmp array
498 if (is_file($file) && strpos(basename($file),".") !== 0) {
499 $file_info['filename'] = basename($file);
500 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
501 $d = Document::document_factory_url("file://" . $file);
502 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
503 $file_info['patient_id'] = $patient_match[1];
504 $file_info['document_id'] = $d->get_id();
505 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
507 //merge the tmp array into the larger array
508 $queue_files[] = $file_info;
511 closedir($dir);
513 else {
514 $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";
518 $this->assign("queue_files",$queue_files);
519 $this->_last_node = null;
521 $menu = new HTML_TreeMenu();
523 //pass an empty array because we don't want the documents for each category showing up in this list box
524 $rnode = $this->_array_recurse($this->tree->tree,array());
525 $menu->addItem($rnode);
526 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
528 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
530 $this->assign("messages",nl2br($messages));
531 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
534 function queue_action_process() {
535 if ($_POST['process'] != "true")
536 return;
538 $messages = $this->_tpl_vars['messages'];
540 //build a category tree so we can have a list of category ids that are valid
541 $ct = new CategoryTree(1);
542 $categories = $ct->_id_name;
544 //see if there were and posted files and assign them
545 $files = null;
546 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
548 //loop through posted files
549 foreach($files as $doc_id=> $file) {
550 //only operate on files checked as active
551 if (!$file['active']) continue;
553 //run basic validation checks
554 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
555 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
556 continue;
559 //validate that the pod exists
560 $d = new Document($doc_id);
561 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
562 $result = $d->_db->Execute($sql);
564 if (!$result || $result->EOF) {
565 //patient id does not exist
566 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
567 continue;
570 //validate that the category id exists
571 if (!isset($categories[$file['category_id']])) {
572 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
573 continue;
576 //now do the work of moving the file
577 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
579 //see if the patient dir exists in the repository and create if not
580 if (!file_exists($new_path)) {
581 if (!mkdir($new_path,0700)) {
582 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
583 continue;
587 //fname is the name of the file after it is moved
588 $fname = $file['name'];
590 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
591 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
592 if ($patient_match[1] == $file['patient_id']) {
593 $fname = preg_replace("/^([0-9]+)_/","",$fname);
596 //filenames should not have funny chars
597 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
599 //see if there is an existing file with the same name and rename as necessary
600 if (file_exists($new_path.$file['name'])) {
601 $messages .= "File with same name already exists at location: " . $new_path . "\n";
602 $fname = basename($this->_rename_file($new_path.$file['name']));
603 $messages .= "Current file name was changed to " . $fname ."\n";
606 //now move the file
607 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
608 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
609 $d->url = "file://" .$new_path.$fname;
610 $d->set_foreign_id($file['patient_id']);
611 $d->set_mimetype($mimetype);
612 $d->persist();
613 $d->populate();
615 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
616 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
617 $d->_db->Execute($sql);
620 else {
621 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
624 $this->assign("messages",$messages);
625 $_POST['process'] = "";
628 function move_action_process($patient_id="",$document_id) {
629 if ($_POST['process'] != "true")
630 return;
632 $new_category_id = $_POST['new_category_id'];
633 $new_patient_id = $_POST['new_patient_id'];
635 //move to new category
636 if (is_numeric($new_category_id) && is_numeric($document_id)) {
637 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
638 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
639 //echo $sql;
640 $this->tree->_db->Execute($sql);
643 //move to new patient
644 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
645 $d = new Document($document_id);
646 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
647 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
648 $result = $d->_db->Execute($sql);
650 if (!$result || $result->EOF) {
651 //patient id does not exist
652 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
654 else {
655 $couchsavefailed = !$d->change_patient($new_patient_id);
657 $this->_state = false;
658 if(!$couchsavefailed){
660 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
662 else{
664 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
666 $this->assign("messages",$messages);
667 return $this->list_action($patient_id);
670 //in this case return the document to the queue instead of moving it
671 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
672 $d = new Document($document_id);
673 $new_path = $this->_config['repository'];
674 $fname = $d->get_url_file();
676 //see if there is an existing file with the same name and rename as necessary
677 if (file_exists($new_path.$d->get_url_file())) {
678 $messages .= "File with same name already exists in the queue.\n";
679 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
680 $messages .= "Current file name was changed to " . $fname ."\n";
683 //now move the file
684 if (rename($d->get_url_filepath(),$new_path.$fname)) {
685 $d->url = "file://" .$new_path.$fname;
686 $d->set_foreign_id("");
687 $d->persist();
688 $d->persist();
689 $d->populate();
691 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
692 $d->_db->Execute($sql);
693 $messages .= "Document returned to queue successfully.\n";
696 else {
697 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
700 $this->_state = false;
701 $this->assign("messages",$messages);
702 return $this->list_action($patient_id);
705 $this->_state = false;
706 $this->assign("messages",$messages);
707 return $this->view_action($patient_id,$document_id);
710 function validate_action_process($patient_id="", $document_id) {
712 $d = new Document($document_id);
713 if($d->couch_docid && $d->couch_revid){
714 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
715 $url = $file_path.$d->get_url();
716 $couch = new CouchDB();
717 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
718 $resp = $couch->retrieve_doc($data);
719 $content = $resp->data;
720 //--------Temporarily writing the file for calculating the hash--------//
721 //-----------Will be removed after calculating the hash value----------//
722 $temp_file = fopen($url,"w");
723 fwrite($temp_file,base64_decode($content));
724 fclose($temp_file);
726 else{
727 $url = $d->get_url();
729 //strip url of protocol handler
730 $url = preg_replace("|^(.*)://|","",$url);
732 //change full path to current webroot. this is for documents that may have
733 //been moved from a different filesystem and the full path in the database
734 //is not current. this is also for documents that may of been moved to
735 //different patients. Note that the path_depth is used to see how far down
736 //the path to go. For example, originally the path_depth was always 1, which
737 //only allowed things like documents/1/<file>, but now can have more structured
738 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
739 // etc.
740 // NOTE that $from_filename and basename($url) are the same thing
741 $from_all = explode("/",$url);
742 $from_filename = array_pop($from_all);
743 $from_pathname_array = array();
744 for ($i=0;$i<$d->get_path_depth();$i++) {
745 $from_pathname_array[] = array_pop($from_all);
747 $from_pathname_array = array_reverse($from_pathname_array);
748 $from_pathname = implode("/",$from_pathname_array);
749 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
750 if (file_exists($temp_url)) {
751 $url = $temp_url;
754 if ($_POST['process'] != "true") {
755 die("process is '" . $_POST['process'] . "', expected 'true'");
756 return;
759 $d = new Document( $document_id );
760 $current_hash = sha1_file( $url );
761 $messages = xl('Current Hash').": ".$current_hash."<br>";
762 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
763 if ( $d->get_hash() == '' ) {
764 $d->hash = $current_hash;
765 $d->persist();
766 $d->populate();
767 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
768 } else if ( $current_hash != $d->get_hash() ) {
769 $messages .= xl('Hash does not match. Data integrity has been compromised.');
770 } else {
771 $messages .= xl('Document passed integrity check.');
773 $this->_state = false;
774 $this->assign("messages", $messages);
775 if($d->couch_docid && $d->couch_revid){
776 //Removing the temporary file which is used to create the hash
777 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
779 return $this->view_action($patient_id, $document_id);
782 // Added by Rod for metadata update.
784 function update_action_process($patient_id="", $document_id) {
786 if ($_POST['process'] != "true") {
787 die("process is '" . $_POST['process'] . "', expected 'true'");
788 return;
791 $docdate = $_POST['docdate'];
792 $docname = $_POST['docname'];
793 $issue_id = $_POST['issue_id'];
795 if (is_numeric($document_id)) {
796 $messages = '';
797 $d = new Document( $document_id );
798 $file_name = $d->get_url_file();
799 if ( $docname != '' &&
800 $docname != $file_name ) {
801 $path = $d->get_url_filepath();
802 $path = str_replace( $file_name, "", $path );
803 $new_url = $this->_rename_file( $path.$docname );
804 if ( rename( $d->get_url(), $new_url ) ) {
805 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
806 $url = preg_replace("|^(.*)://|","",$d->get_url());
807 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
808 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
809 if ( file_exists( $url ) ) {
810 unlink( $url );
812 $d->url = $new_url;
813 $d->persist();
814 $d->populate();
815 $messages .= xl('Document successfully renamed.')."<br>";
816 } else {
817 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
821 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
822 $docdate = "'$docdate'";
823 } else {
824 $docdate = "NULL";
826 if (!is_numeric($issue_id)) {
827 $issue_id = 0;
829 $couch_docid = $d->get_couch_docid();
830 $couch_revid = $d->get_couch_revid();
831 if($couch_docid && $couch_revid ){
832 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
833 "list_id = '$issue_id' " .
834 "WHERE id = '$document_id'";
835 $this->tree->_db->Execute($sql);
838 else{
839 $sql = "UPDATE documents SET docdate = $docdate, " .
840 "list_id = '$issue_id' " .
841 "WHERE id = '$document_id'";
842 $this->tree->_db->Execute($sql);
844 $messages .= xl('Document date and issue updated successfully') . "<br>";
847 $this->_state = false;
848 $this->assign("messages", $messages);
849 return $this->view_action($patient_id, $document_id);
852 function list_action($patient_id = "") {
853 $this->_last_node = null;
854 $categories_list = $this->tree->_get_categories_array($patient_id);
855 //print_r($categories_list);
857 $menu = new HTML_TreeMenu();
858 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
859 $menu->addItem($rnode);
860 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
861 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
863 $this->assign("tree_html",$treeMenu->toHTML());
865 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
869 * This is a recursive function to rename a file to something that doesn't already exist.
870 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
871 * to ensure documents opened correctly by external browser viewers. If the counter is at the
872 * end of the file, then will use it (to continue to work with older files), however all new
873 * counters will be placed within filenames.
875 function _rename_file($fname) {
876 $file = basename($fname);
877 $fparts = split("\.",$fname);
878 $path = dirname($fname);
879 if (count($fparts) > 1) {
880 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
881 //increment the counter in filename
882 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
883 $fname = join(".",$fparts);
885 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
886 //increment counter at end of filename (so compatible with previous openemr version files
887 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
888 $fname = join(".",$fparts);
890 elseif (is_numeric($fparts[count($fparts) -1])) {
891 //leave date at end and place counter in filename
892 array_splice($fparts, -1, 0, "1");
893 $fname = join(".",$fparts);
895 else {
896 //add the counter to filename
897 array_splice($fparts, -1, 0, "1");
898 $fname = join(".",$fparts);
901 else { // (count($fparts) == 1)
902 //place counter at end of filename
903 array_push($fparts,"1");
904 $fname = join(".",$fparts);
907 if (file_exists($fname)) {
908 return $this->_rename_file($fname);
910 else {
911 return($fname);
915 function &_array_recurse($array,$categories = array()) {
916 if (!is_array($array)) {
917 $array = array();
919 $node = &$this->_last_node;
920 $current_node = &$node;
921 $expandedIcon = 'folder-expanded.gif';
922 foreach($array as $id => $ar) {
923 $icon = 'folder.gif';
924 if (is_array($ar) || !empty($id)) {
925 if ($node == null) {
926 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
927 $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));
928 $this->_last_node = &$rnode;
929 $node = &$rnode;
930 $current_node = &$rnode;
932 else {
933 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
934 $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)));
935 $current_node = &$this->_last_node;
938 $this->_array_recurse($ar,$categories);
940 else {
941 if ($id === 0 && !empty($ar)) {
942 $info = $this->tree->get_node_info($id);
943 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
944 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
946 else {
947 //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
948 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
949 if ($id !== 0 && is_object($node)) {
950 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
951 $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)));
957 // If there are documents in this document category, then add their
958 // attributes to the current node.
959 $icon = "file3.png";
960 if (is_array($categories[$id])) {
961 foreach ($categories[$id] as $doc) {
962 if($this->tree->get_node_name($id) == "CCR"){
963 $current_node->addItem(new HTML_TreeNode(array(
964 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
965 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
966 'icon' => $icon,
967 'expandedIcon' => $expandedIcon,
968 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
969 )));
970 }elseif($this->tree->get_node_name($id) == "CCD"){
971 $current_node->addItem(new HTML_TreeNode(array(
972 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
973 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
974 'icon' => $icon,
975 'expandedIcon' => $expandedIcon,
976 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
977 )));
978 }else{
979 $current_node->addItem(new HTML_TreeNode(array(
980 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
981 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
982 'icon' => $icon,
983 'expandedIcon' => $expandedIcon
984 )));
990 return $node;
993 //function for logging the errors in writing file to CouchDB/Hard Disk
994 function document_upload_download_log($patientid,$content){
995 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
996 $log_file = 'log.txt';
997 if(!is_dir($log_path))
998 mkdir($log_path,0777,true);
999 $LOG = fopen($log_path.$log_file,'a');
1000 fwrite($LOG,$content);
1001 fclose($LOG);
1005 //place to hold optional code
1006 //$first_node = array_keys($t->tree);
1007 //$first_node = $first_node[0];
1008 //$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')"));
1010 //$this->_last_node = &$node1;