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 * @author Rod Roark <rod@sunsetsystems.com>
12 * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>
13 * @copyright Copyright (c) 2019 Sherwin Gaddis <sherwingaddis@gmail.com>
14 * @copyright Copyright (c) 2018-2021 Stephen Waite <stephen.waite@cmsvt.com>
15 * @copyright Copyright (c) 2021 Rod Roark <rod@sunsetsystems.com>
16 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
19 use OpenEMR\Common\Uuid\UuidRegistry;
20 use OpenEMR\Services\FacilityService;
21 use OpenEMR\Services\PatientService;
22 use OpenEMR\Services\SocialHistoryService;
24 require_once(dirname(__FILE__) . "/dupscore.inc.php");
26 $facilityService = new FacilityService();
28 // These are for sports team use:
29 $PLAYER_FITNESSES = array(
32 xl('Restricted Training'),
36 xl('International Duty')
38 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
40 // Hard-coding this array because its values and meanings are fixed by the 837p
41 // standard and we don't want people messing with them.
42 $policy_types = array(
44 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
45 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
46 '14' => xl('No-fault Insurance including Auto is Primary'),
47 '15' => xl('Worker`s Compensation'),
48 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
49 '41' => xl('Black Lung'),
50 '42' => xl('Veteran`s Administration'),
51 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
52 '47' => xl('Other Liability Insurance is Primary'),
56 * Get a patient's demographic data.
58 * @param int $pid The PID of the patient
59 * @param string $given an optional subsection of the patient's demographic
61 * @return array The requested subsection of a patient's demographic data.
62 * If no subsection was given, returns everything, with the
63 * date of birth as the last field.
65 // To prevent sql injection on this function, if a variable is used for $given parameter, then
66 // it needs to be escaped via whitelisting prior to using this function.
67 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
69 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
70 return sqlQuery($sql, array($pid));
73 function getInsuranceProvider($ins_id)
76 $sql = "select name from insurance_companies where id=?";
77 $row = sqlQuery($sql, array($ins_id));
81 function getInsuranceProviders()
86 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
87 $rez = sqlStatement($sql);
88 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
89 $returnval[$row['id']] = $row['name'];
91 } else { // Please leave this here. I have a user who wants to see zip codes and PO
92 // box numbers listed along with the insurance company names, as many companies
93 // have different billing addresses for different plans. -- Rod Roark
94 $sql = "select insurance_companies.name, insurance_companies.id, " .
95 "addresses.zip, addresses.line1 " .
96 "from insurance_companies, addresses " .
97 "where addresses.foreign_id = insurance_companies.id " .
98 "order by insurance_companies.name, addresses.zip";
100 $rez = sqlStatement($sql);
102 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
103 preg_match("/\d+/", $row['line1'], $matches);
104 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
105 "," . $matches[0] . ")";
112 function getInsuranceProvidersExtra()
114 $returnval = array();
115 // add a global and if for where to allow inactive inscompanies
117 $sql = "SELECT insurance_companies.name, insurance_companies.id, insurance_companies.cms_id,
118 addresses.line1, addresses.line2, addresses.city, addresses.state, addresses.zip
119 FROM insurance_companies, addresses
120 WHERE addresses.foreign_id = insurance_companies.id
121 AND insurance_companies.inactive != 1
122 ORDER BY insurance_companies.name, addresses.zip";
124 $rez = sqlStatement($sql);
126 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
127 switch ($GLOBALS['insurance_information']) {
128 case $GLOBALS['insurance_information'] = '0':
129 $returnval[$row['id']] = $row['name'];
131 case $GLOBALS['insurance_information'] = '1':
132 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
134 case $GLOBALS['insurance_information'] = '2':
135 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
137 case $GLOBALS['insurance_information'] = '3':
138 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
140 case $GLOBALS['insurance_information'] = '4':
141 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
142 ", " . $row['zip'] . ")";
144 case $GLOBALS['insurance_information'] = '5':
145 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
146 ", " . $row['state'] . ", " . $row['zip'] . ")";
148 case $GLOBALS['insurance_information'] = '6':
149 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
150 ", " . $row['state'] . ", " . $row['zip'] . ", " . $row['cms_id'] . ")";
152 case $GLOBALS['insurance_information'] = '7':
153 preg_match("/\d+/", $row['line1'], $matches);
154 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
155 "," . $matches[0] . ")";
163 // ----------------------------------------------------------------------------
164 // Get one facility row. If the ID is not specified, then get either the
165 // "main" (billing) facility, or the default facility of the currently
166 // logged-in user. This was created to support genFacilityTitle() but
167 // may find additional uses.
169 function getFacility($facid = 0)
171 global $facilityService;
176 return $facilityService->getById($facid);
179 if ($GLOBALS['login_into_facility']) {
180 //facility is saved in sessions
181 $facility = $facilityService->getById($_SESSION['facilityId']);
184 $facility = $facilityService->getPrimaryBillingLocation();
186 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
193 // Generate a report title including report name and facility name, address
196 function genFacilityTitle($repname = '', $facid = 0, $logo = '')
199 $s .= "<table class='ftitletable'>\n";
202 $s .= " <td class='ftitlecell1'>" . text($repname) . "</td>\n";
204 $s .= " <td class='ftitlecell1'>" . $logo . "</td>\n";
205 $s .= " <td class='ftitlecellm'>" . text($repname) . "</td>\n";
207 $s .= " <td class='ftitlecell2'>\n";
208 $r = getFacility($facid);
210 $s .= "<b>" . text($r['name']) . "</b>\n";
212 $s .= "<br />" . text($r['street']) . "\n";
215 if ($r['city'] || $r['state'] || $r['postal_code']) {
218 $s .= text($r['city']);
226 $s .= text($r['state']);
229 if ($r['postal_code']) {
230 $s .= " " . text($r['postal_code']);
236 if ($r['country_code']) {
237 $s .= "<br />" . text($r['country_code']) . "\n";
240 if (preg_match('/[1-9]/', $r['phone'])) {
241 $s .= "<br />" . text($r['phone']) . "\n";
254 returns all facilities or just the id for the first one
255 (FACILITY FILTERING (lemonsoftware))
257 @param string - if 'first' return first facility ordered by id
258 @return array | int for 'first' case
260 function getFacilities($first = '')
262 global $facilityService;
264 $fres = $facilityService->getAllFacility();
266 if ($first == 'first') {
267 return $fres[0]['id'];
273 //(CHEMED) facility filter
274 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
277 if ($providers_only === 'any') {
278 $param1 = " AND authorized = 1 AND active = 1 ";
279 } elseif ($providers_only) {
280 $param1 = " AND authorized = 1 AND calendar = 1 ";
283 //--------------------------------
284 //(CHEMED) facility filter
287 if ($GLOBALS['restrict_user_facility']) {
288 $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))";
290 $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
294 //--------------------------------
297 if ($providerID == "%") {
301 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
302 "from users where username != '' and active = 1 and id $command '" .
303 add_escape_custom($providerID) . "' " . $param1 . $param2;
304 // sort by last name -- JRM June 2008
305 $query .= " ORDER BY lname, fname ";
306 $rez = sqlStatement($query);
307 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
308 $returnval[$iter] = $row;
311 //if only one result returned take the key/value pairs in array [0] and merge them down into
312 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
315 $akeys = array_keys($returnval[0]);
316 foreach ($akeys as $key) {
317 $returnval[0][$key] = $returnval[0][$key];
324 function getProviderName($providerID, $provider_only = 'any')
326 $pi = getProviderInfo($providerID, $provider_only);
327 if (strlen($pi[0]["lname"]) > 0) {
328 if (strlen($pi[0]["suffix"]) > 0) {
329 $pi[0]["lname"] .= ", " . $pi[0]["suffix"];
332 return $pi[0]['fname'] . " " . $pi[0]['lname'];
338 function getProviderId($providerName)
340 $query = "select id from users where username = ?";
341 $rez = sqlStatement($query, array($providerName));
342 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
343 $returnval[$iter] = $row;
349 // To prevent sql injection on this function, if a variable is used for $given parameter, then
350 // it needs to be escaped via whitelisting prior to using this function; see lines 2020-2121 of
351 // library/clinical_rules.php script for example of this.
352 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
355 if ($given == 'tobacco') {
356 $where = 'tobacco is not null and';
359 if ($dateStart && $dateEnd) {
360 $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));
361 } elseif ($dateStart && !$dateEnd) {
362 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
363 } elseif (!$dateStart && $dateEnd) {
364 $res = sqlQuery("select $given from history_data where $where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
366 $res = sqlQuery("select $given from history_data where $where pid=? order by date DESC limit 0,1", array($pid));
372 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
373 // To prevent sql injection on this function, if a variable is used for $given parameter, then
374 // it needs to be escaped via whitelisting prior to using this function.
375 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
377 $sql = "select $given from insurance_data as insd " .
378 "left join insurance_companies as ic on ic.id = insd.provider " .
379 "where pid = ? and type = ? order by date DESC limit 1";
380 return sqlQuery($sql, array($pid, $type));
383 // To prevent sql injection on this function, if a variable is used for $given parameter, then
384 // it needs to be escaped via whitelisting prior to using this function.
385 function getInsuranceDataByDate(
389 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
391 // this must take the date in the following manner: YYYY-MM-DD
392 // this function recalls the insurance value that was most recently enterred from the
393 // given date. it will call up most recent records up to and on the date given,
394 // but not records enterred after the given date
395 $sql = "select $given from insurance_data as insd " .
396 "left join insurance_companies as ic on ic.id = provider " .
397 "where pid = ? and (date_format(date,'%Y-%m-%d') <= ? OR date IS NULL) and " .
398 "type=? order by date DESC limit 1";
399 return sqlQuery($sql, array($pid,$date,$type));
402 // To prevent sql injection on this function, if a variable is used for $given parameter, then
403 // it needs to be escaped via whitelisting prior to using this function.
404 function getEmployerData($pid, $given = "*")
406 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
407 return sqlQuery($sql, array($pid));
410 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
412 // When the limit is exceeded, find out what the unlimited count would be.
413 $GLOBALS['PATIENT_INC_COUNT'] = $count;
414 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
415 if ($limit != "all") {
416 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
417 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
422 * Allow the last name to be followed by a comma and some part of a first name(can
423 * also place middle name after the first name with a space separating them)
424 * Allows comma alone followed by some part of a first name(can also place middle name
425 * after the first name with a space separating them).
426 * Allows comma alone preceded by some part of a last name.
427 * If no comma or space, then will search both last name and first name.
428 * If the first letter of either name is capital, searches for name starting
429 * with given substring (the expected behavior). If it is lower case, it
430 * searches for the substring anywhere in the name. This applies to either
431 * last name, first name, and middle name.
432 * Also allows first name followed by middle and/or last name when separated by spaces.
433 * @param string $term
434 * @param string $given
435 * @param string $orderby
436 * @param string $limit
437 * @param string $start
440 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
441 // it needs to be escaped via whitelisting prior to using this function.
442 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")
444 $names = getPatientNameSplit($term);
446 foreach ($names as $key => $val) {
448 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
449 $names[$key] = '%' . $val . '%';
451 $names[$key] = $val . '%';
456 // Debugging section below
457 //if(array_key_exists('first',$names)) {
458 // error_log("first name search term :".$names['first']);
460 //if(array_key_exists('middle',$names)) {
461 // error_log("middle name search term :".$names['middle']);
463 //if(array_key_exists('last',$names)) {
464 // error_log("last name search term :".$names['last']);
466 // Debugging section above
468 $sqlBindArray = array();
469 if (array_key_exists('last', $names) && $names['last'] == '') {
470 // Do not search last name
471 $where = "fname LIKE ? ";
472 array_push($sqlBindArray, $names['first']);
473 if ($names['middle'] != '') {
474 $where .= "AND mname LIKE ? ";
475 array_push($sqlBindArray, $names['middle']);
477 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
478 // Do not search first name or middle name
479 $where = "lname LIKE ? ";
480 array_push($sqlBindArray, $names['last']);
481 } elseif (empty($names['first']) && !empty($names['last'])) {
482 // Search both first name and last name with same term
483 $names['first'] = $names['last'];
484 $where = "lname LIKE ? OR fname LIKE ? ";
485 array_push($sqlBindArray, $names['last'], $names['first']);
486 } elseif ($names['middle'] != '') {
487 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
488 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
490 $where = "lname LIKE ? AND fname LIKE ? ";
491 array_push($sqlBindArray, $names['last'], $names['first']);
494 if (!empty($GLOBALS['pt_restrict_field'])) {
495 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
496 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
497 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
498 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
499 array_push($sqlBindArray, $_SESSION["authUser"]);
503 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
504 if ($limit != "all") {
505 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
508 $rez = sqlStatement($sql, $sqlBindArray);
510 $returnval = array();
511 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
512 $returnval[$iter] = $row;
515 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
519 * Accept a string used by a search function expected to find a patient name,
520 * then split up the string if a comma or space exists. Return an array having
521 * from 1 to 3 elements, named first, middle, and last.
522 * See above getPatientLnames() function for details on how the splitting occurs.
523 * @param string $term
526 function getPatientNameSplit($term)
529 if (strpos($term, ',') !== false) {
530 $names = explode(',', $term);
531 $n['last'] = $names[0];
532 if (strpos(trim($names[1]), ' ') !== false) {
533 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
535 $n['first'] = $names[1];
537 } elseif (strpos($term, ' ') !== false) {
538 $names = explode(' ', $term);
539 if (count($names) == 1) {
540 $n['last'] = $names[0];
541 } elseif (count($names) == 3) {
542 $n['first'] = $names[0];
543 $n['middle'] = $names[1];
544 $n['last'] = $names[2];
546 // This will handle first and last name or first followed by
547 // multiple names only using just the last of the names in the list.
548 $n['first'] = $names[0];
549 $n['last'] = end($names);
553 if (empty($n['last'])) {
558 // Trim whitespace off the names before returning
559 foreach ($n as $key => $val) {
560 $n[$key] = trim($val);
563 return $n; // associative array containing names
566 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
567 // it needs to be escaped via whitelisting prior to using this function.
568 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")
571 $sqlBindArray = array();
572 $where = "pubpid LIKE ? ";
573 array_push($sqlBindArray, $pid . "%");
574 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
575 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
576 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
577 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
578 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
579 array_push($sqlBindArray, $_SESSION["authUser"]);
583 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
584 if ($limit != "all") {
585 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
588 $rez = sqlStatement($sql, $sqlBindArray);
589 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
590 $returnval[$iter] = $row;
593 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
597 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
598 // it needs to be escaped via whitelisting prior to using this function.
599 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")
601 $layoutCols = sqlStatement(
602 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
606 $sqlBindArray = array();
608 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
613 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
614 array_push($sqlBindArray, "%" . $searchTerm . "%");
617 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
618 if ($limit != "all") {
619 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
622 $rez = sqlStatement($sql, $sqlBindArray);
623 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
624 $returnval[$iter] = $row;
627 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
631 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
632 // it needs to be escaped via whitelisting prior to using this function.
633 function getByPatientDemographicsFilter(
636 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
637 $orderby = "lname ASC, fname ASC",
640 $search_service_code = ''
643 $layoutCols = explode('~', $searchFields);
644 $sqlBindArray = array();
647 foreach ($layoutCols as $val) {
657 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " = ? ";
658 array_push($sqlBindArray, $searchTerm);
660 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " like ? ";
661 array_push($sqlBindArray, $searchTerm . "%");
667 // If no search terms, ensure valid syntax.
672 // If a non-empty service code was given, then restrict to patients who
673 // have been provided that service. Since the code is used in a LIKE
674 // clause, % and _ wildcards are supported.
675 if ($search_service_code) {
676 $where = "( $where ) AND " .
677 "( SELECT COUNT(*) FROM billing AS b WHERE " .
678 "b.pid = patient_data.pid AND " .
679 "b.activity = 1 AND " .
680 "b.code_type != 'COPAY' AND " .
683 array_push($sqlBindArray, $search_service_code);
686 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
687 if ($limit != "all") {
688 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
691 $rez = sqlStatement($sql, $sqlBindArray);
692 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
693 $returnval[$iter] = $row;
696 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
700 // return a collection of Patient PIDs
701 // new arg style by JRM March 2008
702 // 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")
703 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
704 // it needs to be escaped via whitelisting prior to using this function.
705 function getPatientPID($args)
708 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
709 $orderby = "lname ASC, fname ASC";
713 // alter default values if defined in the passed in args
714 if (isset($args['pid'])) {
718 if (isset($args['given'])) {
719 $given = $args['given'];
722 if (isset($args['orderby'])) {
723 $orderby = $args['orderby'];
726 if (isset($args['limit'])) {
727 $limit = $args['limit'];
730 if (isset($args['start'])) {
731 $start = $args['start'];
737 } elseif (empty($pid)) {
741 if (strstr($pid, "%")) {
745 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
746 if ($limit != "all") {
747 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
750 $rez = sqlStatement($sql);
751 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
752 $returnval[$iter] = $row;
758 /* return a patient's name in the format LAST, FIRST */
759 function getPatientName($pid)
765 $patientData = getPatientPID(array("pid" => $pid));
766 if (empty($patientData[0]['lname'])) {
770 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
774 /* return a patient's name in the format FIRST LAST */
775 function getPatientNameFirstLast($pid)
781 $patientData = getPatientPID(array("pid" => $pid));
782 if (empty($patientData[0]['lname'])) {
786 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
790 /* find patient data by DOB */
791 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
792 // it needs to be escaped via whitelisting prior to using this function.
793 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
795 $sqlBindArray = array();
796 $where = "DOB like ? ";
797 array_push($sqlBindArray, $DOB . "%");
798 if (!empty($GLOBALS['pt_restrict_field'])) {
799 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
800 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
801 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
802 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
803 array_push($sqlBindArray, $_SESSION["authUser"]);
807 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
809 if ($limit != "all") {
810 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
813 $rez = sqlStatement($sql, $sqlBindArray);
814 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
815 $returnval[$iter] = $row;
818 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
822 /* find patient data by SSN */
823 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
824 // it needs to be escaped via whitelisting prior to using this function.
825 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
827 $sqlBindArray = array();
828 $where = "ss LIKE ?";
829 array_push($sqlBindArray, $ss . "%");
830 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
831 if ($limit != "all") {
832 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
835 $rez = sqlStatement($sql, $sqlBindArray);
836 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
837 $returnval[$iter] = $row;
840 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
844 //(CHEMED) Search by phone number
845 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
846 // it needs to be escaped via whitelisting prior to using this function.
847 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
849 $phone = preg_replace("/[[:punct:]]/", "", $phone);
850 $sqlBindArray = array();
851 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
852 array_push($sqlBindArray, $phone);
853 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
854 if ($limit != "all") {
855 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
858 $rez = sqlStatement($sql, $sqlBindArray);
859 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
860 $returnval[$iter] = $row;
863 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
867 //----------------------input functions
868 function newPatientData(
887 $contact_relationship = "",
894 $migrantseasonal = "",
896 $monthly_income = "",
898 $financial_review = "",
912 $drivers_license = "",
919 $referral_source = '';
921 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
922 // Check for brain damage:
923 if ($db_id != $rez['id']) {
924 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
925 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
929 $fitness = $rez['fitness'];
930 $referral_source = $rez['referral_source'];
933 // Get the default price level.
934 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
935 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
936 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
938 $query = ("replace into patient_data set
939 id='" . add_escape_custom($db_id) . "',
940 title='" . add_escape_custom($title) . "',
941 fname='" . add_escape_custom($fname) . "',
942 lname='" . add_escape_custom($lname) . "',
943 mname='" . add_escape_custom($mname) . "',
944 sex='" . add_escape_custom($sex) . "',
945 DOB='" . add_escape_custom($DOB) . "',
946 street='" . add_escape_custom($street) . "',
947 postal_code='" . add_escape_custom($postal_code) . "',
948 city='" . add_escape_custom($city) . "',
949 state='" . add_escape_custom($state) . "',
950 country_code='" . add_escape_custom($country_code) . "',
951 drivers_license='" . add_escape_custom($drivers_license) . "',
952 ss='" . add_escape_custom($ss) . "',
953 occupation='" . add_escape_custom($occupation) . "',
954 phone_home='" . add_escape_custom($phone_home) . "',
955 phone_biz='" . add_escape_custom($phone_biz) . "',
956 phone_contact='" . add_escape_custom($phone_contact) . "',
957 status='" . add_escape_custom($status) . "',
958 contact_relationship='" . add_escape_custom($contact_relationship) . "',
959 referrer='" . add_escape_custom($referrer) . "',
960 referrerID='" . add_escape_custom($referrerID) . "',
961 email='" . add_escape_custom($email) . "',
962 language='" . add_escape_custom($language) . "',
963 ethnoracial='" . add_escape_custom($ethnoracial) . "',
964 interpretter='" . add_escape_custom($interpretter) . "',
965 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
966 family_size='" . add_escape_custom($family_size) . "',
967 monthly_income='" . add_escape_custom($monthly_income) . "',
968 homeless='" . add_escape_custom($homeless) . "',
969 financial_review='" . add_escape_custom($financial_review) . "',
970 pubpid='" . add_escape_custom($pubpid) . "',
971 pid= '" . add_escape_custom($pid) . "',
972 providerID = '" . add_escape_custom($providerID) . "',
973 genericname1 = '" . add_escape_custom($genericname1) . "',
974 genericval1 = '" . add_escape_custom($genericval1) . "',
975 genericname2 = '" . add_escape_custom($genericname2) . "',
976 genericval2 = '" . add_escape_custom($genericval2) . "',
977 billing_note= '" . add_escape_custom($billing_note) . "',
978 phone_cell = '" . add_escape_custom($phone_cell) . "',
979 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
980 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
981 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
982 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
983 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
984 squad = '" . add_escape_custom($squad) . "',
985 fitness='" . add_escape_custom($fitness) . "',
986 referral_source='" . add_escape_custom($referral_source) . "',
987 regdate='" . add_escape_custom($regdate) . "',
988 pricelevel='" . add_escape_custom($pricelevel) . "',
991 $id = sqlInsert($query);
994 // find the last inserted id for new patient case
998 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
1000 // set uuid if not set yet (if this was an insert and not an update)
1001 if (empty($foo['uuid'])) {
1002 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
1003 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
1009 // Supported input date formats are:
1011 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1013 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1015 function fixDate($date, $default = "0000-00-00")
1017 $fixed_date = $default;
1018 $date = trim($date);
1019 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1020 $dmy = preg_split("'[/.-]'", $date);
1022 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1024 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1025 if ($dmy[2] < 1000) {
1029 if ($dmy[2] < 1910) {
1034 // phone_country_code indicates format of ambiguous input dates.
1035 if ($GLOBALS['phone_country_code'] == 1) {
1036 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1038 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1046 function pdValueOrNull($key, $value)
1049 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1050 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1051 (empty($value) || $value == '0000-00-00')
1055 return "'" . add_escape_custom($value) . "'";
1060 * Create or update patient data from an array.
1062 * This is a wrapper function for the PatientService which is now the single point
1063 * of patient creation and update.
1065 * If successful, returns the pid of the patient
1069 * @param false $create
1072 function updatePatientData($pid, $new, $create = false)
1074 // Create instance of patient service
1075 $patientService = new PatientService();
1080 $result = $patientService->databaseInsert($new);
1081 updateDupScore($result['pid']);
1084 $result = $patientService->databaseUpdate($new);
1087 // From the returned patient data array
1088 // retrieve the data and return the pid
1089 $pid = $result['pid'];
1094 function newEmployerData(
1104 return sqlInsert("insert into employer_data set
1105 name='" . add_escape_custom($name) . "',
1106 street='" . add_escape_custom($street) . "',
1107 postal_code='" . add_escape_custom($postal_code) . "',
1108 city='" . add_escape_custom($city) . "',
1109 state='" . add_escape_custom($state) . "',
1110 country='" . add_escape_custom($country) . "',
1111 pid='" . add_escape_custom($pid) . "',
1116 // Create or update employer data from an array.
1118 function updateEmployerData($pid, $new, $create = false)
1120 $colnames = array('name','street','city','state','postal_code','country');
1123 $set = "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1124 foreach ($colnames as $key) {
1125 $value = isset($new[$key]) ? $new[$key] : '';
1126 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1129 return sqlInsert("INSERT INTO employer_data SET $set");
1132 $old = getEmployerData($pid);
1134 foreach ($colnames as $key) {
1135 $value = empty($old[$key]) ? '' : $old[$key];
1136 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1137 $value = $new[$key];
1141 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1145 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1146 return sqlInsert("INSERT INTO employer_data SET $set");
1153 // This updates or adds the given insurance data info, while retaining any
1154 // previously added insurance_data rows that should be preserved.
1155 // This does not directly support the maintenance of non-current insurance.
1157 function newInsuranceData(
1161 $policy_number = "",
1164 $subscriber_lname = "",
1165 $subscriber_mname = "",
1166 $subscriber_fname = "",
1167 $subscriber_relationship = "",
1168 $subscriber_ss = "",
1169 $subscriber_DOB = null,
1170 $subscriber_street = "",
1171 $subscriber_postal_code = "",
1172 $subscriber_city = "",
1173 $subscriber_state = "",
1174 $subscriber_country = "",
1175 $subscriber_phone = "",
1176 $subscriber_employer = "",
1177 $subscriber_employer_street = "",
1178 $subscriber_employer_city = "",
1179 $subscriber_employer_postal_code = "",
1180 $subscriber_employer_state = "",
1181 $subscriber_employer_country = "",
1183 $subscriber_sex = "",
1184 $effective_date = null,
1185 $accept_assignment = "TRUE",
1189 if (strlen($type) <= 0) {
1193 if (is_null($accept_assignment)) {
1194 $accept_assignment = "TRUE";
1196 if (is_null($policy_type)) {
1200 // If empty dates were passed, then null.
1201 if (empty($effective_date)) {
1202 $effective_date = null;
1204 if (empty($subscriber_DOB)) {
1205 $subscriber_DOB = null;
1208 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1209 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1210 $idrow = sqlFetchArray($idres);
1212 // Replace the most recent entry in any of the following cases:
1213 // * Its effective date is >= this effective date.
1214 // * It is the first entry and it has no (insurance) provider.
1215 // * There is no encounter that is earlier than the new effective date but
1216 // on or after the old effective date.
1217 // Otherwise insert a new entry.
1221 // convert date from null to "0000-00-00" for below strcmp and query
1222 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1223 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1224 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1227 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1230 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1231 "WHERE pid = ? AND date < ? AND " .
1232 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1233 if ($ferow['count'] == 0) {
1241 // TBD: This is a bit dangerous in that a typo in entering the effective
1242 // date can wipe out previous insurance history. So we want some data
1243 // entry validation somewhere.
1244 if ($effective_date === null) {
1245 sqlStatement("DELETE FROM insurance_data WHERE " .
1246 "pid = ? AND type = ? AND " .
1247 "id != ?", array($pid, $type, $idrow['id']));
1249 sqlStatement("DELETE FROM insurance_data WHERE " .
1250 "pid = ? AND type = ? AND date >= ? AND " .
1251 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1255 $data['type'] = $type;
1256 $data['provider'] = $provider;
1257 $data['policy_number'] = $policy_number;
1258 $data['group_number'] = $group_number;
1259 $data['plan_name'] = $plan_name;
1260 $data['subscriber_lname'] = $subscriber_lname;
1261 $data['subscriber_mname'] = $subscriber_mname;
1262 $data['subscriber_fname'] = $subscriber_fname;
1263 $data['subscriber_relationship'] = $subscriber_relationship;
1264 $data['subscriber_ss'] = $subscriber_ss;
1265 $data['subscriber_DOB'] = $subscriber_DOB;
1266 $data['subscriber_street'] = $subscriber_street;
1267 $data['subscriber_postal_code'] = $subscriber_postal_code;
1268 $data['subscriber_city'] = $subscriber_city;
1269 $data['subscriber_state'] = $subscriber_state;
1270 $data['subscriber_country'] = $subscriber_country;
1271 $data['subscriber_phone'] = $subscriber_phone;
1272 $data['subscriber_employer'] = $subscriber_employer;
1273 $data['subscriber_employer_city'] = $subscriber_employer_city;
1274 $data['subscriber_employer_street'] = $subscriber_employer_street;
1275 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1276 $data['subscriber_employer_state'] = $subscriber_employer_state;
1277 $data['subscriber_employer_country'] = $subscriber_employer_country;
1278 $data['copay'] = $copay;
1279 $data['subscriber_sex'] = $subscriber_sex;
1280 $data['pid'] = $pid;
1281 $data['date'] = $effective_date;
1282 $data['accept_assignment'] = $accept_assignment;
1283 $data['policy_type'] = $policy_type;
1284 updateInsuranceData($idrow['id'], $data);
1285 return $idrow['id'];
1288 "INSERT INTO `insurance_data` SET `type` = ?,
1290 `policy_number` = ?,
1293 `subscriber_lname` = ?,
1294 `subscriber_mname` = ?,
1295 `subscriber_fname` = ?,
1296 `subscriber_relationship` = ?,
1297 `subscriber_ss` = ?,
1298 `subscriber_DOB` = ?,
1299 `subscriber_street` = ?,
1300 `subscriber_postal_code` = ?,
1301 `subscriber_city` = ?,
1302 `subscriber_state` = ?,
1303 `subscriber_country` = ?,
1304 `subscriber_phone` = ?,
1305 `subscriber_employer` = ?,
1306 `subscriber_employer_city` = ?,
1307 `subscriber_employer_street` = ?,
1308 `subscriber_employer_postal_code` = ?,
1309 `subscriber_employer_state` = ?,
1310 `subscriber_employer_country` = ?,
1312 `subscriber_sex` = ?,
1315 `accept_assignment` = ?,
1326 $subscriber_relationship,
1330 $subscriber_postal_code,
1333 $subscriber_country,
1335 $subscriber_employer,
1336 $subscriber_employer_city,
1337 $subscriber_employer_street,
1338 $subscriber_employer_postal_code,
1339 $subscriber_employer_state,
1340 $subscriber_employer_country,
1352 // This is used internally only.
1353 function updateInsuranceData($id, $new)
1355 $fields = sqlListFields("insurance_data");
1358 foreach ($new as $key => $value) {
1359 if (in_array($key, $fields)) {
1360 $use[$key] = $value;
1365 $sql = "UPDATE insurance_data SET ";
1366 foreach ($use as $key => $value) {
1367 $sql .= "`" . $key . "` = ?, ";
1368 array_push($sqlBindArray, $value);
1371 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1372 array_push($sqlBindArray, $id);
1374 sqlStatement($sql, $sqlBindArray);
1377 function newHistoryData($pid, $new = false)
1379 $socialHistoryService = new SocialHistoryService();
1381 $insertionRecord = $new;
1382 if (!is_array(($insertionRecord))) {
1383 $insertionRecord = [
1387 $socialHistoryService->create($insertionRecord);
1390 function updateHistoryData($pid, $new)
1392 $socialHistoryService = new SocialHistoryService();
1393 return $socialHistoryService->updateHistoryDataForPatientPid($pid, $new);
1397 // in months if < 2 years old
1398 // in years if > 2 years old
1399 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1400 // (optional) nowYMD is a date in YYYYMMDD format
1401 function getPatientAge($dobYMD, $nowYMD = null)
1403 if (empty($dobYMD)) {
1406 // strip any dashes from the DOB
1407 $dobYMD = preg_replace("/-/", "", $dobYMD);
1408 $dobDay = substr($dobYMD, 6, 2);
1409 $dobMonth = substr($dobYMD, 4, 2);
1410 $dobYear = (int) substr($dobYMD, 0, 4);
1412 // set the 'now' date values
1413 if ($nowYMD == null) {
1414 $nowDay = date("d");
1415 $nowMonth = date("m");
1416 $nowYear = date("Y");
1418 $nowDay = substr($nowYMD, 6, 2);
1419 $nowMonth = substr($nowYMD, 4, 2);
1420 $nowYear = substr($nowYMD, 0, 4);
1423 $dayDiff = $nowDay - $dobDay;
1424 $monthDiff = $nowMonth - $dobMonth;
1425 $yearDiff = $nowYear - $dobYear;
1427 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear * 12) + $dobMonth);
1429 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1434 if ($ageInMonths > 24) {
1436 if (($monthDiff == 0) && ($dayDiff < 0)) {
1438 } elseif ($monthDiff < 0) {
1442 $age = "$ageInMonths " . xl('month');
1449 * Wrapper to make sure the clinical rules dates formats corresponds to the
1450 * format expected by getPatientAgeYMD
1452 * @param string $dob date of birth
1453 * @param string $target date to calculate age on
1454 * @return array containing
1455 * age - decimal age in years
1456 * age_in_months - decimal age in months
1457 * ageinYMD - formatted string #y #m #d */
1458 function parseAgeInfo($dob, $target)
1460 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1461 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1463 // Prepare target (Y-M-D H:M:S)
1464 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1466 return getPatientAgeYMD($dateDOB, $dateTarget);
1473 * @return array containing
1474 * age - decimal age in years
1475 * age_in_months - decimal age in months
1476 * ageinYMD - formatted string #y #m #d
1478 function getPatientAgeYMD($dob, $date = null)
1481 if ($date == null) {
1482 $daynow = date("d");
1483 $monthnow = date("m");
1484 $yearnow = date("Y");
1485 $datenow = $yearnow . $monthnow . $daynow;
1487 $datenow = preg_replace("/-/", "", $date);
1488 $yearnow = substr($datenow, 0, 4);
1489 $monthnow = substr($datenow, 4, 2);
1490 $daynow = substr($datenow, 6, 2);
1491 $datenow = $yearnow . $monthnow . $daynow;
1494 $dob = preg_replace("/-/", "", $dob);
1495 $dobyear = substr($dob, 0, 4);
1496 $dobmonth = substr($dob, 4, 2);
1497 $dobday = substr($dob, 6, 2);
1498 $dob = $dobyear . $dobmonth . $dobday;
1500 //to compensate for 30, 31, 28, 29 days/month
1501 $mo = $monthnow; //to avoid confusion with later calculation
1503 if ($mo == 05 or $mo == 07 or $mo == 10 or $mo == 12) { // determined by monthnow-1
1504 $nd = 30; // nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1505 } elseif ($mo == 03) { // look at April, June, September, November for calculation. These months only have 30 days.
1506 // for march, look to the month of February for calculation, check for leap year
1507 $check_leap_Y = $yearnow / 4; // To check if this is a leap year.
1508 if (is_int($check_leap_Y)) { // If it true then this is the leap year
1510 } else { // otherwise, it is not a leap year.
1513 } else { // other months have 31 days
1517 $bdthisyear = $yearnow . $dobmonth . $dobday; //Date current year's birthday falls on
1518 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1519 $age_year = $yearnow - $dobyear - 1;
1520 if ($daynow < $dobday) {
1521 $months_since_birthday = 12 - $dobmonth + $monthnow - 1;
1522 $days_since_dobday = $nd - $dobday + $daynow; //did not take into account for month with 31 days
1524 $months_since_birthday = 12 - $dobmonth + $monthnow;
1525 $days_since_dobday = $daynow - $dobday;
1527 } else // if patient has had birthday this calandar year
1529 $age_year = $yearnow - $dobyear;
1530 if ($daynow < $dobday) {
1531 $months_since_birthday = $monthnow - $dobmonth - 1;
1532 $days_since_dobday = $nd - $dobday + $daynow;
1534 $months_since_birthday = $monthnow - $dobmonth;
1535 $days_since_dobday = $daynow - $dobday;
1539 $day_as_month_decimal = $days_since_dobday / 30;
1540 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1541 $month_as_year_decimal = $months_since_birthday_float / 12;
1542 $age_float = $age_year + $month_as_year_decimal;
1544 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1545 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1546 $age = round($age_float, 2);
1548 // round the years to 2 floating points
1549 $ageinYMD = $age_year . "y " . $months_since_birthday . "m " . $days_since_dobday . "d";
1550 return compact('age', 'age_in_months', 'ageinYMD');
1553 // Returns Age in days
1554 // in months if < 2 years old
1555 // in years if > 2 years old
1556 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1557 // (optional) nowYMD is a date in YYYYMMDD format
1558 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1562 // strip any dashes from the DOB
1563 $dobYMD = preg_replace("/-/", "", $dobYMD);
1564 $dobDay = substr($dobYMD, 6, 2);
1565 $dobMonth = substr($dobYMD, 4, 2);
1566 $dobYear = substr($dobYMD, 0, 4);
1568 // set the 'now' date values
1569 if ($nowYMD == null) {
1570 $nowDay = date("d");
1571 $nowMonth = date("m");
1572 $nowYear = date("Y");
1574 $nowDay = substr($nowYMD, 6, 2);
1575 $nowMonth = substr($nowYMD, 4, 2);
1576 $nowYear = substr($nowYMD, 0, 4);
1580 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1581 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1582 $timediff = $nowtime - $dobtime;
1583 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1588 * Returns a string to be used to display a patient's age
1590 * @param type $dobYMD
1591 * @param type $asOfYMD
1592 * @return string suitable for displaying patient's age based on preferences
1594 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1596 if ($GLOBALS['age_display_format'] == '1') {
1597 $ageYMD = getPatientAgeYMD($dobYMD, $asOfYMD);
1598 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age'] <= $GLOBALS['age_display_limit']) {
1599 return $ageYMD['ageinYMD'];
1601 return getPatientAge($dobYMD, $asOfYMD);
1604 return getPatientAge($dobYMD, $asOfYMD);
1607 function dateToDB($date)
1609 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1614 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1615 * for the given patient on the given date.
1617 * @param int The PID of the patient.
1618 * @param string Date in yyyy-mm-dd format.
1619 * @return array Array of 0-3 insurance_data rows.
1621 function getEffectiveInsurances($patient_id, $encdate)
1624 foreach (array('primary','secondary','tertiary') as $instype) {
1626 "SELECT * FROM insurance_data " .
1627 "WHERE pid = ? AND type = ? " .
1628 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1629 array($patient_id, $instype, $encdate)
1631 if (empty($tmp['provider'])) {
1642 * Get all requisition insurance companies
1647 function getAllinsurances($pid)
1650 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1651 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1652 b.name, c.line1, c.line2, c.city, c.state, c.zip
1653 FROM `insurance_data` AS a
1654 RIGHT JOIN insurance_companies AS b
1655 ON a.provider = b.id
1656 RIGHT JOIN addresses AS c
1657 ON a.provider = c.foreign_id
1659 $inco = sqlStatement($sql, array($pid));
1661 while ($icl = sqlFetchArray($inco)) {
1668 * Get the patient's balance due. Normally this excludes amounts that are out
1669 * to insurance. If you want to include what insurance owes, set the second
1670 * parameter to true.
1672 * @param int The PID of the patient.
1673 * @param boolean Indicates if amounts owed by insurance are to be included.
1674 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1675 * @return number The balance.
1677 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1680 $bindarray = array($pid);
1681 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1682 "last_level_closed, stmt_count " .
1683 "FROM form_encounter WHERE pid = ?";
1685 $sqlstatement .= " AND encounter = ?";
1686 array_push($bindarray, $eid);
1688 $feres = sqlStatement($sqlstatement, $bindarray);
1689 while ($ferow = sqlFetchArray($feres)) {
1690 $encounter = $ferow['encounter'];
1691 $dos = substr($ferow['date'], 0, 10);
1692 $insarr = getEffectiveInsurances($pid, $dos);
1693 $inscount = count($insarr);
1694 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1695 // It's out to insurance so only the co-pay might be due.
1697 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1698 "pid = ? AND encounter = ? AND " .
1699 "code_type = 'copay' AND activity = 1",
1700 array($pid, $encounter)
1703 "SELECT SUM(pay_amount) AS payments " .
1704 "FROM ar_activity WHERE " .
1705 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1706 array($pid, $encounter)
1708 // going to comment this out for now since computing future copays doesn't
1709 // equate to cash in hand, which shows in the Billing widget in dashboard 4-23-21
1710 // $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1712 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1713 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1714 $ptbal = $copay + $amt - $pay;
1715 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1719 // Including insurance or not out to insurance, everything is due.
1720 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1721 "pid = ? AND encounter = ? AND " .
1722 "activity = 1", array($pid, $encounter));
1723 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1724 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1725 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1726 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1727 "pid = ? AND encounter = ?", array($pid, $encounter));
1728 $balance += $brow['amount'] + $srow['amount']
1729 - $drow['payments'] - $drow['adjustments'];
1733 return sprintf('%01.2f', $balance);
1736 function get_patient_balance_excluding($pid, $excluded = -1)
1738 // We join form_encounter here to make sure we only count amounts for
1739 // encounters that exist. We've had some trouble before with encounters
1740 // that were deleted but leaving line items in the database.
1742 "SELECT SUM(b.fee) AS amount " .
1743 "FROM billing AS b, form_encounter AS fe WHERE " .
1744 "b.pid = ? AND b.encounter != 0 AND b.encounter != ? AND b.activity = 1 AND " .
1745 "fe.pid = b.pid AND fe.encounter = b.encounter",
1746 array($pid, $excluded)
1749 "SELECT SUM(s.fee) AS amount " .
1750 "FROM drug_sales AS s, form_encounter AS fe WHERE " .
1751 "s.pid = ? AND s.encounter != 0 AND s.encounter != ? AND " .
1752 "fe.pid = s.pid AND fe.encounter = s.encounter",
1753 array($pid, $excluded)
1756 "SELECT SUM(a.pay_amount) AS payments, " .
1757 "SUM(a.adj_amount) AS adjustments " .
1758 "FROM ar_activity AS a, form_encounter AS fe WHERE " .
1759 "a.deleted IS NULL AND a.pid = ? AND a.encounter != 0 AND a.encounter != ? AND " .
1760 "fe.pid = a.pid AND fe.encounter = a.encounter",
1761 array($pid, $excluded)
1765 $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments']
1769 // Function to check if patient is deceased.
1771 // $pid - patient id
1772 // $date - date checking if deceased (will default to current date if blank)
1774 // If deceased, then will return the number of
1775 // days that patient has been deceased and the deceased date.
1776 // If not deceased, then will return false.
1777 function is_patient_deceased($pid, $date = '')
1780 // Set date to current if not set
1781 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1783 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1784 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1785 "FROM `patient_data` " .
1786 "WHERE `pid` = ? AND " .
1787 dateEmptySql('deceased_date', true, true) .
1788 "AND `deceased_date` <= ?", array($date,$pid,$date));
1790 if (empty($results)) {
1791 // Patient is alive, so return false
1794 // Patient is dead, so return the number of days patient has been deceased.
1795 // Don't let it be zero days or else will confuse calls to this function.
1796 if ($results['days_deceased'] === 0) {
1797 $results['days_deceased'] = 1;
1804 // This computes, sets and returns the dup score for the given patient.
1806 function updateDupScore($pid)
1809 "SELECT MAX(" . getDupScoreSQL() . ") AS dupscore " .
1810 "FROM patient_data AS p1, patient_data AS p2 WHERE " .
1811 "p1.pid = ? AND p2.pid < p1.pid",
1814 $dupscore = empty($row['dupscore']) ? 0 : $row['dupscore'];
1816 "UPDATE patient_data SET dupscore = ? WHERE pid = ?",
1817 array($dupscore, $pid)