migrated the outcome and occurrence list from issues to list_options and internationa...
[openemr.git] / controllers / C_Document.class.php
blob190d3b75db0388ce7ddcb9d69190f04d36c7eccd
1 <?php
3 require_once(dirname(__FILE__) . "/../library/classes/Controller.class.php");
4 require_once(dirname(__FILE__) . "/../library/classes/Document.class.php");
5 require_once(dirname(__FILE__) . "/../library/classes/CategoryTree.class.php");
6 require_once(dirname(__FILE__) . "/../library/classes/TreeMenu.php");
7 require_once(dirname(__FILE__) . "/../library/classes/Note.class.php");
9 class C_Document extends Controller {
11 var $template_mod;
12 var $documents;
13 var $document_categories;
14 var $tree;
15 var $_config;
16 var $file_path;
19 function C_Document($template_mod = "general") {
20 parent::Controller();
21 $this->documents = array();
22 $this->template_mod = $template_mod;
23 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
24 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
26 //get global config options for this namespace
27 $this->_config = $GLOBALS['oer_config']['documents'];
29 $this->file_path = $this->_config['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
31 $this->_args = array("patient_id" => $_GET['patient_id']);
33 $this->assign("STYLE", $GLOBALS['style']);
34 $t = new CategoryTree(1);
35 //print_r($t->tree);
36 $this->tree = $t;
39 function upload_action($patient_id,$category_id) {
40 $category_name = $this->tree->get_node_name($category_id);
41 $this->assign("category_id", $category_id);
42 $this->assign("category_name", $category_name);
43 $this->assign("patient_id", $patient_id);
44 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
45 $this->assign("activity", $activity);
46 return $this->list_action($patient_id);
49 function upload_action_process() {
51 if ($_POST['process'] != "true")
52 return;
54 if (is_numeric($_POST['category_id'])) {
55 $category_id = $_POST['category_id'];
57 if (is_numeric($_POST['patient_id'])) {
58 $patient_id = $_POST['patient_id'];
61 foreach ($_FILES as $file) {
62 $fname = $file['name'];
63 $err = "";
64 if ($file['error'] > 0 || empty($file['name']) || $file['size'] == 0) {
65 $fname = $file['name'];
66 if (empty($fname)) {
67 $fname = htmlentities("<empty>");
69 $error = "Error number: " . $file['error'] . " occured while uploading file named: " . $fname . "\n";
70 if ($file['size'] == 0) {
71 $error .= "The system does not permit uploading files of with size 0.\n";
75 else {
77 if (!file_exists($this->file_path)) {
78 if (!mkdir($this->file_path,0700)) {
79 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
83 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
84 if (file_exists($this->file_path.$file['name'])) {
85 $error .= "File with same name already exists at location: " . $this->file_path . "\n";
86 $fname = basename($this->_rename_file($this->file_path.$file['name']));
87 $file['name'] = $fname;
88 $error .= "Current file name was changed to " . $fname ."\n";
90 if (move_uploaded_file($file['tmp_name'],$this->file_path.$file['name'])) {
91 $error .= "File " . $file['name'] . " successfully stored.\n";
92 $d = new Document();
93 $d->url = "file://" .$this->file_path.$file['name'];
94 $d->mimetype = $file['type'];
95 $d->size = $file['size'];
96 $d->type = $d->type_array['file_url'];
97 $d->set_foreign_id($patient_id);
98 $d->persist();
99 $d->populate();
100 $this->assign("file",$d);
102 if (is_numeric($d->get_id()) && is_numeric($category_id)) {
103 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
104 $d->_db->Execute($sql);
107 else {
108 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
112 $this->assign("error", nl2br($error));
113 //$this->_state = false;
114 $_POST['process'] = "";
115 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
118 function note_action_process($patient_id) {
120 if ($_POST['process'] != "true")
121 return;
123 $n = new Note();
124 parent::populate_object($n);
125 $n->persist();
127 $this->_state = false;
128 $_POST['process'] = "";
129 return $this->view_action($patient_id,$n->get_foreign_id());
132 function default_action() {
133 return $this->list_action();
136 function view_action($patient_id="",$doc_id) {
137 // Added by Rod to support document delete:
138 global $gacl_object, $phpgacl_location;
139 global $ISSUE_TYPES;
141 require_once(dirname(__FILE__) . "/../library/acl.inc");
142 require_once(dirname(__FILE__) . "/../library/lists.inc");
144 $d = new Document($doc_id);
145 $n = new Note();
147 $notes = $n->notes_factory($doc_id);
149 $this->assign("file", $d);
150 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
151 $this->assign("NOTE_ACTION",$this->_link("note"));
152 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
154 // Added by Rod to support document delete:
155 $delete_string = '';
156 if (acl_check('admin', 'super')) {
157 $delete_string = "<a href='' onclick='return deleteme(" . $d->get_id() .
158 ")'><font color='red'>(Delete this document)</font></a>";
160 $this->assign("delete_string", $delete_string);
161 $this->assign("REFRESH_ACTION",$this->_link("list"));
163 // Added by Rod to support document date update:
164 $this->assign("DOCDATE", $d->get_docdate());
165 $this->assign("UPDATE_ACTION",$this->_link("update") .
166 "document_id=" . $d->get_id() . "&process=true");
168 // Added by Rod to support document issue update:
169 $issues_options = "<option value='0'>-- Select Issue --</option>";
170 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
171 "pid = $patient_id " . // AND enddate IS NULL " .
172 "ORDER BY type, begdate");
173 while ($irow = sqlFetchArray($ires)) {
174 $desc = $irow['type'];
175 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
176 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
177 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
178 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
180 $this->assign("ISSUES_LIST", $issues_options);
182 $this->assign("notes",$notes);
184 $this->_last_node = null;
186 $menu = new HTML_TreeMenu();
188 //pass an empty array because we don't want the documents for each category showing up in this list box
189 $rnode = $this->_array_recurse($this->tree->tree,array());
190 $menu->addItem($rnode);
191 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => "Move Document to Category:"));
193 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
195 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
196 $this->assign("activity", $activity);
198 return $this->list_action($patient_id);
201 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
203 //controller function ruins booleans, so need to manually re-convert to booleans
204 if ($as_file == "true") {
205 $as_file=true;
207 else if ($as_file == "false") {
208 $as_file=false;
210 if ($original_file == "true") {
211 $original_file=true;
213 else if ($original_file == "false") {
214 $original_file=false;
217 $d = new Document($document_id);
218 $url = $d->get_url();
220 //strip url of protocol handler
221 $url = preg_replace("|^(.*)://|","",$url);
223 //change full path to current webroot. this is for documents that may have
224 //been moved from a different filesystem and the full path in the database
225 //is not current.
226 $temp_url = $GLOBALS["fileroot"].'/documents/'.$_SESSION["pid"].'/'.basename($url);
227 if (file_exists($temp_url)) {
228 $url = $temp_url;
230 if (!file_exists($url)) {
231 echo "The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it. $url";
233 else {
234 if ($original_file) {
235 //normal case when serving the file referenced in database
236 header("Pragma: public");
237 header("Expires: 0");
238 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
239 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
240 header("Content-Type: " . $d->get_mimetype());
241 header("Content-Length: " . $d->get_size());
242 $f = fopen($url,"r");
243 fpassthru($f);
244 exit;
246 else {
247 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
248 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
249 $url = $GLOBALS["fileroot"].'/documents/'.$_SESSION["pid"].'/'.$convertedFile;
250 header("Pragma: public");
251 header("Expires: 0");
252 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
253 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
254 header("Content-Type: image/jpeg");
255 header("Content-Length: " . filesize($url));
256 $f = fopen($url,"r");
257 fpassthru($f);
258 exit;
263 function queue_action($patient_id="") {
264 $messages = $this->_tpl_vars['messages'];
265 $queue_files = array();
267 //see if the repository exists and it is a directory else error
268 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
269 $dir = opendir($this->_config['repository']);
270 //read each entry in the directory
271 while (($file = readdir($dir)) !== false) {
272 //concat the filename and path
273 $file = $this->_config['repository'] .$file;
274 $file_info = array();
275 //if the filename is a file get its info and put into a tmp array
276 if (is_file($file) && strpos(basename($file),".") !== 0) {
277 $file_info['filename'] = basename($file);
278 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
279 $d = Document::document_factory_url("file://" . $file);
280 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
281 $file_info['patient_id'] = $patient_match[1];
282 $file_info['document_id'] = $d->get_id();
283 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
285 //merge the tmp array into the larger array
286 $queue_files[] = $file_info;
289 closedir($dir);
291 else {
292 $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";
296 $this->assign("queue_files",$queue_files);
297 $this->_last_node = null;
299 $menu = new HTML_TreeMenu();
301 //pass an empty array because we don't want the documents for each category showing up in this list box
302 $rnode = $this->_array_recurse($this->tree->tree,array());
303 $menu->addItem($rnode);
304 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
306 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
308 $this->assign("messages",nl2br($messages));
309 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
312 function queue_action_process() {
313 if ($_POST['process'] != "true")
314 return;
316 $messages = $this->_tpl_vars['messages'];
318 //build a category tree so we can have a list of category ids that are valid
319 $ct = new CategoryTree(1);
320 $categories = $ct->_id_name;
322 //see if there were and posted files and assign them
323 $files = null;
324 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
326 //loop through posted files
327 foreach($files as $doc_id=> $file) {
328 //only operate on files checked as active
329 if (!$file['active']) continue;
331 //run basic validation checks
332 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
333 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
334 continue;
337 //validate that the pod exists
338 $d = new Document($doc_id);
339 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
340 $result = $d->_db->Execute($sql);
342 if (!$result || $result->EOF) {
343 //patient id does not exist
344 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
345 continue;
348 //validate that the category id exists
349 if (!isset($categories[$file['category_id']])) {
350 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
351 continue;
354 //now do the work of moving the file
355 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
357 //see if the patient dir exists in the repository and create if not
358 if (!file_exists($new_path)) {
359 if (!mkdir($new_path,0700)) {
360 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
361 continue;
365 //fname is the name of the file after it is moved
366 $fname = $file['name'];
368 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
369 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
370 if ($patient_match[1] == $file['patient_id']) {
371 $fname = preg_replace("/^([0-9]+)_/","",$fname);
374 //filenames should not have funny chars
375 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
377 //see if there is an existing file with the same name and rename as necessary
378 if (file_exists($new_path.$file['name'])) {
379 $messages .= "File with same name already exists at location: " . $new_path . "\n";
380 $fname = basename($this->_rename_file($new_path.$file['name']));
381 $messages .= "Current file name was changed to " . $fname ."\n";
384 //now move the file
385 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
386 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
387 $d->url = "file://" .$new_path.$fname;
388 $d->set_foreign_id($file['patient_id']);
389 $d->set_mimetype($mimetype);
390 $d->persist();
391 $d->populate();
393 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
394 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
395 $d->_db->Execute($sql);
398 else {
399 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
402 $this->assign("messages",$messages);
403 $_POST['process'] = "";
406 function move_action_process($patient_id="",$document_id) {
407 if ($_POST['process'] != "true")
408 return;
410 $new_category_id = $_POST['new_category_id'];
411 $new_patient_id = $_POST['new_patient_id'];
413 //move to new category
414 if (is_numeric($new_category_id) && is_numeric($document_id)) {
415 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
416 $messages .= "Document moved to new category '" . $this->tree->_id_name[$new_category_id]['name'] . "' successfully.\n";
417 //echo $sql;
418 $this->tree->_db->Execute($sql);
421 //move to new patient
422 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
423 $d = new Document($document_id);
424 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
425 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
426 $result = $d->_db->Execute($sql);
428 if (!$result || $result->EOF) {
429 //patient id does not exist
430 $messages .= "Document could not be moved to patient id '" . $new_patient_id . "' because that id does not exist.\n";
432 else {
433 //set the new patient
434 $d->set_foreign_id($new_patient_id);
435 $d->persist();
436 $this->_state = false;
437 $messages .= "Document moved to patient id '" . $new_patient_id . "' successfully.\n";
438 $this->assign("messages",$messages);
439 return $this->list_action($patient_id);
442 //in this case return the document to the queue instead of moving it
443 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
444 $d = new Document($document_id);
445 $new_path = $this->_config['repository'];
446 $fname = $d->get_url_file();
448 //see if there is an existing file with the same name and rename as necessary
449 if (file_exists($new_path.$d->get_url_file())) {
450 $messages .= "File with same name already exists in the queue.\n";
451 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
452 $messages .= "Current file name was changed to " . $fname ."\n";
455 //now move the file
456 if (rename($d->get_url_filepath(),$new_path.$fname)) {
457 $d->url = "file://" .$new_path.$fname;
458 $d->set_foreign_id("");
459 $d->persist();
460 $d->persist();
461 $d->populate();
463 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
464 $d->_db->Execute($sql);
465 $messages .= "Document returned to queue successfully.\n";
468 else {
469 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
472 $this->_state = false;
473 $this->assign("messages",$messages);
474 return $this->list_action($patient_id);
477 $this->_state = false;
478 $this->assign("messages",$messages);
479 return $this->view_action($patient_id,$document_id);
482 // Added by Rod for metadata update.
484 function update_action_process($patient_id="", $document_id) {
485 if ($_POST['process'] != "true") {
486 die("process is '" . $_POST['process'] . "', expected 'true'");
487 return;
490 $docdate = $_POST['docdate'];
491 $issue_id = $_POST['issue_id'];
493 if (is_numeric($document_id)) {
494 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
495 $docdate = "'$docdate'";
496 } else {
497 $docdate = "NULL";
499 if (!is_numeric($issue_id)) {
500 $issue_id = 0;
502 $sql = "UPDATE documents SET docdate = $docdate, " .
503 "list_id = '$issue_id' " .
504 "WHERE id = '$document_id'";
505 $this->tree->_db->Execute($sql);
506 $messages .= "Document date and issue updated successfully\n";
509 $this->_state = false;
510 $this->assign("messages", $messages);
511 return $this->view_action($patient_id, $document_id);
514 function list_action($patient_id = "") {
515 $this->_last_node = null;
516 $categories_list = $this->tree->_get_categories_array($patient_id);
517 //print_r($categories_list);
519 $menu = new HTML_TreeMenu();
520 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
521 $menu->addItem($rnode);
522 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
523 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
525 $this->assign("tree_html",$treeMenu->toHTML());
527 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
531 * This is a recursive function to rename a file to something that doesn't already exist. It appends a numeric to the end of the file, if
532 * the file already has a numeric it increments that.
533 * It supports numeric endings upto 1000, after which it uses an md5sum on now() instead. This is because some files end in
534 * dates and we don't want to increment those.
536 function _rename_file($fname) {
537 $file = basename($fname);
538 $fparts = split("\.",$fname);
539 $path = dirname($fname);
540 if (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
541 $new_name = "";
542 for($i=0;$i<count($fparts);$i++) {
543 if ($i == (count($fparts) -1)) {
544 $new_name .= ($fparts[$i] +1);
546 else {
547 $new_name .= $fparts[$i] . ".";
550 $fname = $new_name;
552 elseif (is_numeric($fparts[count($fparts)])) {
553 $fname = $fname . "." . md5sum(now());
555 else {
556 $fname = $fname . ".1";
558 if (file_exists($fname)) {
559 return $this->_rename_file($fname);
561 else {
562 return($fname);
566 function &_array_recurse($array,$categories = array()) {
567 if (!is_array($array)) {
568 $array = array();
570 $node = &$this->_last_node;
571 $current_node = &$node;
572 $expandedIcon = 'folder-expanded.gif';
573 foreach($array as $id => $ar) {
574 $icon = 'folder.gif';
575 if (is_array($ar) || !empty($id)) {
576 if ($node == null) {
577 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
578 $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));
579 $this->_last_node = &$rnode;
580 $node = &$rnode;
581 $current_node =&$rnode;
583 else {
584 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
585 $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)));
586 $current_node =&$this->_last_node;
589 $this->_array_recurse($ar,$categories);
591 else {
592 if ($id === 0 && !empty($ar)) {
593 $info = $this->tree->get_node_info($id);
594 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
595 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
597 else {
598 //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
599 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
600 if ($id !== 0 && is_object($node)) {
601 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
602 $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)));
608 // If there are documents in this document category, then add their
609 // attributes to the current node.
610 $icon = "file3.png";
611 if (is_array($categories[$id])) {
612 foreach ($categories[$id] as $doc) {
613 $current_node->addItem(new HTML_TreeNode(array(
614 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
615 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
616 'icon' => $icon,
617 'expandedIcon' => $expandedIcon
618 )));
623 return $node;
627 //place to hold optional code
628 //$first_node = array_keys($t->tree);
629 //$first_node = $first_node[0];
630 //$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')"));
632 //$this->_last_node = &$node1;