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));
78 return $row['name'] ?? '';
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";
211 if (!empty($r['street'])) {
212 $s .= "<br />" . text($r['street']) . "\n";
215 if (!empty($r['city']) || !empty($r['state']) || !empty($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 (!empty($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 // removing active from query since is checked above with $providers_only argument
302 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
303 "from users where username != '' and id $command '" .
304 add_escape_custom($providerID) . "' " . $param1 . $param2;
305 // sort by last name -- JRM June 2008
306 $query .= " ORDER BY lname, fname ";
307 $rez = sqlStatement($query);
308 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
309 $returnval[$iter] = $row;
312 //if only one result returned take the key/value pairs in array [0] and merge them down into
313 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
316 $akeys = array_keys($returnval[0]);
317 foreach ($akeys as $key) {
318 $returnval[0][$key] = $returnval[0][$key];
322 return ($returnval ?? null);
325 function getProviderName($providerID, $provider_only = 'any')
327 $pi = getProviderInfo($providerID, $provider_only);
328 if (!empty($pi[0]["lname"]) && (strlen($pi[0]["lname"]) > 0)) {
329 if (!empty($pi[0]["suffix"]) && (strlen($pi[0]["suffix"]) > 0)) {
330 $pi[0]["lname"] .= ", " . $pi[0]["suffix"];
333 return $pi[0]['fname'] . " " . $pi[0]['lname'];
339 function getProviderId($providerName)
341 $query = "select id from users where username = ?";
342 $rez = sqlStatement($query, array($providerName));
343 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
344 $returnval[$iter] = $row;
350 // To prevent sql injection on this function, if a variable is used for $given parameter, then
351 // it needs to be escaped via whitelisting prior to using this function; see lines 2020-2121 of
352 // library/clinical_rules.php script for example of this.
353 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
356 if ($given == 'tobacco') {
357 $where = 'tobacco is not null and';
360 if ($dateStart && $dateEnd) {
361 $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));
362 } elseif ($dateStart && !$dateEnd) {
363 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
364 } elseif (!$dateStart && $dateEnd) {
365 $res = sqlQuery("select $given from history_data where $where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
367 $res = sqlQuery("select $given from history_data where $where pid=? order by date DESC limit 0,1", array($pid));
373 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
374 // To prevent sql injection on this function, if a variable is used for $given parameter, then
375 // it needs to be escaped via whitelisting prior to using this function.
376 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
378 $sql = "select $given from insurance_data as insd " .
379 "left join insurance_companies as ic on ic.id = insd.provider " .
380 "where pid = ? and type = ? order by date DESC limit 1";
381 return sqlQuery($sql, array($pid, $type));
384 // To prevent sql injection on this function, if a variable is used for $given parameter, then
385 // it needs to be escaped via whitelisting prior to using this function.
386 function getInsuranceDataByDate(
390 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
392 // this must take the date in the following manner: YYYY-MM-DD
393 // this function recalls the insurance value that was most recently enterred from the
394 // given date. it will call up most recent records up to and on the date given,
395 // but not records enterred after the given date
396 $sql = "select $given from insurance_data as insd " .
397 "left join insurance_companies as ic on ic.id = provider " .
398 "where pid = ? and (date_format(date,'%Y-%m-%d') <= ? OR date IS NULL) and " .
399 "type=? order by date DESC limit 1";
400 return sqlQuery($sql, array($pid,$date,$type));
403 // To prevent sql injection on this function, if a variable is used for $given parameter, then
404 // it needs to be escaped via whitelisting prior to using this function.
405 function getEmployerData($pid, $given = "*")
407 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
408 return sqlQuery($sql, array($pid));
411 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
413 // When the limit is exceeded, find out what the unlimited count would be.
414 $GLOBALS['PATIENT_INC_COUNT'] = $count;
415 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
416 if ($limit != "all") {
417 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
418 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
423 * Allow the last name to be followed by a comma and some part of a first name(can
424 * also place middle name after the first name with a space separating them)
425 * Allows comma alone followed by some part of a first name(can also place middle name
426 * after the first name with a space separating them).
427 * Allows comma alone preceded by some part of a last name.
428 * If no comma or space, then will search both last name and first name.
429 * If the first letter of either name is capital, searches for name starting
430 * with given substring (the expected behavior). If it is lower case, it
431 * searches for the substring anywhere in the name. This applies to either
432 * last name, first name, and middle name.
433 * Also allows first name followed by middle and/or last name when separated by spaces.
434 * @param string $term
435 * @param string $given
436 * @param string $orderby
437 * @param string $limit
438 * @param string $start
441 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
442 // it needs to be escaped via whitelisting prior to using this function.
443 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")
445 $names = getPatientNameSplit($term);
447 foreach ($names as $key => $val) {
449 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
450 $names[$key] = '%' . $val . '%';
452 $names[$key] = $val . '%';
457 // Debugging section below
458 //if(array_key_exists('first',$names)) {
459 // error_log("first name search term :".$names['first']);
461 //if(array_key_exists('middle',$names)) {
462 // error_log("middle name search term :".$names['middle']);
464 //if(array_key_exists('last',$names)) {
465 // error_log("last name search term :".$names['last']);
467 // Debugging section above
469 $sqlBindArray = array();
470 if (array_key_exists('last', $names) && $names['last'] == '') {
471 // Do not search last name
472 $where = "fname LIKE ? ";
473 array_push($sqlBindArray, $names['first']);
474 if ($names['middle'] != '') {
475 $where .= "AND mname LIKE ? ";
476 array_push($sqlBindArray, $names['middle']);
478 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
479 // Do not search first name or middle name
480 $where = "lname LIKE ? ";
481 array_push($sqlBindArray, $names['last']);
482 } elseif (empty($names['first']) && !empty($names['last'])) {
483 // Search both first name and last name with same term
484 $names['first'] = $names['last'];
485 $where = "lname LIKE ? OR fname LIKE ? ";
486 array_push($sqlBindArray, $names['last'], $names['first']);
487 } elseif ($names['middle'] != '') {
488 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
489 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
491 $where = "lname LIKE ? AND fname LIKE ? ";
492 array_push($sqlBindArray, $names['last'], $names['first']);
495 if (!empty($GLOBALS['pt_restrict_field'])) {
496 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
497 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
498 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
499 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
500 array_push($sqlBindArray, $_SESSION["authUser"]);
504 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
505 if ($limit != "all") {
506 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
509 $rez = sqlStatement($sql, $sqlBindArray);
511 $returnval = array();
512 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
513 $returnval[$iter] = $row;
516 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
520 * Accept a string used by a search function expected to find a patient name,
521 * then split up the string if a comma or space exists. Return an array having
522 * from 1 to 3 elements, named first, middle, and last.
523 * See above getPatientLnames() function for details on how the splitting occurs.
524 * @param string $term
527 function getPatientNameSplit($term)
530 if (strpos($term, ',') !== false) {
531 $names = explode(',', $term);
532 $n['last'] = $names[0];
533 if (strpos(trim($names[1]), ' ') !== false) {
534 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
536 $n['first'] = $names[1];
538 } elseif (strpos($term, ' ') !== false) {
539 $names = explode(' ', $term);
540 if (count($names) == 1) {
541 $n['last'] = $names[0];
542 } elseif (count($names) == 3) {
543 $n['first'] = $names[0];
544 $n['middle'] = $names[1];
545 $n['last'] = $names[2];
547 // This will handle first and last name or first followed by
548 // multiple names only using just the last of the names in the list.
549 $n['first'] = $names[0];
550 $n['last'] = end($names);
554 if (empty($n['last'])) {
559 // Trim whitespace off the names before returning
560 foreach ($n as $key => $val) {
561 $n[$key] = trim($val);
564 return $n; // associative array containing names
567 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
568 // it needs to be escaped via whitelisting prior to using this function.
569 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")
572 $sqlBindArray = array();
573 $where = "pubpid LIKE ? ";
574 array_push($sqlBindArray, $pid . "%");
575 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
576 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
577 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
578 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
579 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
580 array_push($sqlBindArray, $_SESSION["authUser"]);
584 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
585 if ($limit != "all") {
586 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
589 $rez = sqlStatement($sql, $sqlBindArray);
590 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
591 $returnval[$iter] = $row;
594 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
598 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
599 // it needs to be escaped via whitelisting prior to using this function.
600 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")
602 $layoutCols = sqlStatement(
603 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
607 $sqlBindArray = array();
609 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
614 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
615 array_push($sqlBindArray, "%" . $searchTerm . "%");
618 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
619 if ($limit != "all") {
620 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
623 $rez = sqlStatement($sql, $sqlBindArray);
624 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
625 $returnval[$iter] = $row;
628 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
632 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
633 // it needs to be escaped via whitelisting prior to using this function.
634 function getByPatientDemographicsFilter(
637 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
638 $orderby = "lname ASC, fname ASC",
641 $search_service_code = ''
644 $layoutCols = explode('~', $searchFields);
645 $sqlBindArray = array();
648 foreach ($layoutCols as $val) {
658 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " = ? ";
659 array_push($sqlBindArray, $searchTerm);
661 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " like ? ";
662 array_push($sqlBindArray, $searchTerm . "%");
668 // If no search terms, ensure valid syntax.
673 // If a non-empty service code was given, then restrict to patients who
674 // have been provided that service. Since the code is used in a LIKE
675 // clause, % and _ wildcards are supported.
676 if ($search_service_code) {
677 $where = "( $where ) AND " .
678 "( SELECT COUNT(*) FROM billing AS b WHERE " .
679 "b.pid = patient_data.pid AND " .
680 "b.activity = 1 AND " .
681 "b.code_type != 'COPAY' AND " .
684 array_push($sqlBindArray, $search_service_code);
687 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
688 if ($limit != "all") {
689 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
692 $rez = sqlStatement($sql, $sqlBindArray);
693 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
694 $returnval[$iter] = $row;
697 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
701 // return a collection of Patient PIDs
702 // new arg style by JRM March 2008
703 // 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")
704 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
705 // it needs to be escaped via whitelisting prior to using this function.
706 function getPatientPID($args)
709 $given = "pid, id, lname, fname, mname, suffix, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
710 $orderby = "lname ASC, fname ASC";
714 // alter default values if defined in the passed in args
715 if (isset($args['pid'])) {
719 if (isset($args['given'])) {
720 $given = $args['given'];
723 if (isset($args['orderby'])) {
724 $orderby = $args['orderby'];
727 if (isset($args['limit'])) {
728 $limit = $args['limit'];
731 if (isset($args['start'])) {
732 $start = $args['start'];
738 } elseif (empty($pid)) {
742 if (strstr($pid, "%")) {
746 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
747 if ($limit != "all") {
748 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
751 $rez = sqlStatement($sql);
752 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
753 $returnval[$iter] = $row;
759 /* return a patient's name in the format LAST, FIRST */
760 function getPatientName($pid)
766 $patientData = getPatientPID(array("pid" => $pid));
767 if (empty($patientData[0]['lname'])) {
771 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
776 * Get a patient's first name, middle name, last name and suffix if applicable.
778 * Returns a properly formatted, complete name when applicable. Example name
779 * would be "John B Doe Jr". No additional punctuation is added. Spaces are
780 * correctly omitted if the middle name of suffix does not apply.
782 * @var $pid int The Patient ID
783 * @returns string The Full Name
785 function getPatientFullNameAsString(int $pid): string
787 $ptData = getPatientPID(["pid" => $pid]);
790 if (empty($pt['lname'])) {
794 $name = $pt['fname'];
797 $name .= " {$pt['mname']}";
800 $name .= " {$pt['lname']}";
803 $name .= " {$pt['suffix']}";
809 /* return a patient's name in the format FIRST LAST */
810 function getPatientNameFirstLast($pid)
816 $patientData = getPatientPID(array("pid" => $pid));
817 if (empty($patientData[0]['lname'])) {
821 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
825 /* find patient data by DOB */
826 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
827 // it needs to be escaped via whitelisting prior to using this function.
828 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
830 $sqlBindArray = array();
831 $where = "DOB like ? ";
832 array_push($sqlBindArray, $DOB . "%");
833 if (!empty($GLOBALS['pt_restrict_field'])) {
834 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
835 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
836 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
837 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
838 array_push($sqlBindArray, $_SESSION["authUser"]);
842 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
844 if ($limit != "all") {
845 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
848 $rez = sqlStatement($sql, $sqlBindArray);
849 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
850 $returnval[$iter] = $row;
853 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
857 /* find patient data by SSN */
858 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
859 // it needs to be escaped via whitelisting prior to using this function.
860 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
862 $sqlBindArray = array();
863 $where = "ss LIKE ?";
864 array_push($sqlBindArray, $ss . "%");
865 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
866 if ($limit != "all") {
867 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
870 $rez = sqlStatement($sql, $sqlBindArray);
871 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
872 $returnval[$iter] = $row;
875 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
879 //(CHEMED) Search by phone number
880 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
881 // it needs to be escaped via whitelisting prior to using this function.
882 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
884 $phone = preg_replace("/[[:punct:]]/", "", $phone);
885 $sqlBindArray = array();
886 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
887 array_push($sqlBindArray, $phone);
888 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
889 if ($limit != "all") {
890 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
893 $rez = sqlStatement($sql, $sqlBindArray);
894 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
895 $returnval[$iter] = $row;
898 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
902 //----------------------input functions
903 function newPatientData(
922 $contact_relationship = "",
929 $migrantseasonal = "",
931 $monthly_income = "",
933 $financial_review = "",
947 $drivers_license = "",
954 $referral_source = '';
956 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
957 // Check for brain damage:
958 if ($db_id != $rez['id']) {
959 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
960 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
964 $fitness = $rez['fitness'];
965 $referral_source = $rez['referral_source'];
968 // Get the default price level.
969 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
970 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
971 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
973 $query = ("replace into patient_data set
974 id='" . add_escape_custom($db_id) . "',
975 title='" . add_escape_custom($title) . "',
976 fname='" . add_escape_custom($fname) . "',
977 lname='" . add_escape_custom($lname) . "',
978 mname='" . add_escape_custom($mname) . "',
979 sex='" . add_escape_custom($sex) . "',
980 DOB='" . add_escape_custom($DOB) . "',
981 street='" . add_escape_custom($street) . "',
982 postal_code='" . add_escape_custom($postal_code) . "',
983 city='" . add_escape_custom($city) . "',
984 state='" . add_escape_custom($state) . "',
985 country_code='" . add_escape_custom($country_code) . "',
986 drivers_license='" . add_escape_custom($drivers_license) . "',
987 ss='" . add_escape_custom($ss) . "',
988 occupation='" . add_escape_custom($occupation) . "',
989 phone_home='" . add_escape_custom($phone_home) . "',
990 phone_biz='" . add_escape_custom($phone_biz) . "',
991 phone_contact='" . add_escape_custom($phone_contact) . "',
992 status='" . add_escape_custom($status) . "',
993 contact_relationship='" . add_escape_custom($contact_relationship) . "',
994 referrer='" . add_escape_custom($referrer) . "',
995 referrerID='" . add_escape_custom($referrerID) . "',
996 email='" . add_escape_custom($email) . "',
997 language='" . add_escape_custom($language) . "',
998 ethnoracial='" . add_escape_custom($ethnoracial) . "',
999 interpretter='" . add_escape_custom($interpretter) . "',
1000 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1001 family_size='" . add_escape_custom($family_size) . "',
1002 monthly_income='" . add_escape_custom($monthly_income) . "',
1003 homeless='" . add_escape_custom($homeless) . "',
1004 financial_review='" . add_escape_custom($financial_review) . "',
1005 pubpid='" . add_escape_custom($pubpid) . "',
1006 pid= '" . add_escape_custom($pid) . "',
1007 providerID = '" . add_escape_custom($providerID) . "',
1008 genericname1 = '" . add_escape_custom($genericname1) . "',
1009 genericval1 = '" . add_escape_custom($genericval1) . "',
1010 genericname2 = '" . add_escape_custom($genericname2) . "',
1011 genericval2 = '" . add_escape_custom($genericval2) . "',
1012 billing_note= '" . add_escape_custom($billing_note) . "',
1013 phone_cell = '" . add_escape_custom($phone_cell) . "',
1014 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1015 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1016 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1017 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1018 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1019 squad = '" . add_escape_custom($squad) . "',
1020 fitness='" . add_escape_custom($fitness) . "',
1021 referral_source='" . add_escape_custom($referral_source) . "',
1022 regdate='" . add_escape_custom($regdate) . "',
1023 pricelevel='" . add_escape_custom($pricelevel) . "',
1026 $id = sqlInsert($query);
1029 // find the last inserted id for new patient case
1033 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
1035 // set uuid if not set yet (if this was an insert and not an update)
1036 if (empty($foo['uuid'])) {
1037 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
1038 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
1044 // Supported input date formats are:
1046 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1048 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1050 function fixDate($date, $default = "0000-00-00")
1052 $fixed_date = $default;
1053 $date = trim($date);
1054 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1055 $dmy = preg_split("'[/.-]'", $date);
1057 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1059 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1060 if ($dmy[2] < 1000) {
1064 if ($dmy[2] < 1910) {
1069 // phone_country_code indicates format of ambiguous input dates.
1070 if ($GLOBALS['phone_country_code'] == 1) {
1071 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1073 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1081 function pdValueOrNull($key, $value)
1084 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1085 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1086 (empty($value) || $value == '0000-00-00')
1090 return "'" . add_escape_custom($value) . "'";
1095 * Create or update patient data from an array.
1097 * This is a wrapper function for the PatientService which is now the single point
1098 * of patient creation and update.
1100 * If successful, returns the pid of the patient
1104 * @param false $create
1107 function updatePatientData($pid, $new, $create = false)
1109 // Create instance of patient service
1110 $patientService = new PatientService();
1115 $result = $patientService->databaseInsert($new);
1116 updateDupScore($result['pid']);
1119 $result = $patientService->databaseUpdate($new);
1122 // From the returned patient data array
1123 // retrieve the data and return the pid
1124 $pid = $result['pid'];
1129 function newEmployerData(
1139 return sqlInsert("insert into employer_data set
1140 name='" . add_escape_custom($name) . "',
1141 street='" . add_escape_custom($street) . "',
1142 postal_code='" . add_escape_custom($postal_code) . "',
1143 city='" . add_escape_custom($city) . "',
1144 state='" . add_escape_custom($state) . "',
1145 country='" . add_escape_custom($country) . "',
1146 pid='" . add_escape_custom($pid) . "',
1151 // Create or update employer data from an array.
1153 function updateEmployerData($pid, $new, $create = false)
1155 $colnames = array('name','street','city','state','postal_code','country');
1158 $set = "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1159 foreach ($colnames as $key) {
1160 $value = isset($new[$key]) ? $new[$key] : '';
1161 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1164 return sqlInsert("INSERT INTO employer_data SET $set");
1167 $old = getEmployerData($pid);
1169 foreach ($colnames as $key) {
1170 $value = empty($old[$key]) ? '' : $old[$key];
1171 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1172 $value = $new[$key];
1176 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1180 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1181 return sqlInsert("INSERT INTO employer_data SET $set");
1184 return ($old['id'] ?? '');
1188 // This updates or adds the given insurance data info, while retaining any
1189 // previously added insurance_data rows that should be preserved.
1190 // This does not directly support the maintenance of non-current insurance.
1192 function newInsuranceData(
1196 $policy_number = "",
1199 $subscriber_lname = "",
1200 $subscriber_mname = "",
1201 $subscriber_fname = "",
1202 $subscriber_relationship = "",
1203 $subscriber_ss = "",
1204 $subscriber_DOB = null,
1205 $subscriber_street = "",
1206 $subscriber_postal_code = "",
1207 $subscriber_city = "",
1208 $subscriber_state = "",
1209 $subscriber_country = "",
1210 $subscriber_phone = "",
1211 $subscriber_employer = "",
1212 $subscriber_employer_street = "",
1213 $subscriber_employer_city = "",
1214 $subscriber_employer_postal_code = "",
1215 $subscriber_employer_state = "",
1216 $subscriber_employer_country = "",
1218 $subscriber_sex = "",
1219 $effective_date = null,
1220 $accept_assignment = "TRUE",
1224 if (strlen($type) <= 0) {
1228 if (is_null($accept_assignment)) {
1229 $accept_assignment = "TRUE";
1231 if (is_null($policy_type)) {
1235 // If empty dates were passed, then null.
1236 if (empty($effective_date)) {
1237 $effective_date = null;
1239 if (empty($subscriber_DOB)) {
1240 $subscriber_DOB = null;
1243 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1244 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1245 $idrow = sqlFetchArray($idres);
1247 // Replace the most recent entry in any of the following cases:
1248 // * Its effective date is >= this effective date.
1249 // * It is the first entry and it has no (insurance) provider.
1250 // * There is no encounter that is earlier than the new effective date but
1251 // on or after the old effective date.
1252 // Otherwise insert a new entry.
1256 // convert date from null to "0000-00-00" for below strcmp and query
1257 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1258 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1259 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1262 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1265 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1266 "WHERE pid = ? AND date < ? AND " .
1267 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1268 if ($ferow['count'] == 0) {
1276 // TBD: This is a bit dangerous in that a typo in entering the effective
1277 // date can wipe out previous insurance history. So we want some data
1278 // entry validation somewhere.
1279 if ($effective_date === null) {
1280 sqlStatement("DELETE FROM insurance_data WHERE " .
1281 "pid = ? AND type = ? AND " .
1282 "id != ?", array($pid, $type, $idrow['id']));
1284 sqlStatement("DELETE FROM insurance_data WHERE " .
1285 "pid = ? AND type = ? AND date >= ? AND " .
1286 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1290 $data['type'] = $type;
1291 $data['provider'] = $provider;
1292 $data['policy_number'] = $policy_number;
1293 $data['group_number'] = $group_number;
1294 $data['plan_name'] = $plan_name;
1295 $data['subscriber_lname'] = $subscriber_lname;
1296 $data['subscriber_mname'] = $subscriber_mname;
1297 $data['subscriber_fname'] = $subscriber_fname;
1298 $data['subscriber_relationship'] = $subscriber_relationship;
1299 $data['subscriber_ss'] = $subscriber_ss;
1300 $data['subscriber_DOB'] = $subscriber_DOB;
1301 $data['subscriber_street'] = $subscriber_street;
1302 $data['subscriber_postal_code'] = $subscriber_postal_code;
1303 $data['subscriber_city'] = $subscriber_city;
1304 $data['subscriber_state'] = $subscriber_state;
1305 $data['subscriber_country'] = $subscriber_country;
1306 $data['subscriber_phone'] = $subscriber_phone;
1307 $data['subscriber_employer'] = $subscriber_employer;
1308 $data['subscriber_employer_city'] = $subscriber_employer_city;
1309 $data['subscriber_employer_street'] = $subscriber_employer_street;
1310 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1311 $data['subscriber_employer_state'] = $subscriber_employer_state;
1312 $data['subscriber_employer_country'] = $subscriber_employer_country;
1313 $data['copay'] = $copay;
1314 $data['subscriber_sex'] = $subscriber_sex;
1315 $data['pid'] = $pid;
1316 $data['date'] = $effective_date;
1317 $data['accept_assignment'] = $accept_assignment;
1318 $data['policy_type'] = $policy_type;
1319 updateInsuranceData($idrow['id'], $data);
1320 return $idrow['id'];
1323 "INSERT INTO `insurance_data` SET `type` = ?,
1325 `policy_number` = ?,
1328 `subscriber_lname` = ?,
1329 `subscriber_mname` = ?,
1330 `subscriber_fname` = ?,
1331 `subscriber_relationship` = ?,
1332 `subscriber_ss` = ?,
1333 `subscriber_DOB` = ?,
1334 `subscriber_street` = ?,
1335 `subscriber_postal_code` = ?,
1336 `subscriber_city` = ?,
1337 `subscriber_state` = ?,
1338 `subscriber_country` = ?,
1339 `subscriber_phone` = ?,
1340 `subscriber_employer` = ?,
1341 `subscriber_employer_city` = ?,
1342 `subscriber_employer_street` = ?,
1343 `subscriber_employer_postal_code` = ?,
1344 `subscriber_employer_state` = ?,
1345 `subscriber_employer_country` = ?,
1347 `subscriber_sex` = ?,
1350 `accept_assignment` = ?,
1361 $subscriber_relationship,
1365 $subscriber_postal_code,
1368 $subscriber_country,
1370 $subscriber_employer,
1371 $subscriber_employer_city,
1372 $subscriber_employer_street,
1373 $subscriber_employer_postal_code,
1374 $subscriber_employer_state,
1375 $subscriber_employer_country,
1387 // This is used internally only.
1388 function updateInsuranceData($id, $new)
1390 $fields = sqlListFields("insurance_data");
1393 foreach ($new as $key => $value) {
1394 if (in_array($key, $fields)) {
1395 $use[$key] = $value;
1400 $sql = "UPDATE insurance_data SET ";
1401 foreach ($use as $key => $value) {
1402 $sql .= "`" . $key . "` = ?, ";
1403 array_push($sqlBindArray, $value);
1406 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1407 array_push($sqlBindArray, $id);
1409 sqlStatement($sql, $sqlBindArray);
1412 function newHistoryData($pid, $new = false)
1414 $socialHistoryService = new SocialHistoryService();
1416 $insertionRecord = $new;
1417 if (!is_array(($insertionRecord))) {
1418 $insertionRecord = [
1422 $socialHistoryService->create($insertionRecord);
1425 function updateHistoryData($pid, $new)
1427 $socialHistoryService = new SocialHistoryService();
1428 return $socialHistoryService->updateHistoryDataForPatientPid($pid, $new);
1432 // in months if < 2 years old
1433 // in years if > 2 years old
1434 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1435 // (optional) nowYMD is a date in YYYYMMDD format
1436 function getPatientAge($dobYMD, $nowYMD = null)
1438 $patientService = new PatientService();
1439 return $patientService->getPatientAge($dobYMD, $nowYMD);
1443 * Wrapper to make sure the clinical rules dates formats corresponds to the
1444 * format expected by getPatientAgeYMD
1446 * @param string $dob date of birth
1447 * @param string $target date to calculate age on
1448 * @return array containing
1449 * age - decimal age in years
1450 * age_in_months - decimal age in months
1451 * ageinYMD - formatted string #y #m #d */
1452 function parseAgeInfo($dob, $target)
1454 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1455 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1457 // Prepare target (Y-M-D H:M:S)
1458 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1460 return getPatientAgeYMD($dateDOB, $dateTarget);
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
1472 function getPatientAgeYMD($dob, $date = null)
1474 $service = new PatientService();
1475 return $service->getPatientAgeYMD($dob, $date);
1478 // Returns Age in days
1479 // in months if < 2 years old
1480 // in years if > 2 years old
1481 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1482 // (optional) nowYMD is a date in YYYYMMDD format
1483 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1487 // strip any dashes from the DOB
1488 $dobYMD = preg_replace("/-/", "", $dobYMD);
1489 $dobDay = substr($dobYMD, 6, 2);
1490 $dobMonth = substr($dobYMD, 4, 2);
1491 $dobYear = substr($dobYMD, 0, 4);
1493 // set the 'now' date values
1494 if ($nowYMD == null) {
1495 $nowDay = date("d");
1496 $nowMonth = date("m");
1497 $nowYear = date("Y");
1499 $nowDay = substr($nowYMD, 6, 2);
1500 $nowMonth = substr($nowYMD, 4, 2);
1501 $nowYear = substr($nowYMD, 0, 4);
1505 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1506 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1507 $timediff = $nowtime - $dobtime;
1508 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1513 * Returns a string to be used to display a patient's age
1515 * @param type $dobYMD
1516 * @param type $asOfYMD
1517 * @return string suitable for displaying patient's age based on preferences
1519 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1521 $service = new PatientService();
1522 return $service->getPatientAgeDisplay($dobYMD, $asOfYMD);
1524 function dateToDB($date)
1526 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1531 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1532 * for the given patient on the given date.
1534 * @param int The PID of the patient.
1535 * @param string Date in yyyy-mm-dd format.
1536 * @return array Array of 0-3 insurance_data rows.
1538 function getEffectiveInsurances($patient_id, $encdate)
1541 foreach (array('primary','secondary','tertiary') as $instype) {
1543 "SELECT * FROM insurance_data " .
1544 "WHERE pid = ? AND type = ? " .
1545 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1546 array($patient_id, $instype, $encdate)
1548 if (empty($tmp['provider'])) {
1559 * Get all requisition insurance companies
1564 function getAllinsurances($pid)
1567 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1568 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1569 b.name, c.line1, c.line2, c.city, c.state, c.zip
1570 FROM `insurance_data` AS a
1571 RIGHT JOIN insurance_companies AS b
1572 ON a.provider = b.id
1573 RIGHT JOIN addresses AS c
1574 ON a.provider = c.foreign_id
1576 $inco = sqlStatement($sql, array($pid));
1578 while ($icl = sqlFetchArray($inco)) {
1585 * Get the patient's balance due. Normally this excludes amounts that are out
1586 * to insurance. If you want to include what insurance owes, set the second
1587 * parameter to true.
1589 * @param int The PID of the patient.
1590 * @param boolean Indicates if amounts owed by insurance are to be included.
1591 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1592 * @return number The balance.
1594 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1597 $bindarray = array($pid);
1598 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1599 "last_level_closed, stmt_count " .
1600 "FROM form_encounter WHERE pid = ?";
1602 $sqlstatement .= " AND encounter = ?";
1603 array_push($bindarray, $eid);
1605 $feres = sqlStatement($sqlstatement, $bindarray);
1606 while ($ferow = sqlFetchArray($feres)) {
1607 $encounter = $ferow['encounter'];
1608 $dos = substr($ferow['date'], 0, 10);
1609 $insarr = getEffectiveInsurances($pid, $dos);
1610 $inscount = count($insarr);
1611 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1612 // It's out to insurance so only the co-pay might be due.
1614 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1615 "pid = ? AND encounter = ? AND " .
1616 "code_type = 'copay' AND activity = 1",
1617 array($pid, $encounter)
1620 "SELECT SUM(pay_amount) AS payments " .
1621 "FROM ar_activity WHERE " .
1622 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1623 array($pid, $encounter)
1625 // going to comment this out for now since computing future copays doesn't
1626 // equate to cash in hand, which shows in the Billing widget in dashboard 4-23-21
1627 // $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1630 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1631 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1632 $ptbal = $copay + $amt - $pay;
1633 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1637 // Including insurance or not out to insurance, everything is due.
1638 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1639 "pid = ? AND encounter = ? AND " .
1640 "activity = 1", array($pid, $encounter));
1641 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1642 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1643 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1644 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1645 "pid = ? AND encounter = ?", array($pid, $encounter));
1646 $balance += $brow['amount'] + $srow['amount']
1647 - $drow['payments'] - $drow['adjustments'];
1651 return sprintf('%01.2f', $balance);
1654 function get_patient_balance_excluding($pid, $excluded = -1)
1656 // We join form_encounter here to make sure we only count amounts for
1657 // encounters that exist. We've had some trouble before with encounters
1658 // that were deleted but leaving line items in the database.
1660 "SELECT SUM(b.fee) AS amount " .
1661 "FROM billing AS b, form_encounter AS fe WHERE " .
1662 "b.pid = ? AND b.encounter != 0 AND b.encounter != ? AND b.activity = 1 AND " .
1663 "fe.pid = b.pid AND fe.encounter = b.encounter",
1664 array($pid, $excluded)
1667 "SELECT SUM(s.fee) AS amount " .
1668 "FROM drug_sales AS s, form_encounter AS fe WHERE " .
1669 "s.pid = ? AND s.encounter != 0 AND s.encounter != ? AND " .
1670 "fe.pid = s.pid AND fe.encounter = s.encounter",
1671 array($pid, $excluded)
1674 "SELECT SUM(a.pay_amount) AS payments, " .
1675 "SUM(a.adj_amount) AS adjustments " .
1676 "FROM ar_activity AS a, form_encounter AS fe WHERE " .
1677 "a.deleted IS NULL AND a.pid = ? AND a.encounter != 0 AND a.encounter != ? AND " .
1678 "fe.pid = a.pid AND fe.encounter = a.encounter",
1679 array($pid, $excluded)
1683 $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments']
1687 // Function to check if patient is deceased.
1689 // $pid - patient id
1690 // $date - date checking if deceased (will default to current date if blank)
1692 // If deceased, then will return the number of
1693 // days that patient has been deceased and the deceased date.
1694 // If not deceased, then will return false.
1695 function is_patient_deceased($pid, $date = '')
1698 // Set date to current if not set
1699 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1701 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1702 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1703 "FROM `patient_data` " .
1704 "WHERE `pid` = ? AND " .
1705 dateEmptySql('deceased_date', true, true) .
1706 "AND `deceased_date` <= ?", array($date,$pid,$date));
1708 if (empty($results)) {
1709 // Patient is alive, so return false
1712 // Patient is dead, so return the number of days patient has been deceased.
1713 // Don't let it be zero days or else will confuse calls to this function.
1714 if ($results['days_deceased'] === 0) {
1715 $results['days_deceased'] = 1;
1722 // This computes, sets and returns the dup score for the given patient.
1724 function updateDupScore($pid)
1727 "SELECT MAX(" . getDupScoreSQL() . ") AS dupscore " .
1728 "FROM patient_data AS p1, patient_data AS p2 WHERE " .
1729 "p1.pid = ? AND p2.pid < p1.pid",
1732 $dupscore = empty($row['dupscore']) ? 0 : $row['dupscore'];
1734 "UPDATE patient_data SET dupscore = ? WHERE pid = ?",
1735 array($dupscore, $pid)