4 * patient.inc includes functions for manipulating patient information.
7 * @link http://www.open-emr.org
8 * @author Brady Miller <brady.g.miller@gmail.com>
9 * @author Sherwin Gaddis <sherwingaddis@gmail.com>
10 * @author Stephen Waite <stephen.waite@cmsvt.com>
11 * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>
12 * @copyright Copyright (c) 2019 Sherwin Gaddis <sherwingaddis@gmail.com>
13 * @copyright Copyright (c) 2018-2021 Stephen Waite <stephen.waite@cmsvt.com>
14 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
17 use OpenEMR\Common\Uuid\UuidRegistry;
18 use OpenEMR\Services\FacilityService;
19 use OpenEMR\Services\PatientService;
21 $facilityService = new FacilityService();
23 // These are for sports team use:
24 $PLAYER_FITNESSES = array(
27 xl('Restricted Training'),
31 xl('International Duty')
33 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
35 // Hard-coding this array because its values and meanings are fixed by the 837p
36 // standard and we don't want people messing with them.
37 $policy_types = array(
39 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
40 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
41 '14' => xl('No-fault Insurance including Auto is Primary'),
42 '15' => xl('Worker`s Compensation'),
43 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
44 '41' => xl('Black Lung'),
45 '42' => xl('Veteran`s Administration'),
46 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
47 '47' => xl('Other Liability Insurance is Primary'),
51 * Get a patient's demographic data.
53 * @param int $pid The PID of the patient
54 * @param string $given an optional subsection of the patient's demographic
56 * @return array The requested subsection of a patient's demographic data.
57 * If no subsection was given, returns everything, with the
58 * date of birth as the last field.
60 // To prevent sql injection on this function, if a variable is used for $given parameter, then
61 // it needs to be escaped via whitelisting prior to using this function.
62 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
64 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
65 return sqlQuery($sql, array($pid));
68 function getInsuranceProvider($ins_id)
71 $sql = "select name from insurance_companies where id=?";
72 $row = sqlQuery($sql, array($ins_id));
76 function getInsuranceProviders()
81 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
82 $rez = sqlStatement($sql);
83 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
84 $returnval[$row['id']] = $row['name'];
86 } else { // Please leave this here. I have a user who wants to see zip codes and PO
87 // box numbers listed along with the insurance company names, as many companies
88 // have different billing addresses for different plans. -- Rod Roark
89 $sql = "select insurance_companies.name, insurance_companies.id, " .
90 "addresses.zip, addresses.line1 " .
91 "from insurance_companies, addresses " .
92 "where addresses.foreign_id = insurance_companies.id " .
93 "order by insurance_companies.name, addresses.zip";
95 $rez = sqlStatement($sql);
97 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
98 preg_match("/\d+/", $row['line1'], $matches);
99 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
100 "," . $matches[0] . ")";
107 function getInsuranceProvidersExtra()
109 $returnval = array();
110 // add a global and if for where to allow inactive inscompanies
112 $sql = "SELECT insurance_companies.name, insurance_companies.id, insurance_companies.cms_id,
113 addresses.line1, addresses.line2, addresses.city, addresses.state, addresses.zip
114 FROM insurance_companies, addresses
115 WHERE addresses.foreign_id = insurance_companies.id
116 AND insurance_companies.inactive != 1
117 ORDER BY insurance_companies.name, addresses.zip";
119 $rez = sqlStatement($sql);
121 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
122 switch ($GLOBALS['insurance_information']) {
123 case $GLOBALS['insurance_information'] = '0':
124 $returnval[$row['id']] = $row['name'];
126 case $GLOBALS['insurance_information'] = '1':
127 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
129 case $GLOBALS['insurance_information'] = '2':
130 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
132 case $GLOBALS['insurance_information'] = '3':
133 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
135 case $GLOBALS['insurance_information'] = '4':
136 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
137 ", " . $row['zip'] . ")";
139 case $GLOBALS['insurance_information'] = '5':
140 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
141 ", " . $row['state'] . ", " . $row['zip'] . ")";
143 case $GLOBALS['insurance_information'] = '6':
144 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
145 ", " . $row['state'] . ", " . $row['zip'] . ", " . $row['cms_id'] . ")";
147 case $GLOBALS['insurance_information'] = '7':
148 preg_match("/\d+/", $row['line1'], $matches);
149 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
150 "," . $matches[0] . ")";
158 // ----------------------------------------------------------------------------
159 // Get one facility row. If the ID is not specified, then get either the
160 // "main" (billing) facility, or the default facility of the currently
161 // logged-in user. This was created to support genFacilityTitle() but
162 // may find additional uses.
164 function getFacility($facid = 0)
166 global $facilityService;
171 return $facilityService->getById($facid);
174 if ($GLOBALS['login_into_facility']) {
175 //facility is saved in sessions
176 $facility = $facilityService->getById($_SESSION['facilityId']);
179 $facility = $facilityService->getPrimaryBillingLocation();
181 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
188 // Generate a report title including report name and facility name, address
191 function genFacilityTitle($repname = '', $facid = 0, $logo = '')
194 $s .= "<table class='ftitletable'>\n";
197 $s .= " <td class='ftitlecell1'>" . text($repname) . "</td>\n";
199 $s .= " <td class='ftitlecell1'>" . $logo . "</td>\n";
200 $s .= " <td class='ftitlecellm'>" . text($repname) . "</td>\n";
202 $s .= " <td class='ftitlecell2'>\n";
203 $r = getFacility($facid);
205 $s .= "<b>" . text($r['name']) . "</b>\n";
207 $s .= "<br />" . text($r['street']) . "\n";
210 if ($r['city'] || $r['state'] || $r['postal_code']) {
213 $s .= text($r['city']);
221 $s .= text($r['state']);
224 if ($r['postal_code']) {
225 $s .= " " . text($r['postal_code']);
231 if ($r['country_code']) {
232 $s .= "<br />" . text($r['country_code']) . "\n";
235 if (preg_match('/[1-9]/', $r['phone'])) {
236 $s .= "<br />" . text($r['phone']) . "\n";
249 returns all facilities or just the id for the first one
250 (FACILITY FILTERING (lemonsoftware))
252 @param string - if 'first' return first facility ordered by id
253 @return array | int for 'first' case
255 function getFacilities($first = '')
257 global $facilityService;
259 $fres = $facilityService->getAllFacility();
261 if ($first == 'first') {
262 return $fres[0]['id'];
268 //(CHEMED) facility filter
269 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
272 if ($providers_only === 'any') {
273 $param1 = " AND authorized = 1 AND active = 1 ";
274 } elseif ($providers_only) {
275 $param1 = " AND authorized = 1 AND calendar = 1 ";
278 //--------------------------------
279 //(CHEMED) facility filter
282 if ($GLOBALS['restrict_user_facility']) {
283 $param2 = " AND (facility_id = '" . add_escape_custom($facility) . "' OR '" . add_escape_custom($facility) . "' IN (select facility_id from users_facility where tablename = 'users' and table_id = id))";
285 $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
289 //--------------------------------
292 if ($providerID == "%") {
296 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
297 "from users where username != '' and active = 1 and id $command '" .
298 add_escape_custom($providerID) . "' " . $param1 . $param2;
299 // sort by last name -- JRM June 2008
300 $query .= " ORDER BY lname, fname ";
301 $rez = sqlStatement($query);
302 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
303 $returnval[$iter] = $row;
306 //if only one result returned take the key/value pairs in array [0] and merge them down into
307 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
310 $akeys = array_keys($returnval[0]);
311 foreach ($akeys as $key) {
312 $returnval[0][$key] = $returnval[0][$key];
319 function getProviderName($providerID, $provider_only = 'any')
321 $pi = getProviderInfo($providerID, $provider_only);
322 if (strlen($pi[0]["lname"]) > 0) {
323 if (strlen($pi[0]["suffix"]) > 0) {
324 $pi[0]["lname"] .= ", " . $pi[0]["suffix"];
327 return $pi[0]['fname'] . " " . $pi[0]['lname'];
333 function getProviderId($providerName)
335 $query = "select id from users where username = ?";
336 $rez = sqlStatement($query, array($providerName));
337 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
338 $returnval[$iter] = $row;
344 // To prevent sql injection on this function, if a variable is used for $given parameter, then
345 // it needs to be escaped via whitelisting prior to using this function; see lines 2020-2121 of
346 // library/clinical_rules.php script for example of this.
347 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
350 if ($given == 'tobacco') {
351 $where = 'tobacco is not null and';
354 if ($dateStart && $dateEnd) {
355 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
356 } elseif ($dateStart && !$dateEnd) {
357 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
358 } elseif (!$dateStart && $dateEnd) {
359 $res = sqlQuery("select $given from history_data where $where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
361 $res = sqlQuery("select $given from history_data where $where pid=? order by date DESC limit 0,1", array($pid));
367 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
368 // To prevent sql injection on this function, if a variable is used for $given parameter, then
369 // it needs to be escaped via whitelisting prior to using this function.
370 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
372 $sql = "select $given from insurance_data as insd " .
373 "left join insurance_companies as ic on ic.id = insd.provider " .
374 "where pid = ? and type = ? order by date DESC limit 1";
375 return sqlQuery($sql, array($pid, $type));
378 // To prevent sql injection on this function, if a variable is used for $given parameter, then
379 // it needs to be escaped via whitelisting prior to using this function.
380 function getInsuranceDataByDate(
384 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
386 // this must take the date in the following manner: YYYY-MM-DD
387 // this function recalls the insurance value that was most recently enterred from the
388 // given date. it will call up most recent records up to and on the date given,
389 // but not records enterred after the given date
390 $sql = "select $given from insurance_data as insd " .
391 "left join insurance_companies as ic on ic.id = provider " .
392 "where pid = ? and (date_format(date,'%Y-%m-%d') <= ? OR date IS NULL) and " .
393 "type=? order by date DESC limit 1";
394 return sqlQuery($sql, array($pid,$date,$type));
397 // To prevent sql injection on this function, if a variable is used for $given parameter, then
398 // it needs to be escaped via whitelisting prior to using this function.
399 function getEmployerData($pid, $given = "*")
401 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
402 return sqlQuery($sql, array($pid));
405 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
407 // When the limit is exceeded, find out what the unlimited count would be.
408 $GLOBALS['PATIENT_INC_COUNT'] = $count;
409 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
410 if ($limit != "all") {
411 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
412 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
417 * Allow the last name to be followed by a comma and some part of a first name(can
418 * also place middle name after the first name with a space separating them)
419 * Allows comma alone followed by some part of a first name(can also place middle name
420 * after the first name with a space separating them).
421 * Allows comma alone preceded by some part of a last name.
422 * If no comma or space, then will search both last name and first name.
423 * If the first letter of either name is capital, searches for name starting
424 * with given substring (the expected behavior). If it is lower case, it
425 * searches for the substring anywhere in the name. This applies to either
426 * last name, first name, and middle name.
427 * Also allows first name followed by middle and/or last name when separated by spaces.
428 * @param string $term
429 * @param string $given
430 * @param string $orderby
431 * @param string $limit
432 * @param string $start
435 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
436 // it needs to be escaped via whitelisting prior to using this function.
437 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")
439 $names = getPatientNameSplit($term);
441 foreach ($names as $key => $val) {
443 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
444 $names[$key] = '%' . $val . '%';
446 $names[$key] = $val . '%';
451 // Debugging section below
452 //if(array_key_exists('first',$names)) {
453 // error_log("first name search term :".$names['first']);
455 //if(array_key_exists('middle',$names)) {
456 // error_log("middle name search term :".$names['middle']);
458 //if(array_key_exists('last',$names)) {
459 // error_log("last name search term :".$names['last']);
461 // Debugging section above
463 $sqlBindArray = array();
464 if (array_key_exists('last', $names) && $names['last'] == '') {
465 // Do not search last name
466 $where = "fname LIKE ? ";
467 array_push($sqlBindArray, $names['first']);
468 if ($names['middle'] != '') {
469 $where .= "AND mname LIKE ? ";
470 array_push($sqlBindArray, $names['middle']);
472 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
473 // Do not search first name or middle name
474 $where = "lname LIKE ? ";
475 array_push($sqlBindArray, $names['last']);
476 } elseif (empty($names['first']) && !empty($names['last'])) {
477 // Search both first name and last name with same term
478 $names['first'] = $names['last'];
479 $where = "lname LIKE ? OR fname LIKE ? ";
480 array_push($sqlBindArray, $names['last'], $names['first']);
481 } elseif ($names['middle'] != '') {
482 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
483 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
485 $where = "lname LIKE ? AND fname LIKE ? ";
486 array_push($sqlBindArray, $names['last'], $names['first']);
489 if (!empty($GLOBALS['pt_restrict_field'])) {
490 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
491 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
492 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
493 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
494 array_push($sqlBindArray, $_SESSION["authUser"]);
498 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
499 if ($limit != "all") {
500 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
503 $rez = sqlStatement($sql, $sqlBindArray);
505 $returnval = array();
506 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
507 $returnval[$iter] = $row;
510 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
514 * Accept a string used by a search function expected to find a patient name,
515 * then split up the string if a comma or space exists. Return an array having
516 * from 1 to 3 elements, named first, middle, and last.
517 * See above getPatientLnames() function for details on how the splitting occurs.
518 * @param string $term
521 function getPatientNameSplit($term)
524 if (strpos($term, ',') !== false) {
525 $names = explode(',', $term);
526 $n['last'] = $names[0];
527 if (strpos(trim($names[1]), ' ') !== false) {
528 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
530 $n['first'] = $names[1];
532 } elseif (strpos($term, ' ') !== false) {
533 $names = explode(' ', $term);
534 if (count($names) == 1) {
535 $n['last'] = $names[0];
536 } elseif (count($names) == 3) {
537 $n['first'] = $names[0];
538 $n['middle'] = $names[1];
539 $n['last'] = $names[2];
541 // This will handle first and last name or first followed by
542 // multiple names only using just the last of the names in the list.
543 $n['first'] = $names[0];
544 $n['last'] = end($names);
548 if (empty($n['last'])) {
553 // Trim whitespace off the names before returning
554 foreach ($n as $key => $val) {
555 $n[$key] = trim($val);
558 return $n; // associative array containing names
561 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
562 // it needs to be escaped via whitelisting prior to using this function.
563 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")
566 $sqlBindArray = array();
567 $where = "pubpid LIKE ? ";
568 array_push($sqlBindArray, $pid . "%");
569 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
570 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
571 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
572 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
573 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
574 array_push($sqlBindArray, $_SESSION["authUser"]);
578 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
579 if ($limit != "all") {
580 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
583 $rez = sqlStatement($sql, $sqlBindArray);
584 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
585 $returnval[$iter] = $row;
588 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
592 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
593 // it needs to be escaped via whitelisting prior to using this function.
594 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")
596 $layoutCols = sqlStatement(
597 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
601 $sqlBindArray = array();
603 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
608 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
609 array_push($sqlBindArray, "%" . $searchTerm . "%");
612 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
613 if ($limit != "all") {
614 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
617 $rez = sqlStatement($sql, $sqlBindArray);
618 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
619 $returnval[$iter] = $row;
622 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
626 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
627 // it needs to be escaped via whitelisting prior to using this function.
628 function getByPatientDemographicsFilter(
631 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
632 $orderby = "lname ASC, fname ASC",
635 $search_service_code = ''
638 $layoutCols = explode('~', $searchFields);
639 $sqlBindArray = array();
642 foreach ($layoutCols as $val) {
652 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " = ? ";
653 array_push($sqlBindArray, $searchTerm);
655 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " like ? ";
656 array_push($sqlBindArray, $searchTerm . "%");
662 // If no search terms, ensure valid syntax.
667 // If a non-empty service code was given, then restrict to patients who
668 // have been provided that service. Since the code is used in a LIKE
669 // clause, % and _ wildcards are supported.
670 if ($search_service_code) {
671 $where = "( $where ) AND " .
672 "( SELECT COUNT(*) FROM billing AS b WHERE " .
673 "b.pid = patient_data.pid AND " .
674 "b.activity = 1 AND " .
675 "b.code_type != 'COPAY' AND " .
678 array_push($sqlBindArray, $search_service_code);
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 // return a collection of Patient PIDs
696 // new arg style by JRM March 2008
697 // 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")
698 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
699 // it needs to be escaped via whitelisting prior to using this function.
700 function getPatientPID($args)
703 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
704 $orderby = "lname ASC, fname ASC";
708 // alter default values if defined in the passed in args
709 if (isset($args['pid'])) {
713 if (isset($args['given'])) {
714 $given = $args['given'];
717 if (isset($args['orderby'])) {
718 $orderby = $args['orderby'];
721 if (isset($args['limit'])) {
722 $limit = $args['limit'];
725 if (isset($args['start'])) {
726 $start = $args['start'];
732 } elseif (empty($pid)) {
736 if (strstr($pid, "%")) {
740 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
741 if ($limit != "all") {
742 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
745 $rez = sqlStatement($sql);
746 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
747 $returnval[$iter] = $row;
753 /* return a patient's name in the format LAST, FIRST */
754 function getPatientName($pid)
760 $patientData = getPatientPID(array("pid" => $pid));
761 if (empty($patientData[0]['lname'])) {
765 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
769 /* return a patient's name in the format FIRST LAST */
770 function getPatientNameFirstLast($pid)
776 $patientData = getPatientPID(array("pid" => $pid));
777 if (empty($patientData[0]['lname'])) {
781 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
785 /* find patient data by DOB */
786 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
787 // it needs to be escaped via whitelisting prior to using this function.
788 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
790 $sqlBindArray = array();
791 $where = "DOB like ? ";
792 array_push($sqlBindArray, $DOB . "%");
793 if (!empty($GLOBALS['pt_restrict_field'])) {
794 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
795 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
796 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
797 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
798 array_push($sqlBindArray, $_SESSION["authUser"]);
802 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
804 if ($limit != "all") {
805 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
808 $rez = sqlStatement($sql, $sqlBindArray);
809 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
810 $returnval[$iter] = $row;
813 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
817 /* find patient data by SSN */
818 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
819 // it needs to be escaped via whitelisting prior to using this function.
820 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
822 $sqlBindArray = array();
823 $where = "ss LIKE ?";
824 array_push($sqlBindArray, $ss . "%");
825 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
826 if ($limit != "all") {
827 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
830 $rez = sqlStatement($sql, $sqlBindArray);
831 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
832 $returnval[$iter] = $row;
835 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
839 //(CHEMED) Search by phone number
840 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
841 // it needs to be escaped via whitelisting prior to using this function.
842 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
844 $phone = preg_replace("/[[:punct:]]/", "", $phone);
845 $sqlBindArray = array();
846 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
847 array_push($sqlBindArray, $phone);
848 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
849 if ($limit != "all") {
850 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
853 $rez = sqlStatement($sql, $sqlBindArray);
854 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
855 $returnval[$iter] = $row;
858 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
862 //----------------------input functions
863 function newPatientData(
882 $contact_relationship = "",
889 $migrantseasonal = "",
891 $monthly_income = "",
893 $financial_review = "",
907 $drivers_license = "",
914 $referral_source = '';
916 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
917 // Check for brain damage:
918 if ($db_id != $rez['id']) {
919 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
920 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
924 $fitness = $rez['fitness'];
925 $referral_source = $rez['referral_source'];
928 // Get the default price level.
929 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
930 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
931 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
933 $query = ("replace into patient_data set
934 id='" . add_escape_custom($db_id) . "',
935 title='" . add_escape_custom($title) . "',
936 fname='" . add_escape_custom($fname) . "',
937 lname='" . add_escape_custom($lname) . "',
938 mname='" . add_escape_custom($mname) . "',
939 sex='" . add_escape_custom($sex) . "',
940 DOB='" . add_escape_custom($DOB) . "',
941 street='" . add_escape_custom($street) . "',
942 postal_code='" . add_escape_custom($postal_code) . "',
943 city='" . add_escape_custom($city) . "',
944 state='" . add_escape_custom($state) . "',
945 country_code='" . add_escape_custom($country_code) . "',
946 drivers_license='" . add_escape_custom($drivers_license) . "',
947 ss='" . add_escape_custom($ss) . "',
948 occupation='" . add_escape_custom($occupation) . "',
949 phone_home='" . add_escape_custom($phone_home) . "',
950 phone_biz='" . add_escape_custom($phone_biz) . "',
951 phone_contact='" . add_escape_custom($phone_contact) . "',
952 status='" . add_escape_custom($status) . "',
953 contact_relationship='" . add_escape_custom($contact_relationship) . "',
954 referrer='" . add_escape_custom($referrer) . "',
955 referrerID='" . add_escape_custom($referrerID) . "',
956 email='" . add_escape_custom($email) . "',
957 language='" . add_escape_custom($language) . "',
958 ethnoracial='" . add_escape_custom($ethnoracial) . "',
959 interpretter='" . add_escape_custom($interpretter) . "',
960 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
961 family_size='" . add_escape_custom($family_size) . "',
962 monthly_income='" . add_escape_custom($monthly_income) . "',
963 homeless='" . add_escape_custom($homeless) . "',
964 financial_review='" . add_escape_custom($financial_review) . "',
965 pubpid='" . add_escape_custom($pubpid) . "',
966 pid= '" . add_escape_custom($pid) . "',
967 providerID = '" . add_escape_custom($providerID) . "',
968 genericname1 = '" . add_escape_custom($genericname1) . "',
969 genericval1 = '" . add_escape_custom($genericval1) . "',
970 genericname2 = '" . add_escape_custom($genericname2) . "',
971 genericval2 = '" . add_escape_custom($genericval2) . "',
972 billing_note= '" . add_escape_custom($billing_note) . "',
973 phone_cell = '" . add_escape_custom($phone_cell) . "',
974 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
975 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
976 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
977 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
978 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
979 squad = '" . add_escape_custom($squad) . "',
980 fitness='" . add_escape_custom($fitness) . "',
981 referral_source='" . add_escape_custom($referral_source) . "',
982 regdate='" . add_escape_custom($regdate) . "',
983 pricelevel='" . add_escape_custom($pricelevel) . "',
986 $id = sqlInsert($query);
989 // find the last inserted id for new patient case
993 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
995 // set uuid if not set yet (if this was an insert and not an update)
996 if (empty($foo['uuid'])) {
997 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
998 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
1004 // Supported input date formats are:
1006 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1008 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1010 function fixDate($date, $default = "0000-00-00")
1012 $fixed_date = $default;
1013 $date = trim($date);
1014 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1015 $dmy = preg_split("'[/.-]'", $date);
1017 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1019 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1020 if ($dmy[2] < 1000) {
1024 if ($dmy[2] < 1910) {
1029 // phone_country_code indicates format of ambiguous input dates.
1030 if ($GLOBALS['phone_country_code'] == 1) {
1031 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1033 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1041 function pdValueOrNull($key, $value)
1044 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1045 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1046 (empty($value) || $value == '0000-00-00')
1050 return "'" . add_escape_custom($value) . "'";
1055 * Create or update patient data from an array.
1057 * This is a wrapper function for the PatientService which is now the single point
1058 * of patient creation and update.
1060 * If successful, returns the pid of the patient
1064 * @param false $create
1067 function updatePatientData($pid, $new, $create = false)
1069 // Create instance of patient service
1070 $patientService = new PatientService();
1075 $result = $patientService->databaseInsert($new);
1078 $result = $patientService->databaseUpdate($new);
1081 // From the returned patient data array
1082 // retrieve the data and return the pid
1083 $pid = $result['pid'];
1088 function newEmployerData(
1098 return sqlInsert("insert into employer_data set
1099 name='" . add_escape_custom($name) . "',
1100 street='" . add_escape_custom($street) . "',
1101 postal_code='" . add_escape_custom($postal_code) . "',
1102 city='" . add_escape_custom($city) . "',
1103 state='" . add_escape_custom($state) . "',
1104 country='" . add_escape_custom($country) . "',
1105 pid='" . add_escape_custom($pid) . "',
1110 // Create or update employer data from an array.
1112 function updateEmployerData($pid, $new, $create = false)
1114 $colnames = array('name','street','city','state','postal_code','country');
1117 $set = "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1118 foreach ($colnames as $key) {
1119 $value = isset($new[$key]) ? $new[$key] : '';
1120 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1123 return sqlInsert("INSERT INTO employer_data SET $set");
1126 $old = getEmployerData($pid);
1128 foreach ($colnames as $key) {
1129 $value = empty($old[$key]) ? '' : $old[$key];
1130 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1131 $value = $new[$key];
1135 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1139 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1140 return sqlInsert("INSERT INTO employer_data SET $set");
1147 // This updates or adds the given insurance data info, while retaining any
1148 // previously added insurance_data rows that should be preserved.
1149 // This does not directly support the maintenance of non-current insurance.
1151 function newInsuranceData(
1155 $policy_number = "",
1158 $subscriber_lname = "",
1159 $subscriber_mname = "",
1160 $subscriber_fname = "",
1161 $subscriber_relationship = "",
1162 $subscriber_ss = "",
1163 $subscriber_DOB = null,
1164 $subscriber_street = "",
1165 $subscriber_postal_code = "",
1166 $subscriber_city = "",
1167 $subscriber_state = "",
1168 $subscriber_country = "",
1169 $subscriber_phone = "",
1170 $subscriber_employer = "",
1171 $subscriber_employer_street = "",
1172 $subscriber_employer_city = "",
1173 $subscriber_employer_postal_code = "",
1174 $subscriber_employer_state = "",
1175 $subscriber_employer_country = "",
1177 $subscriber_sex = "",
1178 $effective_date = null,
1179 $accept_assignment = "TRUE",
1183 if (strlen($type) <= 0) {
1187 if (is_null($accept_assignment)) {
1188 $accept_assignment = "TRUE";
1190 if (is_null($policy_type)) {
1194 // If empty dates were passed, then null.
1195 if (empty($effective_date)) {
1196 $effective_date = null;
1198 if (empty($subscriber_DOB)) {
1199 $subscriber_DOB = null;
1202 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1203 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1204 $idrow = sqlFetchArray($idres);
1206 // Replace the most recent entry in any of the following cases:
1207 // * Its effective date is >= this effective date.
1208 // * It is the first entry and it has no (insurance) provider.
1209 // * There is no encounter that is earlier than the new effective date but
1210 // on or after the old effective date.
1211 // Otherwise insert a new entry.
1215 // convert date from null to "0000-00-00" for below strcmp and query
1216 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1217 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1218 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1221 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1224 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1225 "WHERE pid = ? AND date < ? AND " .
1226 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1227 if ($ferow['count'] == 0) {
1235 // TBD: This is a bit dangerous in that a typo in entering the effective
1236 // date can wipe out previous insurance history. So we want some data
1237 // entry validation somewhere.
1238 if ($effective_date === null) {
1239 sqlStatement("DELETE FROM insurance_data WHERE " .
1240 "pid = ? AND type = ? AND " .
1241 "id != ?", array($pid, $type, $idrow['id']));
1243 sqlStatement("DELETE FROM insurance_data WHERE " .
1244 "pid = ? AND type = ? AND date >= ? AND " .
1245 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1249 $data['type'] = $type;
1250 $data['provider'] = $provider;
1251 $data['policy_number'] = $policy_number;
1252 $data['group_number'] = $group_number;
1253 $data['plan_name'] = $plan_name;
1254 $data['subscriber_lname'] = $subscriber_lname;
1255 $data['subscriber_mname'] = $subscriber_mname;
1256 $data['subscriber_fname'] = $subscriber_fname;
1257 $data['subscriber_relationship'] = $subscriber_relationship;
1258 $data['subscriber_ss'] = $subscriber_ss;
1259 $data['subscriber_DOB'] = $subscriber_DOB;
1260 $data['subscriber_street'] = $subscriber_street;
1261 $data['subscriber_postal_code'] = $subscriber_postal_code;
1262 $data['subscriber_city'] = $subscriber_city;
1263 $data['subscriber_state'] = $subscriber_state;
1264 $data['subscriber_country'] = $subscriber_country;
1265 $data['subscriber_phone'] = $subscriber_phone;
1266 $data['subscriber_employer'] = $subscriber_employer;
1267 $data['subscriber_employer_city'] = $subscriber_employer_city;
1268 $data['subscriber_employer_street'] = $subscriber_employer_street;
1269 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1270 $data['subscriber_employer_state'] = $subscriber_employer_state;
1271 $data['subscriber_employer_country'] = $subscriber_employer_country;
1272 $data['copay'] = $copay;
1273 $data['subscriber_sex'] = $subscriber_sex;
1274 $data['pid'] = $pid;
1275 $data['date'] = $effective_date;
1276 $data['accept_assignment'] = $accept_assignment;
1277 $data['policy_type'] = $policy_type;
1278 updateInsuranceData($idrow['id'], $data);
1279 return $idrow['id'];
1282 "INSERT INTO `insurance_data` SET `type` = ?,
1284 `policy_number` = ?,
1287 `subscriber_lname` = ?,
1288 `subscriber_mname` = ?,
1289 `subscriber_fname` = ?,
1290 `subscriber_relationship` = ?,
1291 `subscriber_ss` = ?,
1292 `subscriber_DOB` = ?,
1293 `subscriber_street` = ?,
1294 `subscriber_postal_code` = ?,
1295 `subscriber_city` = ?,
1296 `subscriber_state` = ?,
1297 `subscriber_country` = ?,
1298 `subscriber_phone` = ?,
1299 `subscriber_employer` = ?,
1300 `subscriber_employer_city` = ?,
1301 `subscriber_employer_street` = ?,
1302 `subscriber_employer_postal_code` = ?,
1303 `subscriber_employer_state` = ?,
1304 `subscriber_employer_country` = ?,
1306 `subscriber_sex` = ?,
1309 `accept_assignment` = ?,
1320 $subscriber_relationship,
1324 $subscriber_postal_code,
1327 $subscriber_country,
1329 $subscriber_employer,
1330 $subscriber_employer_city,
1331 $subscriber_employer_street,
1332 $subscriber_employer_postal_code,
1333 $subscriber_employer_state,
1334 $subscriber_employer_country,
1346 // This is used internally only.
1347 function updateInsuranceData($id, $new)
1349 $fields = sqlListFields("insurance_data");
1352 foreach ($new as $key => $value) {
1353 if (in_array($key, $fields)) {
1354 $use[$key] = $value;
1359 $sql = "UPDATE insurance_data SET ";
1360 foreach ($use as $key => $value) {
1361 $sql .= "`" . $key . "` = ?, ";
1362 array_push($sqlBindArray, $value);
1365 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1366 array_push($sqlBindArray, $id);
1368 sqlStatement($sql, $sqlBindArray);
1371 function newHistoryData($pid, $new = false)
1373 $arraySqlBind = array();
1374 $sql = "insert into history_data set pid = ?, date = NOW()";
1375 array_push($arraySqlBind, $pid);
1377 foreach ($new as $key => $value) {
1378 array_push($arraySqlBind, $value);
1379 $sql .= ", `$key` = ?";
1383 return sqlInsert($sql, $arraySqlBind);
1386 function updateHistoryData($pid, $new)
1388 $real = getHistoryData($pid);
1389 foreach ($new as $key => $value) {
1390 $real[$key] = $value;
1394 // need to unset date, so can reset it below
1395 unset($real['date']);
1397 $arraySqlBind = array();
1398 $sql = "insert into history_data set `date` = NOW(), ";
1399 foreach ($real as $key => $value) {
1400 array_push($arraySqlBind, $value);
1401 $sql .= "`$key` = ?, ";
1404 $sql = substr($sql, 0, -2);
1406 return sqlInsert($sql, $arraySqlBind);
1410 // in months if < 2 years old
1411 // in years if > 2 years old
1412 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1413 // (optional) nowYMD is a date in YYYYMMDD format
1414 function getPatientAge($dobYMD, $nowYMD = null)
1416 if (empty($dobYMD)) {
1419 // strip any dashes from the DOB
1420 $dobYMD = preg_replace("/-/", "", $dobYMD);
1421 $dobDay = substr($dobYMD, 6, 2);
1422 $dobMonth = substr($dobYMD, 4, 2);
1423 $dobYear = (int) substr($dobYMD, 0, 4);
1425 // set the 'now' date values
1426 if ($nowYMD == null) {
1427 $nowDay = date("d");
1428 $nowMonth = date("m");
1429 $nowYear = date("Y");
1431 $nowDay = substr($nowYMD, 6, 2);
1432 $nowMonth = substr($nowYMD, 4, 2);
1433 $nowYear = substr($nowYMD, 0, 4);
1436 $dayDiff = $nowDay - $dobDay;
1437 $monthDiff = $nowMonth - $dobMonth;
1438 $yearDiff = $nowYear - $dobYear;
1440 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear * 12) + $dobMonth);
1442 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1447 if ($ageInMonths > 24) {
1449 if (($monthDiff == 0) && ($dayDiff < 0)) {
1451 } elseif ($monthDiff < 0) {
1455 $age = "$ageInMonths " . xl('month');
1462 * Wrapper to make sure the clinical rules dates formats corresponds to the
1463 * format expected by getPatientAgeYMD
1465 * @param string $dob date of birth
1466 * @param string $target date to calculate age on
1467 * @return array containing
1468 * age - decimal age in years
1469 * age_in_months - decimal age in months
1470 * ageinYMD - formatted string #y #m #d */
1471 function parseAgeInfo($dob, $target)
1473 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1474 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1476 // Prepare target (Y-M-D H:M:S)
1477 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1479 return getPatientAgeYMD($dateDOB, $dateTarget);
1486 * @return array containing
1487 * age - decimal age in years
1488 * age_in_months - decimal age in months
1489 * ageinYMD - formatted string #y #m #d
1491 function getPatientAgeYMD($dob, $date = null)
1494 if ($date == null) {
1495 $daynow = date("d");
1496 $monthnow = date("m");
1497 $yearnow = date("Y");
1498 $datenow = $yearnow . $monthnow . $daynow;
1500 $datenow = preg_replace("/-/", "", $date);
1501 $yearnow = substr($datenow, 0, 4);
1502 $monthnow = substr($datenow, 4, 2);
1503 $daynow = substr($datenow, 6, 2);
1504 $datenow = $yearnow . $monthnow . $daynow;
1507 $dob = preg_replace("/-/", "", $dob);
1508 $dobyear = substr($dob, 0, 4);
1509 $dobmonth = substr($dob, 4, 2);
1510 $dobday = substr($dob, 6, 2);
1511 $dob = $dobyear . $dobmonth . $dobday;
1513 //to compensate for 30, 31, 28, 29 days/month
1514 $mo = $monthnow; //to avoid confusion with later calculation
1516 if ($mo == 05 or $mo == 07 or $mo == 10 or $mo == 12) { // determined by monthnow-1
1517 $nd = 30; // nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1518 } elseif ($mo == 03) { // look at April, June, September, November for calculation. These months only have 30 days.
1519 // for march, look to the month of February for calculation, check for leap year
1520 $check_leap_Y = $yearnow / 4; // To check if this is a leap year.
1521 if (is_int($check_leap_Y)) { // If it true then this is the leap year
1523 } else { // otherwise, it is not a leap year.
1526 } else { // other months have 31 days
1530 $bdthisyear = $yearnow . $dobmonth . $dobday; //Date current year's birthday falls on
1531 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1532 $age_year = $yearnow - $dobyear - 1;
1533 if ($daynow < $dobday) {
1534 $months_since_birthday = 12 - $dobmonth + $monthnow - 1;
1535 $days_since_dobday = $nd - $dobday + $daynow; //did not take into account for month with 31 days
1537 $months_since_birthday = 12 - $dobmonth + $monthnow;
1538 $days_since_dobday = $daynow - $dobday;
1540 } else // if patient has had birthday this calandar year
1542 $age_year = $yearnow - $dobyear;
1543 if ($daynow < $dobday) {
1544 $months_since_birthday = $monthnow - $dobmonth - 1;
1545 $days_since_dobday = $nd - $dobday + $daynow;
1547 $months_since_birthday = $monthnow - $dobmonth;
1548 $days_since_dobday = $daynow - $dobday;
1552 $day_as_month_decimal = $days_since_dobday / 30;
1553 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1554 $month_as_year_decimal = $months_since_birthday_float / 12;
1555 $age_float = $age_year + $month_as_year_decimal;
1557 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1558 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1559 $age = round($age_float, 2);
1561 // round the years to 2 floating points
1562 $ageinYMD = $age_year . "y " . $months_since_birthday . "m " . $days_since_dobday . "d";
1563 return compact('age', 'age_in_months', 'ageinYMD');
1566 // Returns Age in days
1567 // in months if < 2 years old
1568 // in years if > 2 years old
1569 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1570 // (optional) nowYMD is a date in YYYYMMDD format
1571 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1575 // strip any dashes from the DOB
1576 $dobYMD = preg_replace("/-/", "", $dobYMD);
1577 $dobDay = substr($dobYMD, 6, 2);
1578 $dobMonth = substr($dobYMD, 4, 2);
1579 $dobYear = substr($dobYMD, 0, 4);
1581 // set the 'now' date values
1582 if ($nowYMD == null) {
1583 $nowDay = date("d");
1584 $nowMonth = date("m");
1585 $nowYear = date("Y");
1587 $nowDay = substr($nowYMD, 6, 2);
1588 $nowMonth = substr($nowYMD, 4, 2);
1589 $nowYear = substr($nowYMD, 0, 4);
1593 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1594 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1595 $timediff = $nowtime - $dobtime;
1596 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1601 * Returns a string to be used to display a patient's age
1603 * @param type $dobYMD
1604 * @param type $asOfYMD
1605 * @return string suitable for displaying patient's age based on preferences
1607 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1609 if ($GLOBALS['age_display_format'] == '1') {
1610 $ageYMD = getPatientAgeYMD($dobYMD, $asOfYMD);
1611 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age'] <= $GLOBALS['age_display_limit']) {
1612 return $ageYMD['ageinYMD'];
1614 return getPatientAge($dobYMD, $asOfYMD);
1617 return getPatientAge($dobYMD, $asOfYMD);
1620 function dateToDB($date)
1622 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1627 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1628 * for the given patient on the given date.
1630 * @param int The PID of the patient.
1631 * @param string Date in yyyy-mm-dd format.
1632 * @return array Array of 0-3 insurance_data rows.
1634 function getEffectiveInsurances($patient_id, $encdate)
1637 foreach (array('primary','secondary','tertiary') as $instype) {
1639 "SELECT * FROM insurance_data " .
1640 "WHERE pid = ? AND type = ? " .
1641 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1642 array($patient_id, $instype, $encdate)
1644 if (empty($tmp['provider'])) {
1655 * Get all requisition insurance companies
1660 function getAllinsurances($pid)
1663 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1664 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1665 b.name, c.line1, c.line2, c.city, c.state, c.zip
1666 FROM `insurance_data` AS a
1667 RIGHT JOIN insurance_companies AS b
1668 ON a.provider = b.id
1669 RIGHT JOIN addresses AS c
1670 ON a.provider = c.foreign_id
1672 $inco = sqlStatement($sql, array($pid));
1674 while ($icl = sqlFetchArray($inco)) {
1681 * Get the patient's balance due. Normally this excludes amounts that are out
1682 * to insurance. If you want to include what insurance owes, set the second
1683 * parameter to true.
1685 * @param int The PID of the patient.
1686 * @param boolean Indicates if amounts owed by insurance are to be included.
1687 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1688 * @return number The balance.
1690 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1693 $bindarray = array($pid);
1694 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1695 "last_level_closed, stmt_count " .
1696 "FROM form_encounter WHERE pid = ?";
1698 $sqlstatement .= " AND encounter = ?";
1699 array_push($bindarray, $eid);
1701 $feres = sqlStatement($sqlstatement, $bindarray);
1702 while ($ferow = sqlFetchArray($feres)) {
1703 $encounter = $ferow['encounter'];
1704 $dos = substr($ferow['date'], 0, 10);
1705 $insarr = getEffectiveInsurances($pid, $dos);
1706 $inscount = count($insarr);
1707 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1708 // It's out to insurance so only the co-pay might be due.
1710 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1711 "pid = ? AND encounter = ? AND " .
1712 "code_type = 'copay' AND activity = 1",
1713 array($pid, $encounter)
1716 "SELECT SUM(pay_amount) AS payments " .
1717 "FROM ar_activity WHERE " .
1718 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1719 array($pid, $encounter)
1721 // going to comment this out for now since computing future copays doesn't
1722 // equate to cash in hand, which shows in the Billing widget in dashboard 4-23-21
1723 // $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1725 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1726 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1727 $ptbal = $copay + $amt - $pay;
1728 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1732 // Including insurance or not out to insurance, everything is due.
1733 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1734 "pid = ? AND encounter = ? AND " .
1735 "activity = 1", array($pid, $encounter));
1736 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1737 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1738 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1739 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1740 "pid = ? AND encounter = ?", array($pid, $encounter));
1741 $balance += $brow['amount'] + $srow['amount']
1742 - $drow['payments'] - $drow['adjustments'];
1746 return sprintf('%01.2f', $balance);
1749 function get_patient_balance_excluding($pid, $excluded = -1)
1751 // We join form_encounter here to make sure we only count amounts for
1752 // encounters that exist. We've had some trouble before with encounters
1753 // that were deleted but leaving line items in the database.
1755 "SELECT SUM(b.fee) AS amount " .
1756 "FROM billing AS b, form_encounter AS fe WHERE " .
1757 "b.pid = ? AND b.encounter != 0 AND b.encounter != ? AND b.activity = 1 AND " .
1758 "fe.pid = b.pid AND fe.encounter = b.encounter",
1759 array($pid, $excluded)
1762 "SELECT SUM(s.fee) AS amount " .
1763 "FROM drug_sales AS s, form_encounter AS fe WHERE " .
1764 "s.pid = ? AND s.encounter != 0 AND s.encounter != ? AND " .
1765 "fe.pid = s.pid AND fe.encounter = s.encounter",
1766 array($pid, $excluded)
1769 "SELECT SUM(a.pay_amount) AS payments, " .
1770 "SUM(a.adj_amount) AS adjustments " .
1771 "FROM ar_activity AS a, form_encounter AS fe WHERE " .
1772 "a.deleted IS NULL AND a.pid = ? AND a.encounter != 0 AND a.encounter != ? AND " .
1773 "fe.pid = a.pid AND fe.encounter = a.encounter",
1774 array($pid, $excluded)
1778 $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments']
1782 // Function to check if patient is deceased.
1784 // $pid - patient id
1785 // $date - date checking if deceased (will default to current date if blank)
1787 // If deceased, then will return the number of
1788 // days that patient has been deceased and the deceased date.
1789 // If not deceased, then will return false.
1790 function is_patient_deceased($pid, $date = '')
1793 // Set date to current if not set
1794 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1796 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1797 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1798 "FROM `patient_data` " .
1799 "WHERE `pid` = ? AND " .
1800 dateEmptySql('deceased_date', true, true) .
1801 "AND `deceased_date` <= ?", array($date,$pid,$date));
1803 if (empty($results)) {
1804 // Patient is alive, so return false
1807 // Patient is dead, so return the number of days patient has been deceased.
1808 // Don't let it be zero days or else will confuse calls to this function.
1809 if ($results['days_deceased'] === 0) {
1810 $results['days_deceased'] = 1;