security fix in master branch
[openemr.git] / library / classes / Document.class.php
blob90b14b6120985b08729e4d9825b28f69818abc7b
1 <?php
3 require_once(dirname(__FILE__) . "/../pnotes.inc");
4 require_once(dirname(__FILE__) . "/../gprelations.inc.php");
6 /**
7 * class Document
8 * This class is the logical representation of a physical file on some system somewhere that can be referenced with a URL
9 * of some type. This URL is not necessarily a web url, it could be a file URL or reference to a BLOB in a db.
10 * It is implicit that a document can have other related tables to it at least a one document to many notes which join on a documents
11 * id and categories which do the same.
14 class Document extends ORDataObject
18 * Database unique identifier
19 * @var id
21 var $id;
24 * DB unique identifier reference to some other table, this is not unique in the document table
25 * @var int
27 var $foreign_id;
30 * Enumerated DB field which is met information about how to use the URL
31 * @var int can also be a the properly enumerated string
33 var $type;
36 * Array mapping of possible for values for the type variable
37 * mapping is array text name to index
38 * @var array
40 var $type_array = array();
43 * Size of the document in bytes if that is available
44 * @var int
46 var $size;
49 * Date the document was first persisted
50 * @var string
52 var $date;
55 * URL which point to the document, may be a file URL, a web URL, a db BLOB URL, or others
56 * @var string
58 var $url;
61 * URL which point to the thumbnail document, may be a file URL, a web URL, a db BLOB URL, or others
62 * @var string
64 var $thumb_url;
67 * Mimetype of the document if available
68 * @var string
70 var $mimetype;
73 * If the document is a multi-page format like tiff and has at least 1 page this will be 1 or greater, if a non-multi-page format this should be null or empty
74 * @var int
76 var $pages;
79 * Foreign key identifier of who initially persisited the document,
80 * potentially ownership could be changed but that would be up to an external non-document object process
81 * @var int
83 var $owner;
86 * Timestamp of the last time the document was changed and persisted, auto maintained by DB, manually change at your own peril
87 * @var int
89 var $revision;
92 * Date (YYYY-MM-DD) logically associated with the document, e.g. when a picture was taken.
93 * @var string
95 var $docdate;
98 * 40-character sha1 hash key of the document from when it was uploaded.
99 * @var string
101 var $hash;
104 * DB identifier reference to the lists table (the related issue), 0 if none.
105 * @var int
107 var $list_id;
109 // For tagging with the encounter
110 var $encounter_id;
111 var $encounter_check;
114 * Whether the file is already imported
115 * @var int
117 var $imported;
120 * Constructor sets all Document attributes to their default value
121 * @param int $id optional existing id of a specific document, if omitted a "blank" document is created
123 function __construct($id = "")
125 //call the parent constructor so we have a _db to work with
126 parent::__construct();
128 //shore up the most basic ORDataObject bits
129 $this->id = $id;
130 $this->_table = "documents";
132 //load the enum type from the db using the parent helper function, this uses psuedo-class variables so it is really cheap
133 $this->type_array = $this->_load_enum("type");
135 $this->type = $this->type_array[0];
136 $this->size = 0;
137 $this->date = date("Y-m-d H:i:s");
138 $this->url = "";
139 $this->mimetype = "";
140 $this->docdate = date("Y-m-d");
141 $this->hash = "";
142 $this->list_id = 0;
143 $this->encounter_id = 0;
144 $this->encounter_check = "";
146 if ($id != "") {
147 $this->populate();
152 * Convenience function to get an array of many document objects
153 * For really large numbers of documents there is a way more efficient way to do this by overwriting the populate method
154 * @param int $foreign_id optional id use to limit array on to a specific relation, otherwise every document object is returned
156 function documents_factory($foreign_id = "")
158 $documents = array();
160 if (empty($foreign_id)) {
161 $foreign_id= "like '%'";
162 } else {
163 $foreign_id= " = '" . add_escape_custom(strval($foreign_id)) . "'";
166 $d = new Document();
167 $sql = "SELECT id FROM " . $d->_table . " WHERE foreign_id " .$foreign_id ;
168 $result = $d->_db->Execute($sql);
170 while ($result && !$result->EOF) {
171 $documents[] = new Document($result->fields['id']);
172 $result->MoveNext();
175 return $documents;
179 * Convenience function to get a document object from a url
180 * Checks to see if there is an existing document with that URL and if so returns that object, otherwise
181 * creates a new one, persists it and returns it
182 * @param string $url
183 * @return object new or existing document object with the specified URL
185 function document_factory_url($url)
187 $d = new Document();
188 //strip url handler, for now we always assume file://
189 $filename = preg_replace("|^(.*)://|", "", $url);
191 if (!file_exists($filename)) {
192 die("An invalid URL was specified to crete a new document, this would only be caused if files are being deleted as you are working through the queue. '$filename'\n");
195 $sql = "SELECT id FROM " . $d->_table . " WHERE url= '" . add_escape_custom($url) ."'" ;
196 $result = $d->_db->Execute($sql);
198 if ($result && !$result->EOF) {
199 if (file_exists($filename)) {
200 $d = new Document($result->fields['id']);
201 } else {
202 $sql = "DELETE FROM " . $d->_table . " WHERE id= '" . $result->fields['id'] ."'";
203 $result = $d->_db->Execute($sql);
204 echo("There is a database for the file but it no longer exists on the file system. Its document entry has been deleted. '$filename'\n");
206 } else {
207 $file_command = $GLOBALS['oer_config']['document']['file_command_path'] ;
208 $cmd_args = "-i ".escapeshellarg($new_path.$fname);
210 $command = $file_command." ".$cmd_args;
211 $mimetype = exec($command);
212 $mime_array = explode(":", $mimetype);
213 $mimetype = $mime_array[1];
214 $d->set_mimetype($mimetype);
215 $d->url = $url;
216 $d->size = filesize($filename);
217 $d->type = $d->type_array['file_url'];
218 $d->persist();
219 $d->populate();
222 return $d;
226 * Convenience function to generate string debug data about the object
228 function toString($html = false)
230 $string .= "\n"
231 . "ID: " . $this->id."\n"
232 . "FID: " . $this->foreign_id."\n"
233 . "type: " . $this->type . "\n"
234 . "type_array: " . print_r($this->type_array, true) . "\n"
235 . "size: " . $this->size . "\n"
236 . "date: " . $this->date . "\n"
237 . "url: " . $this->url . "\n"
238 . "mimetype: " . $this->mimetype . "\n"
239 . "pages: " . $this->pages . "\n"
240 . "owner: " . $this->owner . "\n"
241 . "revision: " . $this->revision . "\n"
242 . "docdate: " . $this->docdate . "\n"
243 . "hash: " . $this->hash . "\n"
244 . "list_id: " . $this->list_id . "\n"
245 . "encounter_id: " . $this->encounter_id . "\n"
246 . "encounter_check: " . $this->encounter_check . "\n";
248 if ($html) {
249 return nl2br($string);
250 } else {
251 return $string;
255 /**#@+
256 * Getter/Setter methods used by reflection to affect object in persist/poulate operations
257 * @param mixed new value for given attribute
259 function set_id($id)
261 $this->id = $id;
263 function get_id()
265 return $this->id;
267 function set_foreign_id($fid)
269 $this->foreign_id = $fid;
271 function get_foreign_id()
273 return $this->foreign_id;
275 function set_type($type)
277 $this->type = $type;
279 function get_type()
281 return $this->type;
283 function set_size($size)
285 $this->size = $size;
287 function get_size()
289 return $this->size;
291 function set_date($date)
293 $this->date = $date;
295 function get_date()
297 return $this->date;
299 function set_hash($hash)
301 $this->hash = $hash;
303 function get_hash()
305 return $this->hash;
307 function set_url($url)
309 $this->url = $url;
311 function get_url()
313 return $this->url;
315 function set_thumb_url($url)
317 $this->thumb_url = $url;
319 function get_thumb_url()
321 return $this->thumb_url;
324 * this returns the url stripped down to basename
326 function get_url_web()
328 return basename_international($this->url);
331 * get the url without the protocol handler
333 function get_url_filepath()
335 return preg_replace("|^(.*)://|", "", $this->url);
338 * get the url filename only
340 function get_url_file()
342 return basename_international(preg_replace("|^(.*)://|", "", $this->url));
345 * get the url path only
347 function get_url_path()
349 return dirname(preg_replace("|^(.*)://|", "", $this->url)) ."/";
351 function get_path_depth()
353 return $this->path_depth;
355 function set_path_depth($path_depth)
357 $this->path_depth = $path_depth;
359 function set_mimetype($mimetype)
361 $this->mimetype = $mimetype;
363 function get_mimetype()
365 return $this->mimetype;
367 function set_pages($pages)
369 $this->pages = $pages;
371 function get_pages()
373 return $this->pages;
375 function set_owner($owner)
377 $this->owner = $owner;
379 function get_owner()
381 return $this->owner;
384 * No getter for revision because it is updated automatically by the DB.
386 function set_revision($revision)
388 $this->revision = $revision;
390 function set_docdate($docdate)
392 $this->docdate = $docdate;
394 function get_docdate()
396 return $this->docdate;
398 function set_list_id($list_id)
400 $this->list_id = $list_id;
402 function get_list_id()
404 return $this->list_id;
406 function set_encounter_id($encounter_id)
408 $this->encounter_id = $encounter_id;
410 function get_encounter_id()
412 return $this->encounter_id;
414 function set_encounter_check($encounter_check)
416 $this->encounter_check = $encounter_check;
418 function get_encounter_check()
420 return $this->encounter_check;
423 function get_ccr_type($doc_id)
425 $type = sqlQuery("SELECT c.name FROM categories AS c LEFT JOIN categories_to_documents AS ctd ON c.id = ctd.category_id WHERE ctd.document_id = ?", array($doc_id));
426 return $type['name'];
428 function set_imported($imported)
430 $this->imported = $imported;
432 function get_imported()
434 return $this->imported;
436 function update_imported($doc_id)
438 sqlQuery("UPDATE documents SET imported = 1 WHERE id = ?", array($doc_id));
441 * Overridden function to stor current object state in the db.
442 * current overide is to allow for a just in time foreign id, often this is needed
443 * when the object is never directly exposed and is handled as part of a larger
444 * object hierarchy.
445 * @param int $fid foreign id that should be used so that this document can be related (joined) on it later
448 function persist($fid = "")
450 if (!empty($fid)) {
451 $this->foreign_id = $fid;
454 parent::persist();
457 function set_storagemethod($str)
459 $this->storagemethod = $str;
462 function get_storagemethod()
464 return $this->storagemethod;
467 function set_couch_docid($str)
469 $this->couch_docid = $str;
472 function get_couch_docid()
474 return $this->couch_docid;
477 function set_couch_revid($str)
479 $this->couch_revid = $str;
482 function get_couch_revid()
484 return $this->couch_revid;
487 function get_couch_url($pid, $encounter)
489 $couch_docid = $this->get_couch_docid();
490 $couch_url = $this->get_url();
491 $couch = new CouchDB();
492 $data = array($GLOBALS['couchdb_dbase'],$couch_docid,$pid,$encounter);
493 $resp = $couch->retrieve_doc($data);
494 $content = $resp->data;
495 $temp_url=$couch_url;
496 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $pid . '_' . $couch_url;
497 $f_CDB = fopen($temp_url, 'w');
498 fwrite($f_CDB, base64_decode($content));
499 fclose($f_CDB);
500 return $temp_url;
503 // Function added by Rod to change the patient associated with a document.
504 // This just moves some code that used to be in C_Document.class.php,
505 // changing it as little as possible since I'm not set up to test it.
507 function change_patient($new_patient_id)
509 $couch_docid = $this->get_couch_docid();
510 $couch_revid = $this->get_couch_revid();
512 // Set the new patient in CouchDB.
513 if ($couch_docid && $couch_revid) {
514 $couch = new CouchDB();
515 $db = $GLOBALS['couchdb_dbase'];
516 $data = array($db, $couch_docid);
517 $couchresp = $couch->retrieve_doc($data);
518 // CouchDB doesnot support updating a single value in a document.
519 // Have to retrieve the entire document, update the necessary value and save again
520 list ($db, $docid, $revid, $patient_id, $encounter, $type, $json) = $data;
521 $data = array($db, $couch_docid, $couch_revid, $new_patient_id, $couchresp->encounter,
522 $couchresp->mimetype, json_encode($couchresp->data), json_encode($couchresp->th_data));
523 $resp = $couch->update_doc($data);
524 // Sometimes the response from CouchDB is not available, still it would
525 // have saved in the DB. Hence check one more time.
526 if (!$resp->_id || !$resp->_rev) {
527 $data = array($db, $couch_docid, $new_patient_id, $couchresp->encounter);
528 $resp = $couch->retrieve_doc($data);
531 if ($resp->_rev == $couch_revid) {
532 return false;
533 } else {
534 $this->set_couch_revid($resp->_rev);
538 // Set the new patient in mysql.
539 $this->set_foreign_id($new_patient_id);
540 $this->persist();
542 // Return true for success.
543 return true;
547 * Create a new document and store its data.
548 * This is a mix of new code and code moved from C_Document.class.php.
550 * @param string $patient_id Patient pid; if not known then this may be a simple directory name
551 * @param integer $category_id The desired document category ID
552 * @param string $filename Desired filename, may be modified for uniqueness
553 * @param string $mimetype MIME type
554 * @param string &$data The actual data to store (not encoded)
555 * @param string $higher_level_path Optional subdirectory within the local document repository
556 * @param string $path_depth Number of directory levels in $higher_level_path, if specified
557 * @param integer $owner Owner/user/service that is requesting this action
558 * @param string $tmpfile The tmp location of file (require for thumbnail generator)
559 * @return string Empty string if success, otherwise error message text
561 function createDocument(
562 $patient_id,
563 $category_id,
564 $filename,
565 $mimetype,
566 &$data,
567 $higher_level_path = '',
568 $path_depth = 1,
569 $owner = 0,
570 $tmpfile = null
572 // The original code used the encounter ID but never set it to anything.
573 // That was probably a mistake, but we reference it here for documentation
574 // and leave it empty. Logically, documents are not tied to encounters.
576 if ($GLOBALS['generate_doc_thumb']) {
577 $thumb_size = ($GLOBALS['thumb_doc_max_size'] > 0) ? $GLOBALS['thumb_doc_max_size'] : null;
578 $thumbnail_class = new Thumbnail($thumb_size);
580 if (!is_null($tmpfile)) {
581 $has_thumbnail = $thumbnail_class->file_support_thumbnail($tmpfile);
582 } else {
583 $has_thumbnail = false;
586 if ($has_thumbnail) {
587 $thumbnail_resource = $thumbnail_class->create_thumbnail(null, $data);
588 if ($thumbnail_resource) {
589 $thumbnail_data = $thumbnail_class->get_string_file($thumbnail_resource);
590 } else {
591 $has_thumbnail = false;
594 } else {
595 $has_thumbnail = false;
598 $encounter_id = '';
599 $this->storagemethod = $GLOBALS['document_storage_method'];
600 $this->mimetype = $mimetype;
601 if ($this->storagemethod == 1) {
602 // Store it using CouchDB.
603 $couch = new CouchDB();
604 $docname = $_SESSION['authId'] . $filename . $patient_id . $encounter_id . date("%Y-%m-%d H:i:s");
605 $docid = $couch->stringToId($docname);
606 $json = json_encode(base64_encode($data));
607 if ($has_thumbnail) {
608 $th_json = json_encode(base64_encode($thumbnail_data));
609 $this->thumb_url = $this->get_thumb_name($filename);
610 } else {
611 $th_json = false;
614 $db = $GLOBALS['couchdb_dbase'];
615 $couchdata = array($db, $docid, $patient_id, $encounter_id, $mimetype, $json, $th_json);
616 $resp = $couch->check_saveDOC($couchdata);
617 if (!$resp->id || !$resp->_rev) {
618 // Not sure what this is supposed to do. The references to id, rev,
619 // _id and _rev seem pretty weird.
620 $couchdata = array($db, $docid, $patient_id, $encounter_id);
621 $resp = $couch->retrieve_doc($couchdata);
622 $docid = $resp->_id;
623 $revid = $resp->_rev;
624 } else {
625 $docid = $resp->id;
626 $revid = $resp->rev;
629 if (!$docid && !$revid) {
630 return xl('CouchDB save failed');
633 $this->url = $filename;
634 $this->couch_docid = $docid;
635 $this->couch_revid = $revid;
636 } else {
637 // Storing document files locally.
638 $repository = $GLOBALS['oer_config']['documents']['repository'];
639 $higher_level_path = preg_replace("/[^A-Za-z0-9\/]/", "_", $higher_level_path);
640 if ((!empty($higher_level_path)) && (is_numeric($patient_id) && $patient_id > 0)) {
641 // Allow higher level directory structure in documents directory and a patient is mapped.
642 $filepath = $repository . $higher_level_path . "/";
643 } else if (!empty($higher_level_path)) {
644 // Allow higher level directory structure in documents directory and there is no patient mapping
645 // (will create up to 10000 random directories and increment the path_depth by 1).
646 $filepath = $repository . $higher_level_path . '/' . rand(1, 10000) . '/';
647 ++$path_depth;
648 } else if (!(is_numeric($patient_id)) || !($patient_id > 0)) {
649 // This is the default action except there is no patient mapping (when patient_id is 00 or direct)
650 // (will create up to 10000 random directories and set the path_depth to 2).
651 $filepath = $repository . $patient_id . '/' . rand(1, 10000) . '/';
652 $path_depth = 2;
653 $patient_id = 0;
654 } else {
655 // This is the default action where the patient is used as one level directory structure in documents directory.
656 $filepath = $repository . $patient_id . '/';
657 $path_depth = 1;
660 if (!file_exists($filepath)) {
661 if (!mkdir($filepath, 0700, true)) {
662 return xl('Unable to create patient document subdirectory');
666 // Filename modification to force valid characters and uniqueness.
667 $filename = preg_replace("/[^a-zA-Z0-9_.]/", "_", $filename);
669 $fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
670 if (empty($fileExtension)) {
671 return xl('Your file doesn\'t have an extension');
674 $fnsuffix = 0;
675 $fn1 = $filename;
676 $fn2 = '';
677 $fn3 = '';
678 $dotpos = strrpos($filename, '.');
679 if ($dotpos !== false) {
680 $fn1 = substr($filename, 0, $dotpos);
681 $fn2 = '.';
682 $fn3 = substr($filename, $dotpos + 1);
685 while (file_exists($filepath . $filename)) {
686 if (++$fnsuffix > 10000) {
687 return xl('Failed to compute a unique filename');
690 $filename = $fn1 . '_' . $fnsuffix . $fn2 . $fn3;
693 $this->url = "file://" . $filepath . $filename;
694 if (is_numeric($path_depth)) {
695 // this is for when directory structure is more than one level
696 $this->path_depth = $path_depth;
699 // Store the file into its proper directory.
700 if (file_put_contents($filepath . $filename, $data) === false) {
701 return xl('Failed to create') . " $filepath$filename";
704 if ($has_thumbnail) {
705 $this->thumb_url = "file://" . $filepath . $this->get_thumb_name($filename);
706 // Store the file into its proper directory.
707 if (file_put_contents($filepath . $this->get_thumb_name($filename), $thumbnail_data) === false) {
708 return xl('Failed to create') . $filepath . $this->get_thumb_name($filename);
713 $this->size = strlen($data);
714 $this->hash = sha1($data);
715 $this->type = $this->type_array['file_url'];
716 $this->owner = $owner ? $owner : $_SESSION['authUserID'];
717 $this->set_foreign_id($patient_id);
718 $this->persist();
719 $this->populate();
720 if (is_numeric($this->get_id()) && is_numeric($category_id)) {
721 $sql = "REPLACE INTO categories_to_documents set " .
722 "category_id = '$category_id', " .
723 "document_id = '" . $this->get_id() . "'";
724 $this->_db->Execute($sql);
727 return '';
731 * Return file name for thumbnail (adding 'th_')
733 function get_thumb_name($file_name)
735 return 'th_' . $file_name;
739 * Post a patient note that is linked to this document.
741 * @param string $provider Login name of the provider to receive this note.
742 * @param integer $category_id The desired document category ID
743 * @param string $message Any desired message text for the note.
745 function postPatientNote($provider, $category_id, $message = '')
747 // Build note text in a way that identifies the new document.
748 // See pnotes_full.php which uses this to auto-display the document.
749 $note = $this->get_url_file();
750 for ($tmp = $category_id; $tmp;) {
751 $catrow = sqlQuery("SELECT name, parent FROM categories WHERE id = ?", array($tmp));
752 $note = $catrow['name'] . "/$note";
753 $tmp = $catrow['parent'];
756 $note = "New scanned document " . $this->get_id() . ": $note";
757 if ($message) {
758 $note .= "\n" . $message;
761 $noteid = addPnote($this->get_foreign_id(), $note, 0, '1', 'New Document', $provider);
762 // Link the new note to the document.
763 setGpRelation(1, $this->get_id(), 6, $noteid);
767 * Return note objects associated with this document using Note::notes_factory
770 function get_notes()
772 return (Note::notes_factory($this->get_id()));
774 } // end of Document