3 * patient.inc includes functions for manipulating patient information.
6 * @link http://www.open-emr.org
7 * @author Brady Miller <brady.g.miller@gmail.com>
8 * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>
9 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
13 use OpenEMR\Services\FacilityService;
15 $facilityService = new FacilityService();
17 // These are for sports team use:
18 $PLAYER_FITNESSES = array(
21 xl('Restricted Training'),
25 xl('International Duty')
27 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
29 // Hard-coding this array because its values and meanings are fixed by the 837p
30 // standard and we don't want people messing with them.
31 $policy_types = array(
33 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
34 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
35 '14' => xl('No-fault Insurance including Auto is Primary'),
36 '15' => xl('Worker`s Compensation'),
37 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
38 '41' => xl('Black Lung'),
39 '42' => xl('Veteran`s Administration'),
40 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
41 '47' => xl('Other Liability Insurance is Primary'),
45 * Get a patient's demographic data.
47 * @param int $pid The PID of the patient
48 * @param string $given an optional subsection of the patient's demographic
50 * @return array The requested subsection of a patient's demographic data.
51 * If no subsection was given, returns everything, with the
52 * date of birth as the last field.
54 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
56 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
57 return sqlQuery($sql, array($pid));
60 function getLanguages()
62 $returnval = array('','english');
63 $sql = "select distinct lower(language) as language from patient_data";
64 $rez = sqlStatement($sql);
65 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
66 if (($row["language"] != "english") && ($row["language"] != "")) {
67 array_push($returnval, $row["language"]);
74 function getInsuranceProvider($ins_id)
77 $sql = "select name from insurance_companies where id=?";
78 $row = sqlQuery($sql, array($ins_id));
82 function getInsuranceProviders()
87 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
88 $rez = sqlStatement($sql);
89 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
90 $returnval[$row['id']] = $row['name'];
92 } // Please leave this here. I have a user who wants to see zip codes and PO
93 // box numbers listed along with the insurance company names, as many companies
94 // have different billing addresses for different plans. -- Rod Roark
97 $sql = "select insurance_companies.name, insurance_companies.id, " .
98 "addresses.zip, addresses.line1 " .
99 "from insurance_companies, addresses " .
100 "where addresses.foreign_id = insurance_companies.id " .
101 "order by insurance_companies.name, addresses.zip";
103 $rez = sqlStatement($sql);
105 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
106 preg_match("/\d+/", $row['line1'], $matches);
107 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
108 "," . $matches[0] . ")";
115 function getInsuranceProvidersExtra()
117 $returnval = array();
118 // add a global and if for where to allow inactive inscompanies
120 $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
121 addresses.state, addresses.zip
122 FROM insurance_companies, addresses
123 WHERE addresses.foreign_id = insurance_companies.id
124 AND insurance_companies.inactive != 1
125 ORDER BY insurance_companies.name, addresses.zip";
127 $rez = sqlStatement($sql);
129 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
130 switch ($GLOBALS['insurance_information']) {
131 case $GLOBALS['insurance_information'] = '0':
132 $returnval[$row['id']] = $row['name'];
134 case $GLOBALS['insurance_information'] = '1':
135 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
137 case $GLOBALS['insurance_information'] = '2':
138 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
140 case $GLOBALS['insurance_information'] = '3':
141 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
143 case $GLOBALS['insurance_information'] = '4':
144 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
145 ", " . $row['zip'] . ")";
147 case $GLOBALS['insurance_information'] = '5':
148 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
149 ", " . $row['state'] . ", " . $row['zip'] . ")";
151 case $GLOBALS['insurance_information'] = '6':
152 preg_match("/\d+/", $row['line1'], $matches);
153 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
154 "," . $matches[0] . ")";
162 function getProviders()
164 $returnval = array();
165 $sql = "select fname, lname, suffix from users where authorized = 1 and " .
166 "active = 1 and username != ''";
167 $rez = sqlStatement($sql);
168 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
169 if (($row["fname"] != "") && ($row["lname"] != "")) {
170 if ($row["suffix"] != "") {
171 $row["lname"] .= ", ".$row["suffix"];
174 array_push($returnval, $row["fname"] . " " . $row["lname"]);
181 // ----------------------------------------------------------------------------
182 // Get one facility row. If the ID is not specified, then get either the
183 // "main" (billing) facility, or the default facility of the currently
184 // logged-in user. This was created to support genFacilityTitle() but
185 // may find additional uses.
187 function getFacility($facid = 0)
189 global $facilityService;
194 $facility = $facilityService->getById($facid);
195 } else if ($facid == 0) {
196 $facility = $facilityService->getPrimaryBillingLocation();
198 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
204 // Generate a report title including report name and facility name, address
207 function genFacilityTitle($repname = '', $facid = 0)
210 $s .= "<table class='ftitletable'>\n";
213 $s .= " <td class='ftitlecell1'>$repname</td>\n";
215 $s .= " <td class='ftitlecell1'>$logo</td>\n";
216 $s .= " <td class='ftitlecellm'>$repname</td>\n";
218 $s .= " <td class='ftitlecell2'>\n";
219 $r = getFacility($facid);
221 $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
223 $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
226 if ($r['city'] || $r['state'] || $r['postal_code']) {
229 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
237 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
240 if ($r['postal_code']) {
241 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
247 if ($r['country_code']) {
248 $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
251 if (preg_match('/[1-9]/', $r['phone'])) {
252 $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
265 returns all facilities or just the id for the first one
266 (FACILITY FILTERING (lemonsoftware))
268 @param string - if 'first' return first facility ordered by id
269 @return array | int for 'first' case
271 function getFacilities($first = '')
273 global $facilityService;
275 $fres = $facilityService->getAll();
277 if ($first == 'first') {
278 return $fres[0]['id'];
285 GET SERVICE FACILITIES
287 returns all service_location facilities or just the id for the first one
288 (FACILITY FILTERING (CHEMED))
290 @param string - if 'first' return first facility ordered by id
291 @return array | int for 'first' case
293 function getServiceFacilities($first = '')
295 global $facilityService;
297 $fres = $facilityService->getAllServiceLocations();
299 if ($first == 'first') {
300 return $fres[0]['id'];
306 //(CHEMED) facility filter
307 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
310 if ($providers_only === 'any') {
311 $param1 = " AND authorized = 1 AND active = 1 ";
312 } else if ($providers_only) {
313 $param1 = " AND authorized = 1 AND calendar = 1 ";
316 //--------------------------------
317 //(CHEMED) facility filter
320 if ($GLOBALS['restrict_user_facility']) {
321 $param2 = " AND (facility_id = $facility
325 where tablename = 'users'
330 $param2 = " AND facility_id = $facility ";
334 //--------------------------------
337 if ($providerID == "%") {
341 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
342 "from users where username != '' and active = 1 and id $command '" .
343 add_escape_custom($providerID) . "' " . $param1 . $param2;
344 // sort by last name -- JRM June 2008
345 $query .= " ORDER BY lname, fname ";
346 $rez = sqlStatement($query);
347 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
348 $returnval[$iter]=$row;
351 //if only one result returned take the key/value pairs in array [0] and merge them down into
352 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
355 $akeys = array_keys($returnval[0]);
356 foreach ($akeys as $key) {
357 $returnval[0][$key] = $returnval[0][$key];
364 //same as above but does not reduce if only 1 row returned
365 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
368 if ($providers_only) {
369 $param1 = "AND authorized=1";
373 if ($providerID == "%") {
377 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
378 "from users where active = 1 and username != '' and id $command '" .
379 add_escape_custom($providerID) . "' " . $param1;
381 $rez = sqlStatement($query);
382 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
383 $returnval[$iter]=$row;
389 function getProviderName($providerID)
391 $pi = getProviderInfo($providerID, 'any');
392 if (strlen($pi[0]["lname"]) > 0) {
393 if (strlen($pi[0]["suffix"]) > 0) {
394 $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
397 return $pi[0]['fname'] . " " . $pi[0]['lname'];
403 function getProviderId($providerName)
405 $query = "select id from users where username = ?";
406 $rez = sqlStatement($query, array($providerName));
407 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
408 $returnval[$iter]=$row;
414 function getEthnoRacials()
416 $returnval = array("");
417 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
418 $rez = sqlStatement($sql);
419 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
420 if (($row["ethnoracial"] != "")) {
421 array_push($returnval, $row["ethnoracial"]);
428 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
431 if ($dateStart && $dateEnd) {
432 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
433 } else if ($dateStart && !$dateEnd) {
434 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
435 } else if (!$dateStart && $dateEnd) {
436 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
438 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
441 if ($given == 'tobacco') {
442 $res = sqlQuery("select $given from history_data where pid = ? and tobacco is not null and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
448 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
449 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
451 $sql = "select $given from insurance_data as insd " .
452 "left join insurance_companies as ic on ic.id = insd.provider " .
453 "where pid = ? and type = ? order by date DESC limit 1";
454 return sqlQuery($sql, array($pid, $type));
457 function getInsuranceDataByDate(
461 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
463 // this must take the date in the following manner: YYYY-MM-DD
464 // this function recalls the insurance value that was most recently enterred from the
465 // given date. it will call up most recent records up to and on the date given,
466 // but not records enterred after the given date
467 $sql = "select $given from insurance_data as insd " .
468 "left join insurance_companies as ic on ic.id = provider " .
469 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
470 "type=? order by date DESC limit 1";
471 return sqlQuery($sql, array($pid,$date,$type));
474 function getEmployerData($pid, $given = "*")
476 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
477 return sqlQuery($sql, array($pid));
480 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
482 // When the limit is exceeded, find out what the unlimited count would be.
483 $GLOBALS['PATIENT_INC_COUNT'] = $count;
484 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
485 if ($limit != "all") {
486 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
487 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
492 * Allow the last name to be followed by a comma and some part of a first name(can
493 * also place middle name after the first name with a space separating them)
494 * Allows comma alone followed by some part of a first name(can also place middle name
495 * after the first name with a space separating them).
496 * Allows comma alone preceded by some part of a last name.
497 * If no comma or space, then will search both last name and first name.
498 * If the first letter of either name is capital, searches for name starting
499 * with given substring (the expected behavior). If it is lower case, it
500 * searches for the substring anywhere in the name. This applies to either
501 * last name, first name, and middle name.
502 * Also allows first name followed by middle and/or last name when separated by spaces.
503 * @param string $term
504 * @param string $given
505 * @param string $orderby
506 * @param string $limit
507 * @param string $start
510 function getPatientLnames($term = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
512 $names = getPatientNameSplit($term);
514 foreach ($names as $key => $val) {
516 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
517 $names[$key] = '%' . $val . '%';
519 $names[$key] = $val . '%';
524 // Debugging section below
525 //if(array_key_exists('first',$names)) {
526 // error_log("first name search term :".$names['first']);
528 //if(array_key_exists('middle',$names)) {
529 // error_log("middle name search term :".$names['middle']);
531 //if(array_key_exists('last',$names)) {
532 // error_log("last name search term :".$names['last']);
534 // Debugging section above
536 $sqlBindArray = array();
537 if (array_key_exists('last', $names) && $names['last'] == '') {
538 // Do not search last name
539 $where = "fname LIKE ? ";
540 array_push($sqlBindArray, $names['first']);
541 if ($names['middle'] != '') {
542 $where .= "AND mname LIKE ? ";
543 array_push($sqlBindArray, $names['middle']);
545 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
546 // Do not search first name or middle name
547 $where = "lname LIKE ? ";
548 array_push($sqlBindArray, $names['last']);
549 } elseif ($names['first'] == '' && $names['last'] != '') {
550 // Search both first name and last name with same term
551 $names['first'] = $names['last'];
552 $where = "lname LIKE ? OR fname LIKE ? ";
553 array_push($sqlBindArray, $names['last'], $names['first']);
554 } elseif ($names['middle'] != '') {
555 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
556 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
558 $where = "lname LIKE ? AND fname LIKE ? ";
559 array_push($sqlBindArray, $names['last'], $names['first']);
562 if (!empty($GLOBALS['pt_restrict_field'])) {
563 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
564 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
565 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
566 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
567 array_push($sqlBindArray, $_SESSION{"authUser"});
571 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
572 if ($limit != "all") {
573 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
576 $rez = sqlStatement($sql, $sqlBindArray);
579 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
580 $returnval[$iter] = $row;
583 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
587 * Accept a string used by a search function expected to find a patient name,
588 * then split up the string if a comma or space exists. Return an array having
589 * from 1 to 3 elements, named first, middle, and last.
590 * See above getPatientLnames() function for details on how the splitting occurs.
591 * @param string $term
594 function getPatientNameSplit($term)
597 if (strpos($term, ',') !== false) {
598 $names = explode(',', $term);
599 $n['last'] = $names[0];
600 if (strpos(trim($names[1]), ' ') !== false) {
601 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
603 $n['first'] = $names[1];
605 } elseif (strpos($term, ' ') !== false) {
606 $names = explode(' ', $term);
607 if (count($names) == 1) {
608 $n['last'] = $names[0];
609 } elseif (count($names) == 3) {
610 $n['first'] = $names[0];
611 $n['middle'] = $names[1];
612 $n['last'] = $names[2];
614 // This will handle first and last name or first followed by
615 // multiple names only using just the last of the names in the list.
616 $n['first'] = $names[0];
617 $n['last'] = end($names);
621 if (empty($n['last'])) {
626 // Trim whitespace off the names before returning
627 foreach ($n as $key => $val) {
628 $n[$key] = trim($val);
631 return $n; // associative array containing names
634 function getPatientId($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
637 $sqlBindArray = array();
638 $where = "pubpid LIKE ? ";
639 array_push($sqlBindArray, $pid."%");
640 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
641 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
642 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
643 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
644 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
645 array_push($sqlBindArray, $_SESSION{"authUser"});
649 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
650 if ($limit != "all") {
651 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
654 $rez = sqlStatement($sql, $sqlBindArray);
655 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
656 $returnval[$iter]=$row;
659 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
663 function getByPatientDemographics($searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
665 $layoutCols = sqlStatement(
666 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
670 $sqlBindArray = array();
672 for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
677 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
678 array_push($sqlBindArray, "%".$searchTerm."%");
681 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
682 if ($limit != "all") {
683 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
686 $rez = sqlStatement($sql, $sqlBindArray);
687 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
688 $returnval[$iter]=$row;
691 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
695 function getByPatientDemographicsFilter(
698 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
699 $orderby = "lname ASC, fname ASC",
702 $search_service_code = ''
705 $layoutCols = explode('~', $searchFields);
706 $sqlBindArray = array();
709 foreach ($layoutCols as $val) {
719 $where .= " ".add_escape_custom($val)." = ? ";
720 array_push($sqlBindArray, $searchTerm);
722 $where .= " ".add_escape_custom($val)." like ? ";
723 array_push($sqlBindArray, $searchTerm."%");
729 // If no search terms, ensure valid syntax.
734 // If a non-empty service code was given, then restrict to patients who
735 // have been provided that service. Since the code is used in a LIKE
736 // clause, % and _ wildcards are supported.
737 if ($search_service_code) {
738 $where = "( $where ) AND " .
739 "( SELECT COUNT(*) FROM billing AS b WHERE " .
740 "b.pid = patient_data.pid AND " .
741 "b.activity = 1 AND " .
742 "b.code_type != 'COPAY' AND " .
745 array_push($sqlBindArray, $search_service_code);
748 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
749 if ($limit != "all") {
750 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
753 $rez = sqlStatement($sql, $sqlBindArray);
754 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
755 $returnval[$iter]=$row;
758 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
762 // return a collection of Patient PIDs
763 // new arg style by JRM March 2008
764 // orig function getPatientPID($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
765 function getPatientPID($args)
768 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
769 $orderby = "lname ASC, fname ASC";
773 // alter default values if defined in the passed in args
774 if (isset($args['pid'])) {
778 if (isset($args['given'])) {
779 $given = $args['given'];
782 if (isset($args['orderby'])) {
783 $orderby = $args['orderby'];
786 if (isset($args['limit'])) {
787 $limit = $args['limit'];
790 if (isset($args['start'])) {
791 $start = $args['start'];
797 } elseif (empty($pid)) {
801 if (strstr($pid, "%")) {
805 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
806 if ($limit != "all") {
807 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
810 $rez = sqlStatement($sql);
811 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
812 $returnval[$iter]=$row;
818 /* return a patient's name in the format LAST, FIRST */
819 function getPatientName($pid)
825 $patientData = getPatientPID(array("pid"=>$pid));
826 if (empty($patientData[0]['lname'])) {
830 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
834 /* find patient data by DOB */
835 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
837 $sqlBindArray = array();
838 $where = "DOB like ? ";
839 array_push($sqlBindArray, $DOB."%");
840 if (!empty($GLOBALS['pt_restrict_field'])) {
841 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
842 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
843 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
844 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
845 array_push($sqlBindArray, $_SESSION{"authUser"});
849 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
851 if ($limit != "all") {
852 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
855 $rez = sqlStatement($sql, $sqlBindArray);
856 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
857 $returnval[$iter]=$row;
860 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
864 /* find patient data by SSN */
865 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
867 $sqlBindArray = array();
868 $where = "ss LIKE ?";
869 array_push($sqlBindArray, $ss."%");
870 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
871 if ($limit != "all") {
872 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
875 $rez = sqlStatement($sql, $sqlBindArray);
876 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
877 $returnval[$iter]=$row;
880 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
884 //(CHEMED) Search by phone number
885 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
887 $phone = preg_replace("/[[:punct:]]/", "", $phone);
888 $sqlBindArray = array();
889 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
890 array_push($sqlBindArray, $phone);
891 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
892 if ($limit != "all") {
893 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
896 $rez = sqlStatement($sql, $sqlBindArray);
897 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
898 $returnval[$iter]=$row;
901 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
905 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
907 $sql="select $given from patient_data order by $orderby";
909 if ($limit != "all") {
910 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
913 $rez = sqlStatement($sql);
914 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
915 $returnval[$iter]=$row;
921 //----------------------input functions
922 function newPatientData(
941 $contact_relationship = "",
948 $migrantseasonal = "",
950 $monthly_income = "",
952 $financial_review = "",
966 $drivers_license = "",
973 $referral_source = '';
975 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
976 // Check for brain damage:
977 if ($db_id != $rez['id']) {
978 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
979 $rez['id'] . "' to '$db_id' for pid '$pid'";
983 $fitness = $rez['fitness'];
984 $referral_source = $rez['referral_source'];
987 // Get the default price level.
988 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
989 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
990 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
992 $query = ("replace into patient_data set
1001 postal_code='$postal_code',
1004 country_code='$country_code',
1005 drivers_license='$drivers_license',
1007 occupation='$occupation',
1008 phone_home='$phone_home',
1009 phone_biz='$phone_biz',
1010 phone_contact='$phone_contact',
1012 contact_relationship='$contact_relationship',
1013 referrer='$referrer',
1014 referrerID='$referrerID',
1016 language='$language',
1017 ethnoracial='$ethnoracial',
1018 interpretter='$interpretter',
1019 migrantseasonal='$migrantseasonal',
1020 family_size='$family_size',
1021 monthly_income='$monthly_income',
1022 homeless='$homeless',
1023 financial_review='$financial_review',
1026 providerID = '$providerID',
1027 genericname1 = '$genericname1',
1028 genericval1 = '$genericval1',
1029 genericname2 = '$genericname2',
1030 genericval2 = '$genericval2',
1031 billing_note= '$billing_note',
1032 phone_cell = '$phone_cell',
1033 pharmacy_id = '$pharmacy_id',
1034 hipaa_mail = '$hipaa_mail',
1035 hipaa_voice = '$hipaa_voice',
1036 hipaa_notice = '$hipaa_notice',
1037 hipaa_message = '$hipaa_message',
1040 referral_source='$referral_source',
1042 pricelevel='$pricelevel',
1045 $id = sqlInsert($query);
1048 // find the last inserted id for new patient case
1049 $db_id = getSqlLastID();
1052 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1057 // Supported input date formats are:
1059 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1061 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1063 function fixDate($date, $default = "0000-00-00")
1065 $fixed_date = $default;
1066 $date = trim($date);
1067 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1068 $dmy = preg_split("'[/.-]'", $date);
1070 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1072 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1073 if ($dmy[2] < 1000) {
1077 if ($dmy[2] < 1910) {
1082 // phone_country_code indicates format of ambiguous input dates.
1083 if ($GLOBALS['phone_country_code'] == 1) {
1084 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1086 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1094 function pdValueOrNull($key, $value)
1096 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1097 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1098 (empty($value) || $value == '0000-00-00')) {
1101 return "'" . add_escape_custom($value) . "'";
1105 // Create or update patient data from an array.
1107 function updatePatientData($pid, $new, $create = false)
1109 /*******************************************************************
1110 $real = getPatientData($pid);
1111 foreach ($new as $key => $value)
1112 $real[$key] = $value;
1113 $real['date'] = "'+NOW()+'";
1115 $sql = "insert into patient_data set ";
1116 foreach ($real as $key => $value)
1117 $sql .= $key." = '$value', ";
1118 $sql = substr($sql, 0, -2);
1119 return sqlInsert($sql);
1120 *******************************************************************/
1122 // The above was broken, though seems intent to insert a new patient_data
1123 // row for each update. A good idea, but nothing is doing that yet so
1124 // the code below does not yet attempt it.
1127 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1128 foreach ($new as $key => $value) {
1133 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1136 $db_id = sqlInsert($sql);
1138 $db_id = $new['id'];
1139 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1140 // Check for brain damage:
1141 if ($pid != $rez['pid']) {
1142 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1143 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1147 $sql = "UPDATE patient_data SET date = NOW()";
1148 foreach ($new as $key => $value) {
1149 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1152 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1159 function newEmployerData(
1169 return sqlInsert("insert into employer_data set
1172 postal_code='$postal_code',
1181 // Create or update employer data from an array.
1183 function updateEmployerData($pid, $new, $create = false)
1185 $colnames = array('name','street','city','state','postal_code','country');
1188 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1189 foreach ($colnames as $key) {
1190 $value = isset($new[$key]) ? $new[$key] : '';
1191 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1194 return sqlInsert("INSERT INTO employer_data SET $set");
1197 $old = getEmployerData($pid);
1199 foreach ($colnames as $key) {
1200 $value = empty($old[$key]) ? '' : $old[$key];
1201 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1202 $value = $new[$key];
1206 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1210 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1211 return sqlInsert("INSERT INTO employer_data SET $set");
1218 // This updates or adds the given insurance data info, while retaining any
1219 // previously added insurance_data rows that should be preserved.
1220 // This does not directly support the maintenance of non-current insurance.
1222 function newInsuranceData(
1226 $policy_number = "",
1229 $subscriber_lname = "",
1230 $subscriber_mname = "",
1231 $subscriber_fname = "",
1232 $subscriber_relationship = "",
1233 $subscriber_ss = "",
1234 $subscriber_DOB = "",
1235 $subscriber_street = "",
1236 $subscriber_postal_code = "",
1237 $subscriber_city = "",
1238 $subscriber_state = "",
1239 $subscriber_country = "",
1240 $subscriber_phone = "",
1241 $subscriber_employer = "",
1242 $subscriber_employer_street = "",
1243 $subscriber_employer_city = "",
1244 $subscriber_employer_postal_code = "",
1245 $subscriber_employer_state = "",
1246 $subscriber_employer_country = "",
1248 $subscriber_sex = "",
1249 $effective_date = "0000-00-00",
1250 $accept_assignment = "TRUE",
1254 if (strlen($type) <= 0) {
1258 // If empty dates were passed, then zero them.
1259 if (empty($effective_date)) {
1260 $effective_date = '0000-00-00';
1262 if (empty($subscriber_DOB)) {
1263 $subscriber_DOB = '0000-00-00';
1266 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1267 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1268 $idrow = sqlFetchArray($idres);
1270 // Replace the most recent entry in any of the following cases:
1271 // * Its effective date is >= this effective date.
1272 // * It is the first entry and it has no (insurance) provider.
1273 // * There is no encounter that is earlier than the new effective date but
1274 // on or after the old effective date.
1275 // Otherwise insert a new entry.
1279 if (strcmp($idrow['date'], $effective_date) > 0) {
1282 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1285 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1286 "WHERE pid = ? AND date < ? AND " .
1287 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1288 if ($ferow['count'] == 0) {
1296 // TBD: This is a bit dangerous in that a typo in entering the effective
1297 // date can wipe out previous insurance history. So we want some data
1298 // entry validation somewhere.
1299 sqlStatement("DELETE FROM insurance_data WHERE " .
1300 "pid = ? AND type = ? AND date >= ? AND " .
1301 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1304 $data['type'] = $type;
1305 $data['provider'] = $provider;
1306 $data['policy_number'] = $policy_number;
1307 $data['group_number'] = $group_number;
1308 $data['plan_name'] = $plan_name;
1309 $data['subscriber_lname'] = $subscriber_lname;
1310 $data['subscriber_mname'] = $subscriber_mname;
1311 $data['subscriber_fname'] = $subscriber_fname;
1312 $data['subscriber_relationship'] = $subscriber_relationship;
1313 $data['subscriber_ss'] = $subscriber_ss;
1314 $data['subscriber_DOB'] = $subscriber_DOB;
1315 $data['subscriber_street'] = $subscriber_street;
1316 $data['subscriber_postal_code'] = $subscriber_postal_code;
1317 $data['subscriber_city'] = $subscriber_city;
1318 $data['subscriber_state'] = $subscriber_state;
1319 $data['subscriber_country'] = $subscriber_country;
1320 $data['subscriber_phone'] = $subscriber_phone;
1321 $data['subscriber_employer'] = $subscriber_employer;
1322 $data['subscriber_employer_city'] = $subscriber_employer_city;
1323 $data['subscriber_employer_street'] = $subscriber_employer_street;
1324 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1325 $data['subscriber_employer_state'] = $subscriber_employer_state;
1326 $data['subscriber_employer_country'] = $subscriber_employer_country;
1327 $data['copay'] = $copay;
1328 $data['subscriber_sex'] = $subscriber_sex;
1329 $data['pid'] = $pid;
1330 $data['date'] = $effective_date;
1331 $data['accept_assignment'] = $accept_assignment;
1332 $data['policy_type'] = $policy_type;
1333 updateInsuranceData($idrow['id'], $data);
1334 return $idrow['id'];
1336 return sqlInsert("INSERT INTO insurance_data SET
1337 type = '" . add_escape_custom($type) . "',
1338 provider = '" . add_escape_custom($provider) . "',
1339 policy_number = '" . add_escape_custom($policy_number) . "',
1340 group_number = '" . add_escape_custom($group_number) . "',
1341 plan_name = '" . add_escape_custom($plan_name) . "',
1342 subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1343 subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1344 subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1345 subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1346 subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1347 subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1348 subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1349 subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1350 subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1351 subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1352 subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1353 subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1354 subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1355 subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1356 subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1357 subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1358 subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1359 subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1360 copay = '" . add_escape_custom($copay) . "',
1361 subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1362 pid = '" . add_escape_custom($pid) . "',
1363 date = '" . add_escape_custom($effective_date) . "',
1364 accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1365 policy_type = '" . add_escape_custom($policy_type) . "'
1370 // This is used internally only.
1371 function updateInsuranceData($id, $new)
1373 $fields = sqlListFields("insurance_data");
1376 foreach ($new as $key => $value) {
1377 if (in_array($key, $fields)) {
1378 $use[$key] = $value;
1382 $sql = "UPDATE insurance_data SET ";
1383 foreach ($use as $key => $value) {
1384 $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1387 $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1392 function newHistoryData($pid, $new = false)
1394 $arraySqlBind = array();
1395 $sql = "insert into history_data set pid = ?, date = NOW()";
1396 array_push($arraySqlBind, $pid);
1398 foreach ($new as $key => $value) {
1399 array_push($arraySqlBind, $value);
1400 $sql .= ", `$key` = ?";
1404 return sqlInsert($sql, $arraySqlBind);
1407 function updateHistoryData($pid, $new)
1409 $real = getHistoryData($pid);
1410 foreach ($new as $key => $value) {
1411 $real[$key] = $value;
1415 // need to unset date, so can reset it below
1416 unset($real['date']);
1418 $arraySqlBind = array();
1419 $sql = "insert into history_data set `date` = NOW(), ";
1420 foreach ($real as $key => $value) {
1421 array_push($arraySqlBind, $value);
1422 $sql .= "`$key` = ?, ";
1425 $sql = substr($sql, 0, -2);
1427 return sqlInsert($sql, $arraySqlBind);
1431 // in months if < 2 years old
1432 // in years if > 2 years old
1433 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1434 // (optional) nowYMD is a date in YYYYMMDD format
1435 function getPatientAge($dobYMD, $nowYMD = null)
1437 // strip any dashes from the DOB
1438 $dobYMD = preg_replace("/-/", "", $dobYMD);
1439 $dobDay = substr($dobYMD, 6, 2);
1440 $dobMonth = substr($dobYMD, 4, 2);
1441 $dobYear = substr($dobYMD, 0, 4);
1443 // set the 'now' date values
1444 if ($nowYMD == null) {
1445 $nowDay = date("d");
1446 $nowMonth = date("m");
1447 $nowYear = date("Y");
1449 $nowDay = substr($nowYMD, 6, 2);
1450 $nowMonth = substr($nowYMD, 4, 2);
1451 $nowYear = substr($nowYMD, 0, 4);
1454 $dayDiff = $nowDay - $dobDay;
1455 $monthDiff = $nowMonth - $dobMonth;
1456 $yearDiff = $nowYear - $dobYear;
1458 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1460 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1465 if ($ageInMonths > 24) {
1467 if (($monthDiff == 0) && ($dayDiff < 0)) {
1469 } else if ($monthDiff < 0) {
1473 $age = "$ageInMonths " . xl('month');
1480 * Wrapper to make sure the clinical rules dates formats corresponds to the
1481 * format expected by getPatientAgeYMD
1483 * @param string $dob date of birth
1484 * @param string $target date to calculate age on
1485 * @return array containing
1486 * age - decimal age in years
1487 * age_in_months - decimal age in months
1488 * ageinYMD - formatted string #y #m #d */
1489 function parseAgeInfo($dob, $target)
1491 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1492 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1494 // Prepare target (Y-M-D H:M:S)
1495 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1497 return getPatientAgeYMD($dateDOB, $dateTarget);
1504 * @return array containing
1505 * age - decimal age in years
1506 * age_in_months - decimal age in months
1507 * ageinYMD - formatted string #y #m #d
1509 function getPatientAgeYMD($dob, $date = null)
1512 if ($date == null) {
1513 $daynow = date("d");
1514 $monthnow = date("m");
1515 $yearnow = date("Y");
1516 $datenow=$yearnow.$monthnow.$daynow;
1518 $datenow=preg_replace("/-/", "", $date);
1519 $yearnow=substr($datenow, 0, 4);
1520 $monthnow=substr($datenow, 4, 2);
1521 $daynow=substr($datenow, 6, 2);
1522 $datenow=$yearnow.$monthnow.$daynow;
1525 $dob=preg_replace("/-/", "", $dob);
1526 $dobyear=substr($dob, 0, 4);
1527 $dobmonth=substr($dob, 4, 2);
1528 $dobday=substr($dob, 6, 2);
1529 $dob=$dobyear.$dobmonth.$dobday;
1531 //to compensate for 30, 31, 28, 29 days/month
1532 $mo=$monthnow; //to avoid confusion with later calculation
1534 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1535 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1536 } // look at April, June, September, November for calculation. These months only have 30 days.
1537 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1538 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1539 if (is_int($check_leap_Y)) {
1541 } //If it true then this is the leap year
1544 } //otherwise, it is not a leap year.
1547 } // other months have 31 days
1549 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1550 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1551 $age_year = $yearnow - $dobyear - 1;
1552 if ($daynow < $dobday) {
1553 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1554 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1556 $months_since_birthday=12 - $dobmonth + $monthnow;
1557 $days_since_dobday=$daynow - $dobday;
1559 } else // if patient has had birthday this calandar year
1561 $age_year = $yearnow - $dobyear;
1562 if ($daynow < $dobday) {
1563 $months_since_birthday=$monthnow - $dobmonth -1;
1564 $days_since_dobday=$nd - $dobday + $daynow;
1566 $months_since_birthday=$monthnow - $dobmonth;
1567 $days_since_dobday=$daynow - $dobday;
1571 $day_as_month_decimal = $days_since_dobday / 30;
1572 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1573 $month_as_year_decimal = $months_since_birthday_float / 12;
1574 $age_float = $age_year + $month_as_year_decimal;
1576 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1577 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1578 $age = round($age_float, 2);
1580 // round the years to 2 floating points
1581 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1582 return compact('age', 'age_in_months', 'ageinYMD');
1585 // Returns Age in days
1586 // in months if < 2 years old
1587 // in years if > 2 years old
1588 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1589 // (optional) nowYMD is a date in YYYYMMDD format
1590 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1594 // strip any dashes from the DOB
1595 $dobYMD = preg_replace("/-/", "", $dobYMD);
1596 $dobDay = substr($dobYMD, 6, 2);
1597 $dobMonth = substr($dobYMD, 4, 2);
1598 $dobYear = substr($dobYMD, 0, 4);
1600 // set the 'now' date values
1601 if ($nowYMD == null) {
1602 $nowDay = date("d");
1603 $nowMonth = date("m");
1604 $nowYear = date("Y");
1606 $nowDay = substr($nowYMD, 6, 2);
1607 $nowMonth = substr($nowYMD, 4, 2);
1608 $nowYear = substr($nowYMD, 0, 4);
1612 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1613 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1614 $timediff = $nowtime - $dobtime;
1615 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1620 * Returns a string to be used to display a patient's age
1622 * @param type $dobYMD
1623 * @param type $asOfYMD
1624 * @return string suitable for displaying patient's age based on preferences
1626 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1628 if ($GLOBALS['age_display_format']=='1') {
1629 $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1630 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1631 return $ageYMD['ageinYMD'];
1633 return getPatientAge($dobYMD, $asOfYMD);
1636 return getPatientAge($dobYMD, $asOfYMD);
1639 function dateToDB($date)
1641 $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1646 // ----------------------------------------------------------------------------
1648 * DROPDOWN FOR COUNTRIES
1650 * build a dropdown with all countries from geo_country_reference
1652 * @param int $selected - id for selected record
1653 * @param string $name - the name/id for select form
1654 * @return void - just echo the html encoded string
1656 function dropdown_countries($selected = 0, $name = 'country_code')
1658 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1660 $string = "<select name='$name' id='$name'>";
1661 while ($row = sqlFetchArray($r)) {
1662 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1663 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1666 $string .= '</select>';
1671 // ----------------------------------------------------------------------------
1673 * DROPDOWN FOR YES/NO
1675 * build a dropdown with two options (yes - 1, no - 0)
1677 * @param int $selected - id for selected record
1678 * @param string $name - the name/id for select form
1679 * @return void - just echo the html encoded string
1681 function dropdown_yesno($selected = 0, $name = 'yesno')
1683 $string = "<select name='$name' id='$name'>";
1685 $selected = (int)$selected;
1686 if ($selected == 0) {
1687 $sel1 = 'selected="selected"';
1690 $sel2 = 'selected="selected"';
1694 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1695 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1696 $string .= '</select>';
1701 // ----------------------------------------------------------------------------
1703 * DROPDOWN FOR MALE/FEMALE options
1705 * build a dropdown with three options (unselected/male/female)
1707 * @param int $selected - id for selected record
1708 * @param string $name - the name/id for select form
1709 * @return void - just echo the html encoded string
1711 function dropdown_sex($selected = 0, $name = 'sex')
1713 $string = "<select name='$name' id='$name'>";
1715 if ($selected == 1) {
1716 $sel1 = 'selected="selected"';
1719 } else if ($selected == 2) {
1720 $sel2 = 'selected="selected"';
1724 $sel0 = 'selected="selected"';
1729 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1730 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1731 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1732 $string .= '</select>';
1737 // ----------------------------------------------------------------------------
1739 * DROPDOWN FOR MARITAL STATUS
1741 * build a dropdown with marital status
1743 * @param int $selected - id for selected record
1744 * @param string $name - the name/id for select form
1745 * @return void - just echo the html encoded string
1747 function dropdown_marital($selected = 0, $name = 'status')
1749 $string = "<select name='$name' id='$name'>";
1751 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1753 foreach ($statii as $st) {
1754 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1755 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1758 $string .= '</select>';
1763 // ----------------------------------------------------------------------------
1765 * DROPDOWN FOR PROVIDERS
1767 * build a dropdown with all providers
1769 * @param int $selected - id for selected record
1770 * @param string $name - the name/id for select form
1771 * @return void - just echo the html encoded string
1773 function dropdown_providers($selected = 0, $name = 'status')
1775 $provideri = getProviderInfo();
1777 $string = "<select name='$name' id='$name'>";
1778 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1779 foreach ($provideri as $s) {
1780 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1781 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1784 $string .= '</select>';
1789 // ----------------------------------------------------------------------------
1791 * DROPDOWN FOR INSURANCE COMPANIES
1793 * build a dropdown with all insurers
1795 * @param int $selected - id for selected record
1796 * @param string $name - the name/id for select form
1797 * @return void - just echo the html encoded string
1799 function dropdown_insurance($selected = 0, $name = 'iprovider')
1801 $insurancei = getInsuranceProviders();
1803 $string = "<select name='$name' id='$name'>";
1804 $string .= '<option value="0">Onbekend</option>';
1805 foreach ($insurancei as $iid => $iname) {
1806 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1807 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1810 $string .= '</select>';
1816 // ----------------------------------------------------------------------------
1820 * return the name or the country code, function of arguments
1822 * @param int $country_code
1823 * @param string $country_name
1824 * @return string | int - name or code
1826 function country_code($country_code = 0, $country_name = '')
1829 if ($country_code) {
1830 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1832 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1835 $db = $GLOBALS['adodb']['db'];
1836 $result = $db->Execute($sql);
1837 if ($result && !$result->EOF) {
1838 $strint = $result->fields['res'];
1844 function DBToDate($date)
1846 $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1851 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1852 * for the given patient on the given date.
1854 * @param int The PID of the patient.
1855 * @param string Date in yyyy-mm-dd format.
1856 * @return array Array of 0-3 insurance_data rows.
1858 function getEffectiveInsurances($patient_id, $encdate)
1861 foreach (array('primary','secondary','tertiary') as $instype) {
1863 "SELECT * FROM insurance_data " .
1864 "WHERE pid = ? AND type = ? " .
1865 "AND date <= ? ORDER BY date DESC LIMIT 1",
1866 array($patient_id, $instype, $encdate)
1868 if (empty($tmp['provider'])) {
1879 * Get the patient's balance due. Normally this excludes amounts that are out
1880 * to insurance. If you want to include what insurance owes, set the second
1881 * parameter to true.
1883 * @param int The PID of the patient.
1884 * @param boolean Indicates if amounts owed by insurance are to be included.
1885 * @return number The balance.
1887 function get_patient_balance($pid, $with_insurance = false)
1890 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1891 "last_level_closed, stmt_count " .
1892 "FROM form_encounter WHERE pid = ?", array($pid));
1893 while ($ferow = sqlFetchArray($feres)) {
1894 $encounter = $ferow['encounter'];
1895 $dos = substr($ferow['date'], 0, 10);
1896 $insarr = getEffectiveInsurances($pid, $dos);
1897 $inscount = count($insarr);
1898 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1899 // It's out to insurance so only the co-pay might be due.
1901 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1902 "pid = ? AND encounter = ? AND " .
1903 "code_type = 'copay' AND activity = 1",
1904 array($pid, $encounter)
1907 "SELECT SUM(pay_amount) AS payments " .
1908 "FROM ar_activity WHERE " .
1909 "pid = ? AND encounter = ? AND payer_type = 0",
1910 array($pid, $encounter)
1912 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1917 // Including insurance or not out to insurance, everything is due.
1918 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1919 "pid = ? AND encounter = ? AND " .
1920 "activity = 1", array($pid, $encounter));
1921 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1922 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1923 "pid = ? AND encounter = ?", array($pid, $encounter));
1924 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1925 "pid = ? AND encounter = ?", array($pid, $encounter));
1926 $balance += $brow['amount'] + $srow['amount']
1927 - $drow['payments'] - $drow['adjustments'];
1931 return sprintf('%01.2f', $balance);
1934 // Function to check if patient is deceased.
1936 // $pid - patient id
1937 // $date - date checking if deceased (will default to current date if blank)
1939 // If deceased, then will return the number of
1940 // days that patient has been deceased.
1941 // If not deceased, then will return false.
1942 function is_patient_deceased($pid, $date = '')
1945 // Set date to current if not set
1946 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1948 // Query for deceased status (gets days deceased if patient is deceased)
1949 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1950 "FROM `patient_data` " .
1951 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1953 if (empty($results)) {
1954 // Patient is alive, so return false
1957 // Patient is dead, so return the number of days patient has been deceased.
1958 // Don't let it be zero days or else will confuse calls to this function.
1959 if ($results['days_deceased'] === 0) {
1960 $results['days_deceased'] = 1;
1963 return $results['days_deceased'];