fix: dashboard prescriptions typo (#6454)
[openemr.git] / library / patient.inc.php
blob22a4b7e9f2cdd5b1ff66fa9102fe9fb191d1e846
1 <?php
3 /**
4 * patient.inc.php includes functions for manipulating patient information.
6 * @package OpenEMR
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-2022 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 global $facilityService;
27 $facilityService = new FacilityService();
29 // These are for sports team use:
30 $PLAYER_FITNESSES = array(
31 xl('Full Play'),
32 xl('Full Training'),
33 xl('Restricted Training'),
34 xl('Injured Out'),
35 xl('Rehabilitation'),
36 xl('Illness'),
37 xl('International Duty')
39 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
41 // Hard-coding this array because its values and meanings are fixed by the 837p
42 // standard and we don't want people messing with them.
43 global $policy_types;
44 $policy_types = array(
45 '' => xl('N/A'),
46 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
47 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
48 '14' => xl('No-fault Insurance including Auto is Primary'),
49 '15' => xl('Worker`s Compensation'),
50 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
51 '41' => xl('Black Lung'),
52 '42' => xl('Veteran`s Administration'),
53 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
54 '47' => xl('Other Liability Insurance is Primary'),
57 /**
58 * Get a patient's demographic data.
60 * @param int $pid The PID of the patient
61 * @param string $given an optional subsection of the patient's demographic
62 * data to retrieve.
63 * @return array The requested subsection of a patient's demographic data.
64 * If no subsection was given, returns everything, with the
65 * date of birth as the last field.
67 // To prevent sql injection on this function, if a variable is used for $given parameter, then
68 // it needs to be escaped via whitelisting prior to using this function.
69 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
71 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
72 return sqlQuery($sql, array($pid));
75 function getInsuranceProvider($ins_id)
78 $sql = "select name from insurance_companies where id=?";
79 $row = sqlQuery($sql, array($ins_id));
80 return $row['name'] ?? '';
83 function getInsuranceProviders()
85 $returnval = array();
87 if (true) {
88 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
89 $rez = sqlStatement($sql);
90 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
91 $returnval[$row['id']] = $row['name'];
93 } else { // Please leave this here. I have a user who wants to see zip codes and PO
94 // box numbers listed along with the insurance company names, as many companies
95 // have different billing addresses for different plans. -- Rod Roark
96 $sql = "select insurance_companies.name, insurance_companies.id, " .
97 "addresses.zip, addresses.line1 " .
98 "from insurance_companies, addresses " .
99 "where addresses.foreign_id = insurance_companies.id " .
100 "order by insurance_companies.name, addresses.zip";
102 $rez = sqlStatement($sql);
104 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
105 preg_match("/\d+/", $row['line1'], $matches);
106 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
107 "," . $matches[0] . ")";
111 return $returnval;
114 function getInsuranceProvidersExtra()
116 $returnval = array();
117 // add a global and if for where to allow inactive inscompanies
119 $sql = "SELECT insurance_companies.name, insurance_companies.id, insurance_companies.cms_id,
120 addresses.line1, addresses.line2, addresses.city, addresses.state, addresses.zip
121 FROM insurance_companies, addresses
122 WHERE addresses.foreign_id = insurance_companies.id
123 AND insurance_companies.inactive != 1
124 ORDER BY insurance_companies.name, addresses.zip";
126 $rez = sqlStatement($sql);
128 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
129 switch ($GLOBALS['insurance_information']) {
130 case $GLOBALS['insurance_information'] = '0':
131 $returnval[$row['id']] = $row['name'];
132 break;
133 case $GLOBALS['insurance_information'] = '1':
134 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
135 break;
136 case $GLOBALS['insurance_information'] = '2':
137 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
138 break;
139 case $GLOBALS['insurance_information'] = '3':
140 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
141 break;
142 case $GLOBALS['insurance_information'] = '4':
143 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
144 ", " . $row['zip'] . ")";
145 break;
146 case $GLOBALS['insurance_information'] = '5':
147 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
148 ", " . $row['state'] . ", " . $row['zip'] . ")";
149 break;
150 case $GLOBALS['insurance_information'] = '6':
151 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
152 ", " . $row['state'] . ", " . $row['zip'] . ", " . $row['cms_id'] . ")";
153 break;
154 case $GLOBALS['insurance_information'] = '7':
155 preg_match("/\d+/", $row['line1'], $matches);
156 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
157 "," . $matches[0] . ")";
158 break;
162 return $returnval;
165 // ----------------------------------------------------------------------------
166 // Get one facility row. If the ID is not specified, then get either the
167 // "main" (billing) facility, or the default facility of the currently
168 // logged-in user. This was created to support genFacilityTitle() but
169 // may find additional uses.
171 function getFacility($facid = 0)
173 global $facilityService;
175 $facility = null;
177 if ($facid > 0) {
178 return $facilityService->getById($facid);
181 if ($GLOBALS['login_into_facility']) {
182 //facility is saved in sessions
183 $facility = $facilityService->getById($_SESSION['facilityId']);
184 } else {
185 if ($facid == 0) {
186 $facility = $facilityService->getPrimaryBillingLocation();
187 } else {
188 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
192 return $facility;
195 // Generate a report title including report name and facility name, address
196 // and phone.
198 function genFacilityTitle($repname = '', $facid = 0, $logo = "")
200 $s = '';
201 $s .= "<table class='ftitletable' width='100%'>\n";
202 $s .= " <tr>\n";
203 if (empty($logo)) {
204 $s .= " <td align='left' class='ftitlecell1'>" . text($repname) . "</td>\n";
205 } else {
206 $s .= " <td align='left' class='ftitlecell1'><img class='h-auto' style='max-height:8%;' src='" . attr($logo) . "' /></td>\n";
207 $s .= " <td align='left' class='ftitlecellm'><h2>" . text($repname) . "</h2></td>\n";
209 $s .= " <td align='right' class='ftitlecell2'>\n";
210 $r = getFacility($facid);
211 if (!empty($r)) {
212 $s .= "<b>" . text($r['name'] ?? '') . "</b>\n";
213 if (!empty($r['street'])) {
214 $s .= "<br />" . text($r['street']) . "\n";
217 if (!empty($r['city']) || !empty($r['state']) || !empty($r['postal_code'])) {
218 $s .= "<br />";
219 if ($r['city']) {
220 $s .= text($r['city']);
223 if ($r['state']) {
224 if ($r['city']) {
225 $s .= ", \n";
228 $s .= text($r['state']);
231 if ($r['postal_code']) {
232 $s .= " " . text($r['postal_code']);
235 $s .= "\n";
238 if (!empty($r['country_code'])) {
239 $s .= "<br />" . text($r['country_code']) . "\n";
242 if (preg_match('/[1-9]/', ($r['phone'] ?? ''))) {
243 $s .= "<br />" . text($r['phone']) . "\n";
247 $s .= " </td>\n";
248 $s .= " </tr>\n";
249 $s .= "</table>\n";
250 return $s;
254 GET FACILITIES
256 returns all facilities or just the id for the first one
257 (FACILITY FILTERING (lemonsoftware))
259 @param string - if 'first' return first facility ordered by id
260 @return array | int for 'first' case
262 function getFacilities($first = '')
264 global $facilityService;
266 $fres = $facilityService->getAllFacility();
268 if ($first == 'first') {
269 return $fres[0]['id'];
270 } else {
271 return $fres;
275 //(CHEMED) facility filter
276 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
278 $param1 = "";
279 if ($providers_only === 'any') {
280 $param1 = " AND authorized = 1 AND active = 1 ";
281 } elseif ($providers_only) {
282 $param1 = " AND authorized = 1 AND calendar = 1 ";
285 //--------------------------------
286 //(CHEMED) facility filter
287 $param2 = "";
288 if ($facility) {
289 if ($GLOBALS['restrict_user_facility']) {
290 $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))";
291 } else {
292 $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
296 //--------------------------------
298 $command = "=";
299 if ($providerID == "%") {
300 $command = "like";
303 // removing active from query since is checked above with $providers_only argument
304 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
305 "from users where username != '' and id $command '" .
306 add_escape_custom($providerID) . "' " . $param1 . $param2;
307 // sort by last name -- JRM June 2008
308 $query .= " ORDER BY lname, fname ";
309 $rez = sqlStatement($query);
310 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
311 $returnval[$iter] = $row;
314 //if only one result returned take the key/value pairs in array [0] and merge them down into
315 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
317 if ($iter == 1) {
318 $akeys = array_keys($returnval[0]);
319 foreach ($akeys as $key) {
320 $returnval[0][$key] = $returnval[0][$key];
324 return ($returnval ?? null);
327 function getProviderName($providerID, $provider_only = 'any')
329 $pi = getProviderInfo($providerID, $provider_only);
330 if (!empty($pi[0]["lname"]) && (strlen($pi[0]["lname"]) > 0)) {
331 if (!empty($pi[0]["suffix"]) && (strlen($pi[0]["suffix"]) > 0)) {
332 $pi[0]["lname"] .= ", " . $pi[0]["suffix"];
335 return $pi[0]['fname'] . " " . $pi[0]['lname'];
338 return "";
341 function getProviderId($providerName)
343 $query = "select id from users where username = ?";
344 $rez = sqlStatement($query, array($providerName));
345 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
346 $returnval[$iter] = $row;
349 return $returnval;
352 // To prevent sql injection on this function, if a variable is used for $given parameter, then
353 // it needs to be escaped via whitelisting prior to using this function; see lines 2020-2121 of
354 // library/clinical_rules.php script for example of this.
355 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
357 $where = '';
358 if ($given == 'tobacco') {
359 $where = 'tobacco is not null and';
362 if ($dateStart && $dateEnd) {
363 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? and date <= ? order by date DESC, id DESC limit 0,1", array($pid,$dateStart,$dateEnd));
364 } elseif ($dateStart && !$dateEnd) {
365 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? order by date DESC, id DESC limit 0,1", array($pid,$dateStart));
366 } elseif (!$dateStart && $dateEnd) {
367 $res = sqlQuery("select $given from history_data where $where pid = ? and date <= ? order by date DESC, id DESC limit 0,1", array($pid,$dateEnd));
368 } else {
369 $res = sqlQuery("select $given from history_data where $where pid = ? order by date DESC, id DESC limit 0,1", array($pid));
372 return $res;
375 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
376 // To prevent sql injection on this function, if a variable is used for $given parameter, then
377 // it needs to be escaped via whitelisting prior to using this function.
378 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
380 $sql = "select $given from insurance_data as insd " .
381 "left join insurance_companies as ic on ic.id = insd.provider " .
382 "where pid = ? and type = ? order by date DESC limit 1";
383 return sqlQuery($sql, array($pid, $type));
386 // To prevent sql injection on this function, if a variable is used for $given parameter, then
387 // it needs to be escaped via whitelisting prior to using this function.
388 function getInsuranceDataByDate(
389 $pid,
390 $date,
391 $type,
392 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
394 // this must take the date in the following manner: YYYY-MM-DD
395 // this function recalls the insurance value that was most recently enterred from the
396 // given date. it will call up most recent records up to and on the date given,
397 // but not records enterred after the given date
398 $sql = "select $given from insurance_data as insd " .
399 "left join insurance_companies as ic on ic.id = provider " .
400 "where pid = ? and (date_format(date,'%Y-%m-%d') <= ? OR date IS NULL) and " .
401 "type=? order by date DESC limit 1";
402 return sqlQuery($sql, array($pid,$date,$type));
405 function get_unallocated_patient_balance($pid)
407 $unallocated = 0.0;
408 $query = "SELECT a.session_id, a.pay_total, a.global_amount " .
409 "FROM ar_session AS a " .
410 "WHERE a.patient_id = ? AND " .
411 "a.adjustment_code = 'pre_payment' AND a.closed = 0";
412 $res = sqlStatement($query, array($pid));
413 while ($row = sqlFetchArray($res)) {
414 $total_amt = $row['pay_total'] - $row['global_amount'];
415 $rs = sqlQuery("SELECT sum(pay_amount) AS total_pay_amt FROM ar_activity WHERE session_id = ? AND pid = ? AND deleted IS NULL", array($row['session_id'], $pid));
416 $pay_amount = $rs['total_pay_amt'];
417 $unallocated += ($total_amt - $pay_amount);
419 return sprintf('%01.2f', $unallocated);
422 function getInsuranceNameByDate(
423 $pid,
424 $date,
425 $type,
426 $given = "ic.name as provider_name"
428 // this must take the date in the following manner: YYYY-MM-DD
429 // this function recalls the insurance value that was most recently enterred from the
430 // given date. it will call up most recent records up to and on the date given,
431 // but not records enterred after the given date
432 $sql = "select $given from insurance_data as insd " .
433 "left join insurance_companies as ic on ic.id = provider " .
434 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
435 "type = ? order by date DESC limit 1";
437 $row = sqlQuery($sql, array($pid, $date, $type));
438 return $row['provider_name'];
441 // To prevent sql injection on this function, if a variable is used for $given parameter, then
442 // it needs to be escaped via whitelisting prior to using this function.
443 function getEmployerData($pid, $given = "*")
445 $sql = "select $given from employer_data where pid = ? order by date DESC limit 0,1";
446 return sqlQuery($sql, array($pid));
449 // Generate a consistent header and footer, used for printed patient reports
450 function genPatientHeaderFooter($pid, $DOS = null)
452 $patient_dob = getPatientData($pid, "DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS");
453 $patient_name = getPatientName($pid);
455 // Header
456 $s = '<htmlpageheader name="PageHeader1"><div style="text-align: right; font-weight: bold;">';
457 $s .= text($patient_name) . '&emsp;DOB: ' . text($patient_dob['DOB_TS']);
458 if ($DOS) {
459 $s .= '&emsp;DOS: ' . text($DOS);
461 $s .= '</div></htmlpageheader>';
463 // Footer
464 $s .= '<htmlpagefooter name="PageFooter1"><div style="text-align: right; font-weight: bold;">';
465 $s .= '<div style="float: right; width:33%; text-align: left;">' . oeFormatDateTime(date("Y-m-d H:i:s")) . '</div>';
466 $s .= '<div style="float: right; width:33%; text-align: center;">{PAGENO}/{nbpg}</div>';
467 $s .= '<div style="float: right; width:33%; text-align: right;">' . text($patient_name) . '</div>';
468 $s .= '</div></htmlpagefooter>';
470 // Set the header and footer in the current document
471 $s .= '<sethtmlpageheader name="PageHeader1" page="ALL" value="ON" show-this-page="1" />';
472 $s .= '<sethtmlpagefooter name="PageFooter1" page="ALL" value="ON" />';
474 return $s;
477 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
479 // When the limit is exceeded, find out what the unlimited count would be.
480 $GLOBALS['PATIENT_INC_COUNT'] = $count;
481 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
482 if ($limit != "all") {
483 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
484 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
489 * Allow the last name to be followed by a comma and some part of a first name(can
490 * also place middle name after the first name with a space separating them)
491 * Allows comma alone followed by some part of a first name(can also place middle name
492 * after the first name with a space separating them).
493 * Allows comma alone preceded by some part of a last name.
494 * If no comma or space, then will search both last name and first name.
495 * If the first letter of either name is capital, searches for name starting
496 * with given substring (the expected behavior). If it is lower case, it
497 * searches for the substring anywhere in the name. This applies to either
498 * last name, first name, and middle name.
499 * Also allows first name followed by middle and/or last name when separated by spaces.
500 * @param string $term
501 * @param string $given
502 * @param string $orderby
503 * @param string $limit
504 * @param string $start
505 * @return array
507 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
508 // it needs to be escaped via whitelisting prior to using this function.
509 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")
511 $names = getPatientNameSplit($term);
513 foreach ($names as $key => $val) {
514 if (!empty($val)) {
515 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
516 $names[$key] = '%' . $val . '%';
517 } else {
518 $names[$key] = $val . '%';
523 // Debugging section below
524 //if(array_key_exists('first',$names)) {
525 // error_log("first name search term :".$names['first']);
527 //if(array_key_exists('middle',$names)) {
528 // error_log("middle name search term :".$names['middle']);
530 //if(array_key_exists('last',$names)) {
531 // error_log("last name search term :".$names['last']);
533 // Debugging section above
535 $sqlBindArray = array();
536 if (array_key_exists('last', $names) && $names['last'] == '') {
537 // Do not search last name
538 $where = "fname LIKE ? ";
539 array_push($sqlBindArray, $names['first']);
540 if ($names['middle'] != '') {
541 $where .= "AND mname LIKE ? ";
542 array_push($sqlBindArray, $names['middle']);
544 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
545 // Do not search first name or middle name
546 $where = "lname LIKE ? ";
547 array_push($sqlBindArray, $names['last']);
548 } elseif (empty($names['first']) && !empty($names['last'])) {
549 // Search both first name and last name with same term
550 $names['first'] = $names['last'];
551 $where = "lname LIKE ? OR fname LIKE ? ";
552 array_push($sqlBindArray, $names['last'], $names['first']);
553 } elseif ($names['middle'] != '') {
554 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
555 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
556 } else {
557 $where = "lname LIKE ? AND fname LIKE ? ";
558 array_push($sqlBindArray, $names['last'], $names['first']);
561 if (!empty($GLOBALS['pt_restrict_field'])) {
562 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
563 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
564 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
565 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
566 array_push($sqlBindArray, $_SESSION["authUser"]);
570 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
571 if ($limit != "all") {
572 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
575 $rez = sqlStatement($sql, $sqlBindArray);
577 $returnval = array();
578 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
579 $returnval[$iter] = $row;
582 if (is_countable($returnval)) {
583 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
586 return $returnval;
589 * Accept a string used by a search function expected to find a patient name,
590 * then split up the string if a comma or space exists. Return an array having
591 * from 1 to 3 elements, named first, middle, and last.
592 * See above getPatientLnames() function for details on how the splitting occurs.
593 * @param string $term
594 * @return array
596 function getPatientNameSplit($term)
598 $term = trim($term);
599 if (strpos($term, ',') !== false) {
600 $names = explode(',', $term);
601 $n['last'] = $names[0];
602 if (strpos(trim($names[1]), ' ') !== false) {
603 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
604 } else {
605 $n['first'] = $names[1];
607 } elseif (strpos($term, ' ') !== false) {
608 $names = explode(' ', $term);
609 if (count($names) == 1) {
610 $n['last'] = $names[0];
611 } elseif (count($names) == 3) {
612 $n['first'] = $names[0];
613 $n['middle'] = $names[1];
614 $n['last'] = $names[2];
615 } else {
616 // This will handle first and last name or first followed by
617 // multiple names only using just the last of the names in the list.
618 $n['first'] = $names[0];
619 $n['last'] = end($names);
621 } else {
622 $n['last'] = $term;
623 if (empty($n['last'])) {
624 $n['last'] = '%';
628 // Trim whitespace off the names before returning
629 foreach ($n as $key => $val) {
630 $n[$key] = trim($val);
633 return $n; // associative array containing names
636 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
637 // it needs to be escaped via whitelisting prior to using this function.
638 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")
641 $sqlBindArray = array();
642 $where = "pubpid LIKE ? ";
643 array_push($sqlBindArray, $pid . "%");
644 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
645 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
646 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
647 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
648 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
649 array_push($sqlBindArray, $_SESSION["authUser"]);
653 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
654 if ($limit != "all") {
655 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
658 $rez = sqlStatement($sql, $sqlBindArray);
659 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
660 $returnval[$iter] = $row;
663 if (is_countable($returnval)) {
664 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
666 return $returnval;
669 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
670 // it needs to be escaped via whitelisting prior to using this function.
671 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")
673 $layoutCols = sqlStatement(
674 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor != 0",
675 array('em\_%')
678 $sqlBindArray = array();
679 $where = "";
680 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
681 if ($iter > 0) {
682 $where .= " or ";
685 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
686 array_push($sqlBindArray, "%" . $searchTerm . "%");
689 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
690 if ($limit != "all") {
691 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
694 $rez = sqlStatement($sql, $sqlBindArray);
695 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
696 $returnval[$iter] = $row;
699 if (is_countable($returnval)) {
700 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
702 return $returnval;
705 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
706 // it needs to be escaped via whitelisting prior to using this function.
707 function getByPatientDemographicsFilter(
708 $searchFields,
709 $searchTerm = "%",
710 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
711 $orderby = "lname ASC, fname ASC",
712 $limit = "all",
713 $start = "0",
714 $search_service_code = ''
717 $layoutCols = explode('~', $searchFields);
718 $sqlBindArray = array();
719 $where = "";
720 $i = 0;
721 foreach ($layoutCols as $val) {
722 if (empty($val)) {
723 continue;
726 if ($i > 0) {
727 $where .= " or ";
730 if ($val == 'pid') {
731 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " = ? ";
732 array_push($sqlBindArray, $searchTerm);
733 } else {
734 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " like ? ";
735 array_push($sqlBindArray, $searchTerm . "%");
738 $i++;
741 // If no search terms, ensure valid syntax.
742 if ($i == 0) {
743 $where = "1 = 1";
746 // If a non-empty service code was given, then restrict to patients who
747 // have been provided that service. Since the code is used in a LIKE
748 // clause, % and _ wildcards are supported.
749 if ($search_service_code) {
750 $where = "( $where ) AND " .
751 "( SELECT COUNT(*) FROM billing AS b WHERE " .
752 "b.pid = patient_data.pid AND " .
753 "b.activity = 1 AND " .
754 "b.code_type != 'COPAY' AND " .
755 "b.code LIKE ? " .
756 ") > 0";
757 array_push($sqlBindArray, $search_service_code);
760 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
761 if ($limit != "all") {
762 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
765 $rez = sqlStatement($sql, $sqlBindArray);
766 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
767 $returnval[$iter] = $row;
770 if (is_countable($returnval)) {
771 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
773 return $returnval;
776 // return a collection of Patient PIDs
777 // new arg style by JRM March 2008
778 // 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")
779 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
780 // it needs to be escaped via whitelisting prior to using this function.
781 function getPatientPID($args)
783 $pid = "%";
784 $given = "pid, id, lname, fname, mname, suffix, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
785 $orderby = "lname ASC, fname ASC";
786 $limit = "all";
787 $start = "0";
789 // alter default values if defined in the passed in args
790 if (isset($args['pid'])) {
791 $pid = $args['pid'];
794 if (isset($args['given'])) {
795 $given = $args['given'];
798 if (isset($args['orderby'])) {
799 $orderby = $args['orderby'];
802 if (isset($args['limit'])) {
803 $limit = $args['limit'];
806 if (isset($args['start'])) {
807 $start = $args['start'];
810 $command = "=";
811 if ($pid == -1) {
812 $pid = "%";
813 } elseif (empty($pid)) {
814 $pid = "NULL";
817 if (strstr($pid, "%")) {
818 $command = "like";
821 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
822 if ($limit != "all") {
823 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
826 $rez = sqlStatement($sql);
827 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
828 $returnval[$iter] = $row;
831 return $returnval;
834 /* return a patient's name in the format LAST [SUFFIX], FIRST [MIDDLE] */
835 function getPatientName($pid)
837 if (empty($pid)) {
838 return "";
841 $patientData = getPatientPID(array("pid" => $pid));
842 if (empty($patientData[0]['lname'])) {
843 return "";
846 $patientName = $patientData[0]['lname'];
847 $patientName .= $patientData[0]['suffix'] ? " " . $patientData[0]['suffix'] . ", " : ", ";
848 $patientName .= $patientData[0]['fname'];
849 $patientName .= empty($patientData[0]['mname']) ? "" : " " . $patientData[0]['mname'];
850 return $patientName;
854 * Get a patient's first name, middle name, last name and suffix if applicable.
856 * Returns a properly formatted, complete name when applicable. Example name
857 * would be "John B Doe Jr". No additional punctuation is added. Spaces are
858 * correctly omitted if the middle name of suffix does not apply.
860 * @var $pid int The Patient ID
861 * @returns string The Full Name
863 function getPatientFullNameAsString($pid): string
865 if (empty($pid)) {
866 return '';
868 $ptData = getPatientPID(["pid" => $pid]);
869 $pt = $ptData[0];
871 if (empty($pt['lname'])) {
872 return "";
875 $name = $pt['fname'];
877 if ($pt['mname']) {
878 $name .= " {$pt['mname']}";
881 $name .= " {$pt['lname']}";
883 if ($pt['suffix']) {
884 $name .= " {$pt['suffix']}";
887 return $name;
890 /* return a patient's name in the format FIRST LAST */
891 function getPatientNameFirstLast($pid)
893 if (empty($pid)) {
894 return "";
897 $patientData = getPatientPID(array("pid" => $pid));
898 if (empty($patientData[0]['lname'])) {
899 return "";
902 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
903 return $patientName;
906 /* find patient data by DOB */
907 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
908 // it needs to be escaped via whitelisting prior to using this function.
909 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
911 $sqlBindArray = array();
912 $where = "DOB like ? ";
913 array_push($sqlBindArray, $DOB . "%");
914 if (!empty($GLOBALS['pt_restrict_field'])) {
915 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
916 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
917 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
918 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
919 array_push($sqlBindArray, $_SESSION["authUser"]);
923 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
925 if ($limit != "all") {
926 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
929 $rez = sqlStatement($sql, $sqlBindArray);
930 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
931 $returnval[$iter] = $row;
934 if (is_countable($returnval)) {
935 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
937 return $returnval;
940 /* find patient data by SSN */
941 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
942 // it needs to be escaped via whitelisting prior to using this function.
943 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
945 $sqlBindArray = array();
946 $where = "ss LIKE ?";
947 array_push($sqlBindArray, $ss . "%");
948 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
949 if ($limit != "all") {
950 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
953 $rez = sqlStatement($sql, $sqlBindArray);
954 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
955 $returnval[$iter] = $row;
958 if (is_countable($returnval)) {
959 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
961 return $returnval;
964 //(CHEMED) Search by phone number
965 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
966 // it needs to be escaped via whitelisting prior to using this function.
967 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
969 $phone = preg_replace("/[[:punct:]]/", "", $phone);
970 $sqlBindArray = array();
971 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
972 array_push($sqlBindArray, $phone);
973 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
974 if ($limit != "all") {
975 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
978 $rez = sqlStatement($sql, $sqlBindArray);
979 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
980 $returnval[$iter] = $row;
983 if (is_countable($returnval)) {
984 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
986 return $returnval;
989 //----------------------input functions
990 function newPatientData(
991 $db_id = "",
992 $title = "",
993 $fname = "",
994 $lname = "",
995 $mname = "",
996 $sex = "",
997 $DOB = "",
998 $street = "",
999 $postal_code = "",
1000 $city = "",
1001 $state = "",
1002 $country_code = "",
1003 $ss = "",
1004 $occupation = "",
1005 $phone_home = "",
1006 $phone_biz = "",
1007 $phone_contact = "",
1008 $status = "",
1009 $contact_relationship = "",
1010 $referrer = "",
1011 $referrerID = "",
1012 $email = "",
1013 $language = "",
1014 $ethnoracial = "",
1015 $interpretter = "",
1016 $migrantseasonal = "",
1017 $family_size = "",
1018 $monthly_income = "",
1019 $homeless = "",
1020 $financial_review = "",
1021 $pubpid = "",
1022 $pid = "MAX(pid)+1",
1023 $providerID = "",
1024 $genericname1 = "",
1025 $genericval1 = "",
1026 $genericname2 = "",
1027 $genericval2 = "",
1028 $billing_note = "",
1029 $phone_cell = "",
1030 $hipaa_mail = "",
1031 $hipaa_voice = "",
1032 $squad = 0,
1033 $pharmacy_id = 0,
1034 $drivers_license = "",
1035 $hipaa_notice = "",
1036 $hipaa_message = "",
1037 $regdate = ""
1040 $fitness = 0;
1041 $referral_source = '';
1042 if ($pid) {
1043 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
1044 // Check for brain damage:
1045 if ($db_id != $rez['id']) {
1046 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
1047 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
1048 die($errmsg);
1051 $fitness = $rez['fitness'];
1052 $referral_source = $rez['referral_source'];
1055 // Get the default price level.
1056 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
1057 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
1058 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
1060 $query = ("replace into patient_data set
1061 id='" . add_escape_custom($db_id) . "',
1062 title='" . add_escape_custom($title) . "',
1063 fname='" . add_escape_custom($fname) . "',
1064 lname='" . add_escape_custom($lname) . "',
1065 mname='" . add_escape_custom($mname) . "',
1066 sex='" . add_escape_custom($sex) . "',
1067 DOB='" . add_escape_custom($DOB) . "',
1068 street='" . add_escape_custom($street) . "',
1069 postal_code='" . add_escape_custom($postal_code) . "',
1070 city='" . add_escape_custom($city) . "',
1071 state='" . add_escape_custom($state) . "',
1072 country_code='" . add_escape_custom($country_code) . "',
1073 drivers_license='" . add_escape_custom($drivers_license) . "',
1074 ss='" . add_escape_custom($ss) . "',
1075 occupation='" . add_escape_custom($occupation) . "',
1076 phone_home='" . add_escape_custom($phone_home) . "',
1077 phone_biz='" . add_escape_custom($phone_biz) . "',
1078 phone_contact='" . add_escape_custom($phone_contact) . "',
1079 status='" . add_escape_custom($status) . "',
1080 contact_relationship='" . add_escape_custom($contact_relationship) . "',
1081 referrer='" . add_escape_custom($referrer) . "',
1082 referrerID='" . add_escape_custom($referrerID) . "',
1083 email='" . add_escape_custom($email) . "',
1084 language='" . add_escape_custom($language) . "',
1085 ethnoracial='" . add_escape_custom($ethnoracial) . "',
1086 interpretter='" . add_escape_custom($interpretter) . "',
1087 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1088 family_size='" . add_escape_custom($family_size) . "',
1089 monthly_income='" . add_escape_custom($monthly_income) . "',
1090 homeless='" . add_escape_custom($homeless) . "',
1091 financial_review='" . add_escape_custom($financial_review) . "',
1092 pubpid='" . add_escape_custom($pubpid) . "',
1093 pid= '" . add_escape_custom($pid) . "',
1094 providerID = '" . add_escape_custom($providerID) . "',
1095 genericname1 = '" . add_escape_custom($genericname1) . "',
1096 genericval1 = '" . add_escape_custom($genericval1) . "',
1097 genericname2 = '" . add_escape_custom($genericname2) . "',
1098 genericval2 = '" . add_escape_custom($genericval2) . "',
1099 billing_note= '" . add_escape_custom($billing_note) . "',
1100 phone_cell = '" . add_escape_custom($phone_cell) . "',
1101 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1102 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1103 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1104 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1105 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1106 squad = '" . add_escape_custom($squad) . "',
1107 fitness='" . add_escape_custom($fitness) . "',
1108 referral_source='" . add_escape_custom($referral_source) . "',
1109 regdate='" . add_escape_custom($regdate) . "',
1110 pricelevel='" . add_escape_custom($pricelevel) . "',
1111 date=NOW()");
1113 $id = sqlInsert($query);
1115 if (!$db_id) {
1116 // find the last inserted id for new patient case
1117 $db_id = $id;
1120 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
1122 // set uuid if not set yet (if this was an insert and not an update)
1123 if (empty($foo['uuid'])) {
1124 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
1125 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
1128 return $foo['pid'];
1131 // Supported input date formats are:
1132 // mm/dd/yyyy
1133 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1134 // yyyy/mm/dd
1135 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1137 function fixDate($date, $default = "0000-00-00")
1139 $fixed_date = $default;
1140 $date = trim($date);
1141 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1142 $dmy = preg_split("'[/.-]'", $date);
1143 if ($dmy[0] > 99) {
1144 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1145 } else {
1146 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1147 if ($dmy[2] < 1000) {
1148 $dmy[2] += 1900;
1151 if ($dmy[2] < 1910) {
1152 $dmy[2] += 100;
1155 // Determine if MDY date format is used, preferring Date Display Format from
1156 // global settings if it's not YMD, otherwise guessing from country code.
1157 $using_mdy = empty($GLOBALS['date_display_format']) ?
1158 ($GLOBALS['phone_country_code'] == 1) : ($GLOBALS['date_display_format'] == 1);
1159 if ($using_mdy) {
1160 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1161 } else {
1162 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1167 return $fixed_date;
1170 function pdValueOrNull($key, $value)
1172 if (
1173 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1174 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1175 (empty($value) || $value == '0000-00-00')
1177 return "NULL";
1178 } else {
1179 return "'" . add_escape_custom($value) . "'";
1184 * Create or update patient data from an array.
1186 * This is a wrapper function for the PatientService which is now the single point
1187 * of patient creation and update.
1189 * If successful, returns the pid of the patient
1191 * @param $pid
1192 * @param $new
1193 * @param false $create
1194 * @return mixed
1196 function updatePatientData($pid, $new, $create = false)
1198 // Create instance of patient service
1199 $patientService = new PatientService();
1200 if (
1201 $create === true ||
1202 $pid === null
1204 $result = $patientService->databaseInsert($new);
1205 updateDupScore($result['pid']);
1206 } else {
1207 $new['pid'] = $pid;
1208 $result = $patientService->databaseUpdate($new);
1211 // From the returned patient data array
1212 // retrieve the data and return the pid
1213 $pid = $result['pid'];
1215 return $pid;
1218 function newEmployerData(
1219 $pid,
1220 $name = "",
1221 $street = "",
1222 $postal_code = "",
1223 $city = "",
1224 $state = "",
1225 $country = ""
1228 return sqlInsert("insert into employer_data set
1229 name='" . add_escape_custom($name) . "',
1230 street='" . add_escape_custom($street) . "',
1231 postal_code='" . add_escape_custom($postal_code) . "',
1232 city='" . add_escape_custom($city) . "',
1233 state='" . add_escape_custom($state) . "',
1234 country='" . add_escape_custom($country) . "',
1235 pid='" . add_escape_custom($pid) . "',
1236 date=NOW()
1240 // Create or update employer data from an array.
1242 function updateEmployerData($pid, $new, $create = false)
1244 // used to hard code colnames array('name','street','city','state','postal_code','country');
1245 // but now adapted for layout based
1246 $colnames = array();
1247 foreach ($new as $key => $value) {
1248 $colnames[] = $key;
1251 if ($create) {
1252 $set = "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1253 foreach ($colnames as $key) {
1254 $value = isset($new[$key]) ? $new[$key] : '';
1255 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1258 return sqlInsert("INSERT INTO employer_data SET $set");
1259 } else {
1260 $set = '';
1261 $old = getEmployerData($pid);
1262 $modified = false;
1263 foreach ($colnames as $key) {
1264 $value = empty($old[$key]) ? '' : $old[$key];
1265 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1266 $value = $new[$key];
1267 $modified = true;
1270 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1273 if ($modified) {
1274 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1275 return sqlInsert("INSERT INTO employer_data SET $set");
1278 return ($old['id'] ?? '');
1282 // This updates or adds the given insurance data info, while retaining any
1283 // previously added insurance_data rows that should be preserved.
1284 // This does not directly support the maintenance of non-current insurance.
1286 function newInsuranceData(
1287 $pid,
1288 $type = "",
1289 $provider = "",
1290 $policy_number = "",
1291 $group_number = "",
1292 $plan_name = "",
1293 $subscriber_lname = "",
1294 $subscriber_mname = "",
1295 $subscriber_fname = "",
1296 $subscriber_relationship = "",
1297 $subscriber_ss = "",
1298 $subscriber_DOB = null,
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_street = "",
1307 $subscriber_employer_city = "",
1308 $subscriber_employer_postal_code = "",
1309 $subscriber_employer_state = "",
1310 $subscriber_employer_country = "",
1311 $copay = "",
1312 $subscriber_sex = "",
1313 $effective_date = null,
1314 $accept_assignment = "TRUE",
1315 $policy_type = "",
1316 $effective_date_end = null
1319 if (strlen($type) <= 0) {
1320 return false;
1323 if (is_null($accept_assignment)) {
1324 $accept_assignment = "TRUE";
1326 if (is_null($policy_type)) {
1327 $policy_type = "";
1330 // If empty dates were passed, then null.
1331 if (empty($effective_date)) {
1332 $effective_date = null;
1334 if (empty($subscriber_DOB)) {
1335 $subscriber_DOB = null;
1337 if (empty($effective_date_end)) {
1338 $effective_date_end = null;
1341 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1342 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1343 $idrow = sqlFetchArray($idres);
1345 // Replace the most recent entry in any of the following cases:
1346 // * Its effective date is >= this effective date.
1347 // * It is the first entry and it has no (insurance) provider.
1348 // * There is no encounter that is earlier than the new effective date but
1349 // on or after the old effective date.
1350 // Otherwise insert a new entry.
1352 $replace = false;
1353 if ($idrow) {
1354 // convert date from null to "0000-00-00" for below strcmp and query
1355 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1356 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1357 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1358 $replace = true;
1359 } else {
1360 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1361 $replace = true;
1362 } else {
1363 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1364 "WHERE pid = ? AND date < ? AND " .
1365 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1366 if ($ferow['count'] == 0) {
1367 $replace = true;
1373 if ($replace) {
1374 // TBD: This is a bit dangerous in that a typo in entering the effective
1375 // date can wipe out previous insurance history. So we want some data
1376 // entry validation somewhere.
1377 if ($effective_date === null) {
1378 sqlStatement("DELETE FROM insurance_data WHERE " .
1379 "pid = ? AND type = ? AND " .
1380 "id != ?", array($pid, $type, $idrow['id']));
1381 } else {
1382 sqlStatement("DELETE FROM insurance_data WHERE " .
1383 "pid = ? AND type = ? AND date >= ? AND " .
1384 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1387 $data = array();
1388 $data['type'] = $type;
1389 $data['provider'] = $provider;
1390 $data['policy_number'] = $policy_number;
1391 $data['group_number'] = $group_number;
1392 $data['plan_name'] = $plan_name;
1393 $data['subscriber_lname'] = $subscriber_lname;
1394 $data['subscriber_mname'] = $subscriber_mname;
1395 $data['subscriber_fname'] = $subscriber_fname;
1396 $data['subscriber_relationship'] = $subscriber_relationship;
1397 $data['subscriber_ss'] = $subscriber_ss;
1398 $data['subscriber_DOB'] = $subscriber_DOB;
1399 $data['subscriber_street'] = $subscriber_street;
1400 $data['subscriber_postal_code'] = $subscriber_postal_code;
1401 $data['subscriber_city'] = $subscriber_city;
1402 $data['subscriber_state'] = $subscriber_state;
1403 $data['subscriber_country'] = $subscriber_country;
1404 $data['subscriber_phone'] = $subscriber_phone;
1405 $data['subscriber_employer'] = $subscriber_employer;
1406 $data['subscriber_employer_city'] = $subscriber_employer_city;
1407 $data['subscriber_employer_street'] = $subscriber_employer_street;
1408 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1409 $data['subscriber_employer_state'] = $subscriber_employer_state;
1410 $data['subscriber_employer_country'] = $subscriber_employer_country;
1411 $data['copay'] = $copay;
1412 $data['subscriber_sex'] = $subscriber_sex;
1413 $data['pid'] = $pid;
1414 $data['date'] = $effective_date;
1415 $data['accept_assignment'] = $accept_assignment;
1416 $data['policy_type'] = $policy_type;
1417 $data['date_end'] = $effective_date_end;
1418 updateInsuranceData($idrow['id'], $data);
1419 return $idrow['id'];
1420 } else {
1421 return sqlInsert(
1422 "INSERT INTO `insurance_data` SET `type` = ?,
1423 `provider` = ?,
1424 `policy_number` = ?,
1425 `group_number` = ?,
1426 `plan_name` = ?,
1427 `subscriber_lname` = ?,
1428 `subscriber_mname` = ?,
1429 `subscriber_fname` = ?,
1430 `subscriber_relationship` = ?,
1431 `subscriber_ss` = ?,
1432 `subscriber_DOB` = ?,
1433 `subscriber_street` = ?,
1434 `subscriber_postal_code` = ?,
1435 `subscriber_city` = ?,
1436 `subscriber_state` = ?,
1437 `subscriber_country` = ?,
1438 `subscriber_phone` = ?,
1439 `subscriber_employer` = ?,
1440 `subscriber_employer_city` = ?,
1441 `subscriber_employer_street` = ?,
1442 `subscriber_employer_postal_code` = ?,
1443 `subscriber_employer_state` = ?,
1444 `subscriber_employer_country` = ?,
1445 `copay` = ?,
1446 `subscriber_sex` = ?,
1447 `pid` = ?,
1448 `date` = ?,
1449 `accept_assignment` = ?,
1450 `policy_type` = ?,
1451 `date_end` = ?",
1453 $type,
1454 $provider,
1455 $policy_number,
1456 $group_number,
1457 $plan_name,
1458 $subscriber_lname,
1459 $subscriber_mname,
1460 $subscriber_fname,
1461 $subscriber_relationship,
1462 $subscriber_ss,
1463 $subscriber_DOB,
1464 $subscriber_street,
1465 $subscriber_postal_code,
1466 $subscriber_city,
1467 $subscriber_state,
1468 $subscriber_country,
1469 $subscriber_phone,
1470 $subscriber_employer,
1471 $subscriber_employer_city,
1472 $subscriber_employer_street,
1473 $subscriber_employer_postal_code,
1474 $subscriber_employer_state,
1475 $subscriber_employer_country,
1476 $copay,
1477 $subscriber_sex,
1478 $pid,
1479 $effective_date,
1480 $accept_assignment,
1481 $policy_type,
1482 $effective_date_end
1488 // This is used internally only.
1489 function updateInsuranceData($id, $new)
1491 $fields = sqlListFields("insurance_data");
1492 $use = array();
1494 foreach ($new as $key => $value) {
1495 if (in_array($key, $fields)) {
1496 $use[$key] = $value;
1500 $sqlBindArray = [];
1501 $sql = "UPDATE insurance_data SET ";
1502 foreach ($use as $key => $value) {
1503 $sql .= "`" . $key . "` = ?, ";
1504 array_push($sqlBindArray, $value);
1507 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1508 array_push($sqlBindArray, $id);
1510 sqlStatement($sql, $sqlBindArray);
1513 function newHistoryData($pid, $new = false)
1515 $socialHistoryService = new SocialHistoryService();
1517 $insertionRecord = $new;
1518 if (!is_array(($insertionRecord))) {
1519 $insertionRecord = [
1520 'pid' => $pid
1523 $socialHistoryService->create($insertionRecord);
1526 function updateHistoryData($pid, $new)
1528 $socialHistoryService = new SocialHistoryService();
1529 return $socialHistoryService->updateHistoryDataForPatientPid($pid, $new);
1532 // Returns Age
1533 // in months if < 2 years old
1534 // in years if > 2 years old
1535 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1536 // (optional) nowYMD is a date in YYYYMMDD format
1537 function getPatientAge($dobYMD, $nowYMD = null)
1539 $patientService = new PatientService();
1540 return $patientService->getPatientAge($dobYMD, $nowYMD);
1544 * Wrapper to make sure the clinical rules dates formats corresponds to the
1545 * format expected by getPatientAgeYMD
1547 * @param string $dob date of birth
1548 * @param string $target date to calculate age on
1549 * @return array containing
1550 * age - decimal age in years
1551 * age_in_months - decimal age in months
1552 * ageinYMD - formatted string #y #m #d */
1553 function parseAgeInfo($dob, $target)
1555 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1556 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1558 // Prepare target (Y-M-D H:M:S)
1559 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1561 return getPatientAgeYMD($dateDOB, $dateTarget);
1566 * @param type $dob
1567 * @param type $date
1568 * @return array containing
1569 * age - decimal age in years
1570 * age_in_months - decimal age in months
1571 * ageinYMD - formatted string #y #m #d
1573 function getPatientAgeYMD($dob, $date = null)
1575 $service = new PatientService();
1576 return $service->getPatientAgeYMD($dob, $date);
1579 // Returns Age in days
1580 // in months if < 2 years old
1581 // in years if > 2 years old
1582 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1583 // (optional) nowYMD is a date in YYYYMMDD format
1584 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1586 $age = -1;
1588 // strip any dashes from the DOB
1589 $dobYMD = preg_replace("/-/", "", $dobYMD);
1590 $dobDay = substr($dobYMD, 6, 2);
1591 $dobMonth = substr($dobYMD, 4, 2);
1592 $dobYear = substr($dobYMD, 0, 4);
1594 // set the 'now' date values
1595 if ($nowYMD == null) {
1596 $nowDay = date("d");
1597 $nowMonth = date("m");
1598 $nowYear = date("Y");
1599 } else {
1600 $nowDay = substr($nowYMD, 6, 2);
1601 $nowMonth = substr($nowYMD, 4, 2);
1602 $nowYear = substr($nowYMD, 0, 4);
1605 // do the date math
1606 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1607 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1608 $timediff = $nowtime - $dobtime;
1609 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1611 return $age;
1614 * Returns a string to be used to display a patient's age
1616 * @param type $dobYMD
1617 * @param type $asOfYMD
1618 * @return string suitable for displaying patient's age based on preferences
1620 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1622 $service = new PatientService();
1623 return $service->getPatientAgeDisplay($dobYMD, $asOfYMD);
1625 function dateToDB($date)
1627 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1628 return $date;
1632 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1633 * for the given patient on the given date.
1635 * @param int The PID of the patient.
1636 * @param string Date in yyyy-mm-dd format.
1637 * @return array Array of 0-3 insurance_data rows.
1639 function getEffectiveInsurances($patient_id, $encdate)
1641 $insarr = array();
1642 foreach (array('primary','secondary','tertiary') as $instype) {
1643 $tmp = sqlQuery(
1644 "SELECT * FROM insurance_data " .
1645 "WHERE pid = ? AND type = ? " .
1646 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1647 array($patient_id, $instype, $encdate)
1649 if (empty($tmp['provider'])) {
1650 break;
1653 $insarr[] = $tmp;
1656 return $insarr;
1660 * Get all requisition insurance companies
1665 function getAllinsurances($pid)
1667 $insarr = array();
1668 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1669 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1670 b.name, c.line1, c.line2, c.city, c.state, c.zip
1671 FROM `insurance_data` AS a
1672 RIGHT JOIN insurance_companies AS b
1673 ON a.provider = b.id
1674 RIGHT JOIN addresses AS c
1675 ON a.provider = c.foreign_id
1676 WHERE a.pid = ? ";
1677 $inco = sqlStatement($sql, array($pid));
1679 while ($icl = sqlFetchArray($inco)) {
1680 $insarr[] = $icl;
1682 return $insarr;
1686 * Get the patient's balance due. Normally this excludes amounts that are out
1687 * to insurance. If you want to include what insurance owes, set the second
1688 * parameter to true.
1690 * @param int The PID of the patient.
1691 * @param boolean Indicates if amounts owed by insurance are to be included.
1692 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1693 * @return number The balance.
1695 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1697 $balance = 0;
1698 $bindarray = array($pid);
1699 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1700 "last_level_closed, stmt_count " .
1701 "FROM form_encounter WHERE pid = ?";
1702 if ($eid) {
1703 $sqlstatement .= " AND encounter = ?";
1704 array_push($bindarray, $eid);
1706 $feres = sqlStatement($sqlstatement, $bindarray);
1707 while ($ferow = sqlFetchArray($feres)) {
1708 $encounter = $ferow['encounter'];
1709 $dos = substr($ferow['date'], 0, 10);
1710 $insarr = getEffectiveInsurances($pid, $dos);
1711 $inscount = count($insarr);
1712 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1713 // It's out to insurance so only the co-pay might be due.
1714 $brow = sqlQuery(
1715 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1716 "pid = ? AND encounter = ? AND " .
1717 "code_type = 'copay' AND activity = 1",
1718 array($pid, $encounter)
1720 $drow = sqlQuery(
1721 "SELECT SUM(pay_amount) AS payments " .
1722 "FROM ar_activity WHERE " .
1723 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1724 array($pid, $encounter)
1726 // going to comment this out for now since computing future copays doesn't
1727 // equate to cash in hand, which shows in the Billing widget in dashboard 4-23-21
1728 // $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1729 $copay = 0;
1731 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1732 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1733 $ptbal = $copay + $amt - $pay;
1734 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1735 $balance += $ptbal;
1737 } else {
1738 // Including insurance or not out to insurance, everything is due.
1739 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1740 "pid = ? AND encounter = ? AND " .
1741 "activity = 1", array($pid, $encounter));
1742 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1743 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1744 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1745 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1746 "pid = ? AND encounter = ?", array($pid, $encounter));
1747 $balance += $brow['amount'] + $srow['amount']
1748 - $drow['payments'] - $drow['adjustments'];
1752 return sprintf('%01.2f', $balance);
1755 function get_patient_balance_excluding($pid, $excluded = -1)
1757 // We join form_encounter here to make sure we only count amounts for
1758 // encounters that exist. We've had some trouble before with encounters
1759 // that were deleted but leaving line items in the database.
1760 $brow = sqlQuery(
1761 "SELECT SUM(b.fee) AS amount " .
1762 "FROM billing AS b, form_encounter AS fe WHERE " .
1763 "b.pid = ? AND b.encounter != 0 AND b.encounter != ? AND b.activity = 1 AND " .
1764 "fe.pid = b.pid AND fe.encounter = b.encounter",
1765 array($pid, $excluded)
1767 $srow = sqlQuery(
1768 "SELECT SUM(s.fee) AS amount " .
1769 "FROM drug_sales AS s, form_encounter AS fe WHERE " .
1770 "s.pid = ? AND s.encounter != 0 AND s.encounter != ? AND " .
1771 "fe.pid = s.pid AND fe.encounter = s.encounter",
1772 array($pid, $excluded)
1774 $drow = sqlQuery(
1775 "SELECT SUM(a.pay_amount) AS payments, " .
1776 "SUM(a.adj_amount) AS adjustments " .
1777 "FROM ar_activity AS a, form_encounter AS fe WHERE " .
1778 "a.deleted IS NULL AND a.pid = ? AND a.encounter != 0 AND a.encounter != ? AND " .
1779 "fe.pid = a.pid AND fe.encounter = a.encounter",
1780 array($pid, $excluded)
1782 return sprintf(
1783 '%01.2f',
1784 $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments']
1788 // Function to check if patient is deceased.
1789 // Param:
1790 // $pid - patient id
1791 // $date - date checking if deceased (will default to current date if blank)
1792 // Return:
1793 // If deceased, then will return the number of
1794 // days that patient has been deceased and the deceased date.
1795 // If not deceased, then will return false.
1796 function is_patient_deceased($pid, $date = '')
1799 // Set date to current if not set
1800 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1802 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1803 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1804 "FROM `patient_data` " .
1805 "WHERE `pid` = ? AND " .
1806 dateEmptySql('deceased_date', true, true) .
1807 "AND `deceased_date` <= ?", array($date,$pid,$date));
1809 if (empty($results)) {
1810 // Patient is alive, so return false
1811 return false;
1812 } else {
1813 // Patient is dead, so return the number of days patient has been deceased.
1814 // Don't let it be zero days or else will confuse calls to this function.
1815 if ($results['days_deceased'] === 0) {
1816 $results['days_deceased'] = 1;
1819 return $results;
1823 // This computes, sets and returns the dup score for the given patient.
1825 function updateDupScore($pid)
1827 $row = sqlQuery(
1828 "SELECT MAX(" . getDupScoreSQL() . ") AS dupscore " .
1829 "FROM patient_data AS p1, patient_data AS p2 WHERE " .
1830 "p1.pid = ? AND p2.pid < p1.pid",
1831 array($pid)
1833 $dupscore = empty($row['dupscore']) ? 0 : $row['dupscore'];
1834 sqlStatement(
1835 "UPDATE patient_data SET dupscore = ? WHERE pid = ?",
1836 array($dupscore, $pid)
1838 return $dupscore;
1841 function get_unallocated_payment_id($pid)
1843 $query = "SELECT session_id " .
1844 "FROM ar_session " .
1845 "WHERE apatient_id = ? AND " .
1846 "adjustment_code = 'pre_payment' AND closed = 0 ORDER BY check_date ASC LIMIT 1";
1847 $res = sqlQuery($query, array($pid));
1848 if ($res['session_id']) {
1849 return $res['session_id'];
1850 } else {
1851 return '';