Another ubuntu debian package bug fix for raw upgrading
[openemr.git] / controllers / C_Document.class.php
blob43f1c6a2c9f233528e19455dc9c9f8c4b429f57e
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");
13 class C_Document extends Controller {
15 var $template_mod;
16 var $documents;
17 var $document_categories;
18 var $tree;
19 var $_config;
20 var $file_path;
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->file_path = $this->_config['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
35 $this->_args = array("patient_id" => $_GET['patient_id']);
37 $this->assign("STYLE", $GLOBALS['style']);
38 $t = new CategoryTree(1);
39 //print_r($t->tree);
40 $this->tree = $t;
43 function upload_action($patient_id,$category_id) {
44 $category_name = $this->tree->get_node_name($category_id);
45 $this->assign("category_id", $category_id);
46 $this->assign("category_name", $category_name);
47 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
48 $this->assign("patient_id", $patient_id);
49 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
50 $this->assign("activity", $activity);
51 return $this->list_action($patient_id);
54 function upload_action_process() {
56 if ($_POST['process'] != "true")
57 return;
59 $doDecryption = false;
60 $encrypted = $_POST['encrypted'];
61 $passphrase = $_POST['passphrase'];
62 if ( !$GLOBALS['hide_document_encryption'] &&
63 $encrypted && $passphrase ) {
64 $doDecryption = true;
67 if (is_numeric($_POST['category_id'])) {
68 $category_id = $_POST['category_id'];
70 if (is_numeric($_POST['patient_id'])) {
71 $patient_id = $_POST['patient_id'];
74 foreach ($_FILES as $file) {
75 $fname = $file['name'];
76 $err = "";
77 if ($file['error'] > 0 || empty($file['name']) || $file['size'] == 0) {
78 $fname = $file['name'];
79 if (empty($fname)) {
80 $fname = htmlentities("<empty>");
82 $error = "Error number: " . $file['error'] . " occured while uploading file named: " . $fname . "\n";
83 if ($file['size'] == 0) {
84 $error .= "The system does not permit uploading files of with size 0.\n";
88 else {
90 if (!file_exists($this->file_path)) {
91 if (!mkdir($this->file_path,0700)) {
92 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
95 if ( $_POST['destination'] != '' ) {
96 $fname = $_POST['destination'];
98 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
99 if (file_exists($this->file_path.$fname)) {
100 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
101 $fname = basename($this->_rename_file($this->file_path.$fname));
102 $file['name'] = $fname;
103 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
106 if ( $doDecryption ) {
107 $tmpfile = fopen( $file['tmp_name'], "r" );
108 $filetext = fread( $tmpfile, $file['size'] );
109 $plaintext = $this->decrypt( $filetext, $passphrase );
110 unlink( $file['tmp_name'] );
111 $tmpfile = fopen( $file['tmp_name'], "w+" );
112 fwrite( $tmpfile, $plaintext );
113 fclose( $tmpfile );
114 $file['size'] = filesize( $tmpfilepath.$tmpfilename );
117 if (move_uploaded_file($file['tmp_name'],$this->file_path.$fname)) {
118 $this->assign("upload_success", "true");
119 $d = new Document();
120 $d->url = "file://" .$this->file_path.$fname;
121 $d->mimetype = $file['type'];
122 $d->size = $file['size'];
123 $sha1Hash = sha1_file( $this->file_path.$fname );
124 $d->hash = $sha1Hash;
125 $d->type = $d->type_array['file_url'];
126 $d->set_foreign_id($patient_id);
127 $d->persist();
128 $d->populate();
129 $this->assign("file",$d);
131 if (is_numeric($d->get_id()) && is_numeric($category_id)) {
132 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
133 $d->_db->Execute($sql);
136 else {
137 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
141 $this->assign("error", nl2br($error));
142 //$this->_state = false;
143 $_POST['process'] = "";
144 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
147 function note_action_process($patient_id) {
149 if ($_POST['process'] != "true")
150 return;
152 $n = new Note();
153 parent::populate_object($n);
154 $n->persist();
156 $this->_state = false;
157 $_POST['process'] = "";
158 return $this->view_action($patient_id,$n->get_foreign_id());
161 function default_action() {
162 return $this->list_action();
165 function view_action($patient_id="",$doc_id) {
166 // Added by Rod to support document delete:
167 global $gacl_object, $phpgacl_location;
168 global $ISSUE_TYPES;
170 require_once(dirname(__FILE__) . "/../library/acl.inc");
171 require_once(dirname(__FILE__) . "/../library/lists.inc");
173 $d = new Document($doc_id);
174 $n = new Note();
176 $notes = $n->notes_factory($doc_id);
178 $this->assign("file", $d);
179 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
180 $this->assign("NOTE_ACTION",$this->_link("note"));
181 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
182 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
184 // Added by Rod to support document delete:
185 $delete_string = '';
186 if (acl_check('admin', 'super')) {
187 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
188 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
190 $this->assign("delete_string", $delete_string);
191 $this->assign("REFRESH_ACTION",$this->_link("list"));
193 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
194 "document_id=" . $d->get_id() . "&process=true");
196 // Added by Rod to support document date update:
197 $this->assign("DOCDATE", $d->get_docdate());
198 $this->assign("UPDATE_ACTION",$this->_link("update") .
199 "document_id=" . $d->get_id() . "&process=true");
201 // Added by Rod to support document issue update:
202 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
203 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
204 "pid = $patient_id " . // AND enddate IS NULL " .
205 "ORDER BY type, begdate");
206 while ($irow = sqlFetchArray($ires)) {
207 $desc = $irow['type'];
208 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
209 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
210 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
211 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
213 $this->assign("ISSUES_LIST", $issues_options);
215 $this->assign("notes",$notes);
217 $this->_last_node = null;
219 $menu = new HTML_TreeMenu();
221 //pass an empty array because we don't want the documents for each category showing up in this list box
222 $rnode = $this->_array_recurse($this->tree->tree,array());
223 $menu->addItem($rnode);
224 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
226 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
228 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
229 $this->assign("activity", $activity);
231 return $this->list_action($patient_id);
234 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
236 $td = mcrypt_module_open( $cypher, '', $mode, '');
237 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
238 mcrypt_generic_init( $td, $key, $iv );
239 $crypttext = mcrypt_generic( $td, $plaintext );
240 mcrypt_generic_deinit( $td );
241 return $iv.$crypttext;
244 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
246 $plaintext = '';
247 $td = mcrypt_module_open( $cypher, '', $mode, '' );
248 $ivsize = mcrypt_enc_get_iv_size( $td) ;
249 $iv = substr( $crypttext, 0, $ivsize );
250 $crypttext = substr( $crypttext, $ivsize );
251 if( $iv )
253 mcrypt_generic_init( $td, $key, $iv );
254 $plaintext = mdecrypt_generic( $td, $crypttext );
256 return $plaintext;
260 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
262 $encrypted = $_POST['encrypted'];
263 $passphrase = $_POST['passphrase'];
264 $doEncryption = false;
265 if ( !$GLOBALS['hide_document_encryption'] &&
266 $encrypted == "true" &&
267 $passphrase ) {
268 $doEncryption = true;
271 //controller function ruins booleans, so need to manually re-convert to booleans
272 if ($as_file == "true") {
273 $as_file=true;
275 else if ($as_file == "false") {
276 $as_file=false;
278 if ($original_file == "true") {
279 $original_file=true;
281 else if ($original_file == "false") {
282 $original_file=false;
285 $d = new Document($document_id);
286 $url = $d->get_url();
288 //strip url of protocol handler
289 $url = preg_replace("|^(.*)://|","",$url);
291 //change full path to current webroot. this is for documents that may have
292 //been moved from a different filesystem and the full path in the database
293 //is not current. this is also for documents that may of been moved to
294 //different patients
295 // NOTE that $from_filename and basename($url) are the same thing
296 $from_all = explode("/",$url);
297 $from_filename = array_pop($from_all);
298 $from_patientid = array_pop($from_all);
299 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
300 if (file_exists($temp_url)) {
301 $url = $temp_url;
303 if (!file_exists($url)) {
304 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;
306 else {
307 if ($original_file) {
308 //normal case when serving the file referenced in database
309 header('Content-Description: File Transfer');
310 header('Content-Transfer-Encoding: binary');
311 header('Expires: 0');
312 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
313 header('Pragma: public');
314 $f = fopen($url,"r");
315 if ( $doEncryption ) {
316 $filetext = fread( $f, filesize($url) );
317 $ciphertext = $this->encrypt( $filetext, $passphrase );
318 $tmpfilepath = $GLOBALS['temporary_files_dir'];
319 $tmpfilename = "/encrypted_".$d->get_url_file();
320 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
321 fwrite( $tmpfile, $ciphertext );
322 fclose( $tmpfile );
323 header('Content-Disposition: attachment; filename='.$tmpfilename );
324 header("Content-Type: application/octet-stream" );
325 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
326 ob_clean();
327 flush();
328 readfile( $tmpfilepath.$tmpfilename );
329 unlink( $tmpfilepath.$tmpfilename );
330 } else {
331 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
332 header("Content-Type: " . $d->get_mimetype());
333 $size = filesize($d->get_url_filepath());
334 header("Content-Length: " . $size );
335 fpassthru($f);
337 exit;
339 else {
340 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
341 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
342 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
343 header("Pragma: public");
344 header("Expires: 0");
345 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
346 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
347 header("Content-Type: image/jpeg");
348 header("Content-Length: " . filesize($url));
349 $f = fopen($url,"r");
350 fpassthru($f);
351 exit;
356 function queue_action($patient_id="") {
357 $messages = $this->_tpl_vars['messages'];
358 $queue_files = array();
360 //see if the repository exists and it is a directory else error
361 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
362 $dir = opendir($this->_config['repository']);
363 //read each entry in the directory
364 while (($file = readdir($dir)) !== false) {
365 //concat the filename and path
366 $file = $this->_config['repository'] .$file;
367 $file_info = array();
368 //if the filename is a file get its info and put into a tmp array
369 if (is_file($file) && strpos(basename($file),".") !== 0) {
370 $file_info['filename'] = basename($file);
371 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
372 $d = Document::document_factory_url("file://" . $file);
373 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
374 $file_info['patient_id'] = $patient_match[1];
375 $file_info['document_id'] = $d->get_id();
376 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
378 //merge the tmp array into the larger array
379 $queue_files[] = $file_info;
382 closedir($dir);
384 else {
385 $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";
389 $this->assign("queue_files",$queue_files);
390 $this->_last_node = null;
392 $menu = new HTML_TreeMenu();
394 //pass an empty array because we don't want the documents for each category showing up in this list box
395 $rnode = $this->_array_recurse($this->tree->tree,array());
396 $menu->addItem($rnode);
397 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
399 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
401 $this->assign("messages",nl2br($messages));
402 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
405 function queue_action_process() {
406 if ($_POST['process'] != "true")
407 return;
409 $messages = $this->_tpl_vars['messages'];
411 //build a category tree so we can have a list of category ids that are valid
412 $ct = new CategoryTree(1);
413 $categories = $ct->_id_name;
415 //see if there were and posted files and assign them
416 $files = null;
417 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
419 //loop through posted files
420 foreach($files as $doc_id=> $file) {
421 //only operate on files checked as active
422 if (!$file['active']) continue;
424 //run basic validation checks
425 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
426 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
427 continue;
430 //validate that the pod exists
431 $d = new Document($doc_id);
432 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
433 $result = $d->_db->Execute($sql);
435 if (!$result || $result->EOF) {
436 //patient id does not exist
437 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
438 continue;
441 //validate that the category id exists
442 if (!isset($categories[$file['category_id']])) {
443 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
444 continue;
447 //now do the work of moving the file
448 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
450 //see if the patient dir exists in the repository and create if not
451 if (!file_exists($new_path)) {
452 if (!mkdir($new_path,0700)) {
453 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
454 continue;
458 //fname is the name of the file after it is moved
459 $fname = $file['name'];
461 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
462 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
463 if ($patient_match[1] == $file['patient_id']) {
464 $fname = preg_replace("/^([0-9]+)_/","",$fname);
467 //filenames should not have funny chars
468 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
470 //see if there is an existing file with the same name and rename as necessary
471 if (file_exists($new_path.$file['name'])) {
472 $messages .= "File with same name already exists at location: " . $new_path . "\n";
473 $fname = basename($this->_rename_file($new_path.$file['name']));
474 $messages .= "Current file name was changed to " . $fname ."\n";
477 //now move the file
478 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
479 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
480 $d->url = "file://" .$new_path.$fname;
481 $d->set_foreign_id($file['patient_id']);
482 $d->set_mimetype($mimetype);
483 $d->persist();
484 $d->populate();
486 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
487 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
488 $d->_db->Execute($sql);
491 else {
492 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
495 $this->assign("messages",$messages);
496 $_POST['process'] = "";
499 function move_action_process($patient_id="",$document_id) {
500 if ($_POST['process'] != "true")
501 return;
503 $new_category_id = $_POST['new_category_id'];
504 $new_patient_id = $_POST['new_patient_id'];
506 //move to new category
507 if (is_numeric($new_category_id) && is_numeric($document_id)) {
508 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
509 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
510 //echo $sql;
511 $this->tree->_db->Execute($sql);
514 //move to new patient
515 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
516 $d = new Document($document_id);
517 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
518 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
519 $result = $d->_db->Execute($sql);
521 if (!$result || $result->EOF) {
522 //patient id does not exist
523 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
525 else {
526 //set the new patient
527 $d->set_foreign_id($new_patient_id);
528 $d->persist();
529 $this->_state = false;
530 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
531 $this->assign("messages",$messages);
532 return $this->list_action($patient_id);
535 //in this case return the document to the queue instead of moving it
536 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
537 $d = new Document($document_id);
538 $new_path = $this->_config['repository'];
539 $fname = $d->get_url_file();
541 //see if there is an existing file with the same name and rename as necessary
542 if (file_exists($new_path.$d->get_url_file())) {
543 $messages .= "File with same name already exists in the queue.\n";
544 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
545 $messages .= "Current file name was changed to " . $fname ."\n";
548 //now move the file
549 if (rename($d->get_url_filepath(),$new_path.$fname)) {
550 $d->url = "file://" .$new_path.$fname;
551 $d->set_foreign_id("");
552 $d->persist();
553 $d->persist();
554 $d->populate();
556 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
557 $d->_db->Execute($sql);
558 $messages .= "Document returned to queue successfully.\n";
561 else {
562 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
565 $this->_state = false;
566 $this->assign("messages",$messages);
567 return $this->list_action($patient_id);
570 $this->_state = false;
571 $this->assign("messages",$messages);
572 return $this->view_action($patient_id,$document_id);
575 function validate_action_process($patient_id="", $document_id) {
576 if ($_POST['process'] != "true") {
577 die("process is '" . $_POST['process'] . "', expected 'true'");
578 return;
581 $d = new Document( $document_id );
582 $current_hash = sha1_file( $d->get_url_filepath() );
583 $messages = xl('Current Hash').": ".$current_hash."<br>";
584 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
585 if ( $d->get_hash() == '' ) {
586 $d->hash = $current_hash;
587 $d->persist();
588 $d->populate();
589 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
590 } else if ( $current_hash != $d->get_hash() ) {
591 $messages .= xl('Hash does not match. Data integrity has been compromised.');
592 } else {
593 $messages .= xl('Document passed integrity check.');
596 $this->_state = false;
597 $this->assign("messages", $messages);
598 return $this->view_action($patient_id, $document_id);
601 // Added by Rod for metadata update.
603 function update_action_process($patient_id="", $document_id) {
604 if ($_POST['process'] != "true") {
605 die("process is '" . $_POST['process'] . "', expected 'true'");
606 return;
609 $docdate = $_POST['docdate'];
610 $docname = $_POST['docname'];
611 $issue_id = $_POST['issue_id'];
613 if (is_numeric($document_id)) {
614 $messages = '';
615 $d = new Document( $document_id );
616 $file_name = $d->get_url_file();
617 if ( $docname != '' &&
618 $docname != $file_name ) {
619 $path = $d->get_url_filepath();
620 $path = str_replace( $file_name, "", $path );
621 $new_url = $this->_rename_file( $path.$docname );
622 if ( rename( $d->get_url(), $new_url ) ) {
623 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
624 $url = preg_replace("|^(.*)://|","",$d->get_url());
625 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
626 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
627 if ( file_exists( $url ) ) {
628 unlink( $url );
630 $d->url = $new_url;
631 $d->persist();
632 $d->populate();
633 $messages .= xl('Document successfully renamed.')."<br>";
634 } else {
635 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
639 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
640 $docdate = "'$docdate'";
641 } else {
642 $docdate = "NULL";
644 if (!is_numeric($issue_id)) {
645 $issue_id = 0;
647 $sql = "UPDATE documents SET docdate = $docdate, " .
648 "list_id = '$issue_id' " .
649 "WHERE id = '$document_id'";
650 $this->tree->_db->Execute($sql);
651 $messages .= xl('Document date and issue updated successfully') . "<br>";
654 $this->_state = false;
655 $this->assign("messages", $messages);
656 return $this->view_action($patient_id, $document_id);
659 function list_action($patient_id = "") {
660 $this->_last_node = null;
661 $categories_list = $this->tree->_get_categories_array($patient_id);
662 //print_r($categories_list);
664 $menu = new HTML_TreeMenu();
665 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
666 $menu->addItem($rnode);
667 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
668 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
670 $this->assign("tree_html",$treeMenu->toHTML());
672 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
676 * This is a recursive function to rename a file to something that doesn't already exist.
677 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
678 * to ensure documents opened correctly by external browser viewers. If the counter is at the
679 * end of the file, then will use it (to continue to work with older files), however all new
680 * counters will be placed within filenames.
682 function _rename_file($fname) {
683 $file = basename($fname);
684 $fparts = split("\.",$fname);
685 $path = dirname($fname);
686 if (count($fparts) > 1) {
687 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
688 //increment the counter in filename
689 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
690 $fname = join(".",$fparts);
692 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
693 //increment counter at end of filename (so compatible with previous openemr version files
694 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
695 $fname = join(".",$fparts);
697 elseif (is_numeric($fparts[count($fparts) -1])) {
698 //leave date at end and place counter in filename
699 array_splice($fparts, -1, 0, "1");
700 $fname = join(".",$fparts);
702 else {
703 //add the counter to filename
704 array_splice($fparts, -1, 0, "1");
705 $fname = join(".",$fparts);
708 else { // (count($fparts) == 1)
709 //place counter at end of filename
710 array_push($fparts,"1");
711 $fname = join(".",$fparts);
714 if (file_exists($fname)) {
715 return $this->_rename_file($fname);
717 else {
718 return($fname);
722 function &_array_recurse($array,$categories = array()) {
723 if (!is_array($array)) {
724 $array = array();
726 $node = &$this->_last_node;
727 $current_node = &$node;
728 $expandedIcon = 'folder-expanded.gif';
729 foreach($array as $id => $ar) {
730 $icon = 'folder.gif';
731 if (is_array($ar) || !empty($id)) {
732 if ($node == null) {
733 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
734 $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));
735 $this->_last_node = &$rnode;
736 $node = &$rnode;
737 $current_node =&$rnode;
739 else {
740 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
741 $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)));
742 $current_node =&$this->_last_node;
745 $this->_array_recurse($ar,$categories);
747 else {
748 if ($id === 0 && !empty($ar)) {
749 $info = $this->tree->get_node_info($id);
750 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
751 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
753 else {
754 //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
755 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
756 if ($id !== 0 && is_object($node)) {
757 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
758 $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)));
764 // If there are documents in this document category, then add their
765 // attributes to the current node.
766 $icon = "file3.png";
767 if (is_array($categories[$id])) {
768 foreach ($categories[$id] as $doc) {
769 $current_node->addItem(new HTML_TreeNode(array(
770 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
771 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
772 'icon' => $icon,
773 'expandedIcon' => $expandedIcon
774 )));
779 return $node;
783 //place to hold optional code
784 //$first_node = array_keys($t->tree);
785 //$first_node = $first_node[0];
786 //$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')"));
788 //$this->_last_node = &$node1;