add insurance effective date end (#6077)
[openemr.git] / library / patient.inc.php
blob1e70fc28888cb459fbf796564f6ac210311d1322
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 // To prevent sql injection on this function, if a variable is used for $given parameter, then
406 // it needs to be escaped via whitelisting prior to using this function.
407 function getEmployerData($pid, $given = "*")
409 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
410 return sqlQuery($sql, array($pid));
413 // Generate a consistent header and footer, used for printed patient reports
414 function genPatientHeaderFooter($pid, $DOS = null)
416 $patient_dob = getPatientData($pid, "DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS");
417 $patient_name = getPatientName($pid);
419 // Header
420 $s = '<htmlpageheader name="PageHeader1"><div style="text-align: right; font-weight: bold;">';
421 $s .= text($patient_name) . '&emsp;DOB: ' . text($patient_dob['DOB_TS']);
422 if ($DOS) {
423 $s .= '&emsp;DOS: ' . text($DOS);
425 $s .= '</div></htmlpageheader>';
427 // Footer
428 $s .= '<htmlpagefooter name="PageFooter1"><div style="text-align: right; font-weight: bold;">';
429 $s .= '<div style="float: right; width:33%; text-align: left;">' . oeFormatDateTime(date("Y-m-d H:i:s")) . '</div>';
430 $s .= '<div style="float: right; width:33%; text-align: center;">{PAGENO}/{nbpg}</div>';
431 $s .= '<div style="float: right; width:33%; text-align: right;">' . text($patient_name) . '</div>';
432 $s .= '</div></htmlpagefooter>';
434 // Set the header and footer in the current document
435 $s .= '<sethtmlpageheader name="PageHeader1" page="ALL" value="ON" show-this-page="1" />';
436 $s .= '<sethtmlpagefooter name="PageFooter1" page="ALL" value="ON" />';
438 return $s;
441 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
443 // When the limit is exceeded, find out what the unlimited count would be.
444 $GLOBALS['PATIENT_INC_COUNT'] = $count;
445 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
446 if ($limit != "all") {
447 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
448 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
453 * Allow the last name to be followed by a comma and some part of a first name(can
454 * also place middle name after the first name with a space separating them)
455 * Allows comma alone followed by some part of a first name(can also place middle name
456 * after the first name with a space separating them).
457 * Allows comma alone preceded by some part of a last name.
458 * If no comma or space, then will search both last name and first name.
459 * If the first letter of either name is capital, searches for name starting
460 * with given substring (the expected behavior). If it is lower case, it
461 * searches for the substring anywhere in the name. This applies to either
462 * last name, first name, and middle name.
463 * Also allows first name followed by middle and/or last name when separated by spaces.
464 * @param string $term
465 * @param string $given
466 * @param string $orderby
467 * @param string $limit
468 * @param string $start
469 * @return array
471 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
472 // it needs to be escaped via whitelisting prior to using this function.
473 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")
475 $names = getPatientNameSplit($term);
477 foreach ($names as $key => $val) {
478 if (!empty($val)) {
479 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
480 $names[$key] = '%' . $val . '%';
481 } else {
482 $names[$key] = $val . '%';
487 // Debugging section below
488 //if(array_key_exists('first',$names)) {
489 // error_log("first name search term :".$names['first']);
491 //if(array_key_exists('middle',$names)) {
492 // error_log("middle name search term :".$names['middle']);
494 //if(array_key_exists('last',$names)) {
495 // error_log("last name search term :".$names['last']);
497 // Debugging section above
499 $sqlBindArray = array();
500 if (array_key_exists('last', $names) && $names['last'] == '') {
501 // Do not search last name
502 $where = "fname LIKE ? ";
503 array_push($sqlBindArray, $names['first']);
504 if ($names['middle'] != '') {
505 $where .= "AND mname LIKE ? ";
506 array_push($sqlBindArray, $names['middle']);
508 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
509 // Do not search first name or middle name
510 $where = "lname LIKE ? ";
511 array_push($sqlBindArray, $names['last']);
512 } elseif (empty($names['first']) && !empty($names['last'])) {
513 // Search both first name and last name with same term
514 $names['first'] = $names['last'];
515 $where = "lname LIKE ? OR fname LIKE ? ";
516 array_push($sqlBindArray, $names['last'], $names['first']);
517 } elseif ($names['middle'] != '') {
518 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
519 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
520 } else {
521 $where = "lname LIKE ? AND fname LIKE ? ";
522 array_push($sqlBindArray, $names['last'], $names['first']);
525 if (!empty($GLOBALS['pt_restrict_field'])) {
526 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
527 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
528 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
529 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
530 array_push($sqlBindArray, $_SESSION["authUser"]);
534 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
535 if ($limit != "all") {
536 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
539 $rez = sqlStatement($sql, $sqlBindArray);
541 $returnval = array();
542 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
543 $returnval[$iter] = $row;
546 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
547 return $returnval;
550 * Accept a string used by a search function expected to find a patient name,
551 * then split up the string if a comma or space exists. Return an array having
552 * from 1 to 3 elements, named first, middle, and last.
553 * See above getPatientLnames() function for details on how the splitting occurs.
554 * @param string $term
555 * @return array
557 function getPatientNameSplit($term)
559 $term = trim($term);
560 if (strpos($term, ',') !== false) {
561 $names = explode(',', $term);
562 $n['last'] = $names[0];
563 if (strpos(trim($names[1]), ' ') !== false) {
564 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
565 } else {
566 $n['first'] = $names[1];
568 } elseif (strpos($term, ' ') !== false) {
569 $names = explode(' ', $term);
570 if (count($names) == 1) {
571 $n['last'] = $names[0];
572 } elseif (count($names) == 3) {
573 $n['first'] = $names[0];
574 $n['middle'] = $names[1];
575 $n['last'] = $names[2];
576 } else {
577 // This will handle first and last name or first followed by
578 // multiple names only using just the last of the names in the list.
579 $n['first'] = $names[0];
580 $n['last'] = end($names);
582 } else {
583 $n['last'] = $term;
584 if (empty($n['last'])) {
585 $n['last'] = '%';
589 // Trim whitespace off the names before returning
590 foreach ($n as $key => $val) {
591 $n[$key] = trim($val);
594 return $n; // associative array containing names
597 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
598 // it needs to be escaped via whitelisting prior to using this function.
599 function 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")
602 $sqlBindArray = array();
603 $where = "pubpid LIKE ? ";
604 array_push($sqlBindArray, $pid . "%");
605 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
606 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
607 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
608 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
609 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
610 array_push($sqlBindArray, $_SESSION["authUser"]);
614 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
615 if ($limit != "all") {
616 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
619 $rez = sqlStatement($sql, $sqlBindArray);
620 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
621 $returnval[$iter] = $row;
624 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
625 return $returnval;
628 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
629 // it needs to be escaped via whitelisting prior to using this function.
630 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")
632 $layoutCols = sqlStatement(
633 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
634 array('em\_%')
637 $sqlBindArray = array();
638 $where = "";
639 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
640 if ($iter > 0) {
641 $where .= " or ";
644 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
645 array_push($sqlBindArray, "%" . $searchTerm . "%");
648 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
649 if ($limit != "all") {
650 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
653 $rez = sqlStatement($sql, $sqlBindArray);
654 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
655 $returnval[$iter] = $row;
658 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
659 return $returnval;
662 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
663 // it needs to be escaped via whitelisting prior to using this function.
664 function getByPatientDemographicsFilter(
665 $searchFields,
666 $searchTerm = "%",
667 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
668 $orderby = "lname ASC, fname ASC",
669 $limit = "all",
670 $start = "0",
671 $search_service_code = ''
674 $layoutCols = explode('~', $searchFields);
675 $sqlBindArray = array();
676 $where = "";
677 $i = 0;
678 foreach ($layoutCols as $val) {
679 if (empty($val)) {
680 continue;
683 if ($i > 0) {
684 $where .= " or ";
687 if ($val == 'pid') {
688 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " = ? ";
689 array_push($sqlBindArray, $searchTerm);
690 } else {
691 $where .= " " . escape_sql_column_name($val, ['patient_data']) . " like ? ";
692 array_push($sqlBindArray, $searchTerm . "%");
695 $i++;
698 // If no search terms, ensure valid syntax.
699 if ($i == 0) {
700 $where = "1 = 1";
703 // If a non-empty service code was given, then restrict to patients who
704 // have been provided that service. Since the code is used in a LIKE
705 // clause, % and _ wildcards are supported.
706 if ($search_service_code) {
707 $where = "( $where ) AND " .
708 "( SELECT COUNT(*) FROM billing AS b WHERE " .
709 "b.pid = patient_data.pid AND " .
710 "b.activity = 1 AND " .
711 "b.code_type != 'COPAY' AND " .
712 "b.code LIKE ? " .
713 ") > 0";
714 array_push($sqlBindArray, $search_service_code);
717 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
718 if ($limit != "all") {
719 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
722 $rez = sqlStatement($sql, $sqlBindArray);
723 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
724 $returnval[$iter] = $row;
727 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
728 return $returnval;
731 // return a collection of Patient PIDs
732 // new arg style by JRM March 2008
733 // 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")
734 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
735 // it needs to be escaped via whitelisting prior to using this function.
736 function getPatientPID($args)
738 $pid = "%";
739 $given = "pid, id, lname, fname, mname, suffix, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
740 $orderby = "lname ASC, fname ASC";
741 $limit = "all";
742 $start = "0";
744 // alter default values if defined in the passed in args
745 if (isset($args['pid'])) {
746 $pid = $args['pid'];
749 if (isset($args['given'])) {
750 $given = $args['given'];
753 if (isset($args['orderby'])) {
754 $orderby = $args['orderby'];
757 if (isset($args['limit'])) {
758 $limit = $args['limit'];
761 if (isset($args['start'])) {
762 $start = $args['start'];
765 $command = "=";
766 if ($pid == -1) {
767 $pid = "%";
768 } elseif (empty($pid)) {
769 $pid = "NULL";
772 if (strstr($pid, "%")) {
773 $command = "like";
776 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
777 if ($limit != "all") {
778 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
781 $rez = sqlStatement($sql);
782 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
783 $returnval[$iter] = $row;
786 return $returnval;
789 /* return a patient's name in the format LAST [SUFFIX], FIRST [MIDDLE] */
790 function getPatientName($pid)
792 if (empty($pid)) {
793 return "";
796 $patientData = getPatientPID(array("pid" => $pid));
797 if (empty($patientData[0]['lname'])) {
798 return "";
801 $patientName = $patientData[0]['lname'];
802 $patientName .= $patientData[0]['suffix'] ? " " . $patientData[0]['suffix'] . ", " : ", ";
803 $patientName .= $patientData[0]['fname'];
804 $patientName .= empty($patientData[0]['mname']) ? "" : " " . $patientData[0]['mname'];
805 return $patientName;
809 * Get a patient's first name, middle name, last name and suffix if applicable.
811 * Returns a properly formatted, complete name when applicable. Example name
812 * would be "John B Doe Jr". No additional punctuation is added. Spaces are
813 * correctly omitted if the middle name of suffix does not apply.
815 * @var $pid int The Patient ID
816 * @returns string The Full Name
818 function getPatientFullNameAsString($pid): string
820 if (empty($pid)) {
821 return '';
823 $ptData = getPatientPID(["pid" => $pid]);
824 $pt = $ptData[0];
826 if (empty($pt['lname'])) {
827 return "";
830 $name = $pt['fname'];
832 if ($pt['mname']) {
833 $name .= " {$pt['mname']}";
836 $name .= " {$pt['lname']}";
838 if ($pt['suffix']) {
839 $name .= " {$pt['suffix']}";
842 return $name;
845 /* return a patient's name in the format FIRST LAST */
846 function getPatientNameFirstLast($pid)
848 if (empty($pid)) {
849 return "";
852 $patientData = getPatientPID(array("pid" => $pid));
853 if (empty($patientData[0]['lname'])) {
854 return "";
857 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
858 return $patientName;
861 /* find patient data by DOB */
862 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
863 // it needs to be escaped via whitelisting prior to using this function.
864 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
866 $sqlBindArray = array();
867 $where = "DOB like ? ";
868 array_push($sqlBindArray, $DOB . "%");
869 if (!empty($GLOBALS['pt_restrict_field'])) {
870 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
871 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
872 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
873 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
874 array_push($sqlBindArray, $_SESSION["authUser"]);
878 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
880 if ($limit != "all") {
881 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
884 $rez = sqlStatement($sql, $sqlBindArray);
885 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
886 $returnval[$iter] = $row;
889 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
890 return $returnval;
893 /* find patient data by SSN */
894 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
895 // it needs to be escaped via whitelisting prior to using this function.
896 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
898 $sqlBindArray = array();
899 $where = "ss LIKE ?";
900 array_push($sqlBindArray, $ss . "%");
901 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
902 if ($limit != "all") {
903 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
906 $rez = sqlStatement($sql, $sqlBindArray);
907 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
908 $returnval[$iter] = $row;
911 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
912 return $returnval;
915 //(CHEMED) Search by phone number
916 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
917 // it needs to be escaped via whitelisting prior to using this function.
918 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
920 $phone = preg_replace("/[[:punct:]]/", "", $phone);
921 $sqlBindArray = array();
922 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
923 array_push($sqlBindArray, $phone);
924 $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 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
935 return $returnval;
938 //----------------------input functions
939 function newPatientData(
940 $db_id = "",
941 $title = "",
942 $fname = "",
943 $lname = "",
944 $mname = "",
945 $sex = "",
946 $DOB = "",
947 $street = "",
948 $postal_code = "",
949 $city = "",
950 $state = "",
951 $country_code = "",
952 $ss = "",
953 $occupation = "",
954 $phone_home = "",
955 $phone_biz = "",
956 $phone_contact = "",
957 $status = "",
958 $contact_relationship = "",
959 $referrer = "",
960 $referrerID = "",
961 $email = "",
962 $language = "",
963 $ethnoracial = "",
964 $interpretter = "",
965 $migrantseasonal = "",
966 $family_size = "",
967 $monthly_income = "",
968 $homeless = "",
969 $financial_review = "",
970 $pubpid = "",
971 $pid = "MAX(pid)+1",
972 $providerID = "",
973 $genericname1 = "",
974 $genericval1 = "",
975 $genericname2 = "",
976 $genericval2 = "",
977 $billing_note = "",
978 $phone_cell = "",
979 $hipaa_mail = "",
980 $hipaa_voice = "",
981 $squad = 0,
982 $pharmacy_id = 0,
983 $drivers_license = "",
984 $hipaa_notice = "",
985 $hipaa_message = "",
986 $regdate = ""
989 $fitness = 0;
990 $referral_source = '';
991 if ($pid) {
992 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
993 // Check for brain damage:
994 if ($db_id != $rez['id']) {
995 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
996 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
997 die($errmsg);
1000 $fitness = $rez['fitness'];
1001 $referral_source = $rez['referral_source'];
1004 // Get the default price level.
1005 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
1006 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
1007 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
1009 $query = ("replace into patient_data set
1010 id='" . add_escape_custom($db_id) . "',
1011 title='" . add_escape_custom($title) . "',
1012 fname='" . add_escape_custom($fname) . "',
1013 lname='" . add_escape_custom($lname) . "',
1014 mname='" . add_escape_custom($mname) . "',
1015 sex='" . add_escape_custom($sex) . "',
1016 DOB='" . add_escape_custom($DOB) . "',
1017 street='" . add_escape_custom($street) . "',
1018 postal_code='" . add_escape_custom($postal_code) . "',
1019 city='" . add_escape_custom($city) . "',
1020 state='" . add_escape_custom($state) . "',
1021 country_code='" . add_escape_custom($country_code) . "',
1022 drivers_license='" . add_escape_custom($drivers_license) . "',
1023 ss='" . add_escape_custom($ss) . "',
1024 occupation='" . add_escape_custom($occupation) . "',
1025 phone_home='" . add_escape_custom($phone_home) . "',
1026 phone_biz='" . add_escape_custom($phone_biz) . "',
1027 phone_contact='" . add_escape_custom($phone_contact) . "',
1028 status='" . add_escape_custom($status) . "',
1029 contact_relationship='" . add_escape_custom($contact_relationship) . "',
1030 referrer='" . add_escape_custom($referrer) . "',
1031 referrerID='" . add_escape_custom($referrerID) . "',
1032 email='" . add_escape_custom($email) . "',
1033 language='" . add_escape_custom($language) . "',
1034 ethnoracial='" . add_escape_custom($ethnoracial) . "',
1035 interpretter='" . add_escape_custom($interpretter) . "',
1036 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1037 family_size='" . add_escape_custom($family_size) . "',
1038 monthly_income='" . add_escape_custom($monthly_income) . "',
1039 homeless='" . add_escape_custom($homeless) . "',
1040 financial_review='" . add_escape_custom($financial_review) . "',
1041 pubpid='" . add_escape_custom($pubpid) . "',
1042 pid= '" . add_escape_custom($pid) . "',
1043 providerID = '" . add_escape_custom($providerID) . "',
1044 genericname1 = '" . add_escape_custom($genericname1) . "',
1045 genericval1 = '" . add_escape_custom($genericval1) . "',
1046 genericname2 = '" . add_escape_custom($genericname2) . "',
1047 genericval2 = '" . add_escape_custom($genericval2) . "',
1048 billing_note= '" . add_escape_custom($billing_note) . "',
1049 phone_cell = '" . add_escape_custom($phone_cell) . "',
1050 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1051 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1052 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1053 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1054 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1055 squad = '" . add_escape_custom($squad) . "',
1056 fitness='" . add_escape_custom($fitness) . "',
1057 referral_source='" . add_escape_custom($referral_source) . "',
1058 regdate='" . add_escape_custom($regdate) . "',
1059 pricelevel='" . add_escape_custom($pricelevel) . "',
1060 date=NOW()");
1062 $id = sqlInsert($query);
1064 if (!$db_id) {
1065 // find the last inserted id for new patient case
1066 $db_id = $id;
1069 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
1071 // set uuid if not set yet (if this was an insert and not an update)
1072 if (empty($foo['uuid'])) {
1073 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
1074 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
1077 return $foo['pid'];
1080 // Supported input date formats are:
1081 // mm/dd/yyyy
1082 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1083 // yyyy/mm/dd
1084 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1086 function fixDate($date, $default = "0000-00-00")
1088 $fixed_date = $default;
1089 $date = trim($date);
1090 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1091 $dmy = preg_split("'[/.-]'", $date);
1092 if ($dmy[0] > 99) {
1093 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1094 } else {
1095 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1096 if ($dmy[2] < 1000) {
1097 $dmy[2] += 1900;
1100 if ($dmy[2] < 1910) {
1101 $dmy[2] += 100;
1104 // Determine if MDY date format is used, preferring Date Display Format from
1105 // global settings if it's not YMD, otherwise guessing from country code.
1106 $using_mdy = empty($GLOBALS['date_display_format']) ?
1107 ($GLOBALS['phone_country_code'] == 1) : ($GLOBALS['date_display_format'] == 1);
1108 if ($using_mdy) {
1109 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1110 } else {
1111 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1116 return $fixed_date;
1119 function pdValueOrNull($key, $value)
1121 if (
1122 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1123 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1124 (empty($value) || $value == '0000-00-00')
1126 return "NULL";
1127 } else {
1128 return "'" . add_escape_custom($value) . "'";
1133 * Create or update patient data from an array.
1135 * This is a wrapper function for the PatientService which is now the single point
1136 * of patient creation and update.
1138 * If successful, returns the pid of the patient
1140 * @param $pid
1141 * @param $new
1142 * @param false $create
1143 * @return mixed
1145 function updatePatientData($pid, $new, $create = false)
1147 // Create instance of patient service
1148 $patientService = new PatientService();
1149 if (
1150 $create === true ||
1151 $pid === null
1153 $result = $patientService->databaseInsert($new);
1154 updateDupScore($result['pid']);
1155 } else {
1156 $new['pid'] = $pid;
1157 $result = $patientService->databaseUpdate($new);
1160 // From the returned patient data array
1161 // retrieve the data and return the pid
1162 $pid = $result['pid'];
1164 return $pid;
1167 function newEmployerData(
1168 $pid,
1169 $name = "",
1170 $street = "",
1171 $postal_code = "",
1172 $city = "",
1173 $state = "",
1174 $country = ""
1177 return sqlInsert("insert into employer_data set
1178 name='" . add_escape_custom($name) . "',
1179 street='" . add_escape_custom($street) . "',
1180 postal_code='" . add_escape_custom($postal_code) . "',
1181 city='" . add_escape_custom($city) . "',
1182 state='" . add_escape_custom($state) . "',
1183 country='" . add_escape_custom($country) . "',
1184 pid='" . add_escape_custom($pid) . "',
1185 date=NOW()
1189 // Create or update employer data from an array.
1191 function updateEmployerData($pid, $new, $create = false)
1193 // used to hard code colnames array('name','street','city','state','postal_code','country');
1194 // but now adapted for layout based
1195 $colnames = array();
1196 foreach ($new as $key => $value) {
1197 $colnames[] = $key;
1200 if ($create) {
1201 $set = "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1202 foreach ($colnames as $key) {
1203 $value = isset($new[$key]) ? $new[$key] : '';
1204 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1207 return sqlInsert("INSERT INTO employer_data SET $set");
1208 } else {
1209 $set = '';
1210 $old = getEmployerData($pid);
1211 $modified = false;
1212 foreach ($colnames as $key) {
1213 $value = empty($old[$key]) ? '' : $old[$key];
1214 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1215 $value = $new[$key];
1216 $modified = true;
1219 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1222 if ($modified) {
1223 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1224 return sqlInsert("INSERT INTO employer_data SET $set");
1227 return ($old['id'] ?? '');
1231 // This updates or adds the given insurance data info, while retaining any
1232 // previously added insurance_data rows that should be preserved.
1233 // This does not directly support the maintenance of non-current insurance.
1235 function newInsuranceData(
1236 $pid,
1237 $type = "",
1238 $provider = "",
1239 $policy_number = "",
1240 $group_number = "",
1241 $plan_name = "",
1242 $subscriber_lname = "",
1243 $subscriber_mname = "",
1244 $subscriber_fname = "",
1245 $subscriber_relationship = "",
1246 $subscriber_ss = "",
1247 $subscriber_DOB = null,
1248 $subscriber_street = "",
1249 $subscriber_postal_code = "",
1250 $subscriber_city = "",
1251 $subscriber_state = "",
1252 $subscriber_country = "",
1253 $subscriber_phone = "",
1254 $subscriber_employer = "",
1255 $subscriber_employer_street = "",
1256 $subscriber_employer_city = "",
1257 $subscriber_employer_postal_code = "",
1258 $subscriber_employer_state = "",
1259 $subscriber_employer_country = "",
1260 $copay = "",
1261 $subscriber_sex = "",
1262 $effective_date = null,
1263 $accept_assignment = "TRUE",
1264 $policy_type = "",
1265 $effective_date_end = null
1268 if (strlen($type) <= 0) {
1269 return false;
1272 if (is_null($accept_assignment)) {
1273 $accept_assignment = "TRUE";
1275 if (is_null($policy_type)) {
1276 $policy_type = "";
1279 // If empty dates were passed, then null.
1280 if (empty($effective_date)) {
1281 $effective_date = null;
1283 if (empty($subscriber_DOB)) {
1284 $subscriber_DOB = null;
1286 if (empty($effective_date_end)) {
1287 $effective_date_end = null;
1290 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1291 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1292 $idrow = sqlFetchArray($idres);
1294 // Replace the most recent entry in any of the following cases:
1295 // * Its effective date is >= this effective date.
1296 // * It is the first entry and it has no (insurance) provider.
1297 // * There is no encounter that is earlier than the new effective date but
1298 // on or after the old effective date.
1299 // Otherwise insert a new entry.
1301 $replace = false;
1302 if ($idrow) {
1303 // convert date from null to "0000-00-00" for below strcmp and query
1304 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1305 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1306 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1307 $replace = true;
1308 } else {
1309 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1310 $replace = true;
1311 } else {
1312 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1313 "WHERE pid = ? AND date < ? AND " .
1314 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1315 if ($ferow['count'] == 0) {
1316 $replace = true;
1322 if ($replace) {
1323 // TBD: This is a bit dangerous in that a typo in entering the effective
1324 // date can wipe out previous insurance history. So we want some data
1325 // entry validation somewhere.
1326 if ($effective_date === null) {
1327 sqlStatement("DELETE FROM insurance_data WHERE " .
1328 "pid = ? AND type = ? AND " .
1329 "id != ?", array($pid, $type, $idrow['id']));
1330 } else {
1331 sqlStatement("DELETE FROM insurance_data WHERE " .
1332 "pid = ? AND type = ? AND date >= ? AND " .
1333 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1336 $data = array();
1337 $data['type'] = $type;
1338 $data['provider'] = $provider;
1339 $data['policy_number'] = $policy_number;
1340 $data['group_number'] = $group_number;
1341 $data['plan_name'] = $plan_name;
1342 $data['subscriber_lname'] = $subscriber_lname;
1343 $data['subscriber_mname'] = $subscriber_mname;
1344 $data['subscriber_fname'] = $subscriber_fname;
1345 $data['subscriber_relationship'] = $subscriber_relationship;
1346 $data['subscriber_ss'] = $subscriber_ss;
1347 $data['subscriber_DOB'] = $subscriber_DOB;
1348 $data['subscriber_street'] = $subscriber_street;
1349 $data['subscriber_postal_code'] = $subscriber_postal_code;
1350 $data['subscriber_city'] = $subscriber_city;
1351 $data['subscriber_state'] = $subscriber_state;
1352 $data['subscriber_country'] = $subscriber_country;
1353 $data['subscriber_phone'] = $subscriber_phone;
1354 $data['subscriber_employer'] = $subscriber_employer;
1355 $data['subscriber_employer_city'] = $subscriber_employer_city;
1356 $data['subscriber_employer_street'] = $subscriber_employer_street;
1357 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1358 $data['subscriber_employer_state'] = $subscriber_employer_state;
1359 $data['subscriber_employer_country'] = $subscriber_employer_country;
1360 $data['copay'] = $copay;
1361 $data['subscriber_sex'] = $subscriber_sex;
1362 $data['pid'] = $pid;
1363 $data['date'] = $effective_date;
1364 $data['accept_assignment'] = $accept_assignment;
1365 $data['policy_type'] = $policy_type;
1366 $data['date_end'] = $effective_date_end;
1367 updateInsuranceData($idrow['id'], $data);
1368 return $idrow['id'];
1369 } else {
1370 return sqlInsert(
1371 "INSERT INTO `insurance_data` SET `type` = ?,
1372 `provider` = ?,
1373 `policy_number` = ?,
1374 `group_number` = ?,
1375 `plan_name` = ?,
1376 `subscriber_lname` = ?,
1377 `subscriber_mname` = ?,
1378 `subscriber_fname` = ?,
1379 `subscriber_relationship` = ?,
1380 `subscriber_ss` = ?,
1381 `subscriber_DOB` = ?,
1382 `subscriber_street` = ?,
1383 `subscriber_postal_code` = ?,
1384 `subscriber_city` = ?,
1385 `subscriber_state` = ?,
1386 `subscriber_country` = ?,
1387 `subscriber_phone` = ?,
1388 `subscriber_employer` = ?,
1389 `subscriber_employer_city` = ?,
1390 `subscriber_employer_street` = ?,
1391 `subscriber_employer_postal_code` = ?,
1392 `subscriber_employer_state` = ?,
1393 `subscriber_employer_country` = ?,
1394 `copay` = ?,
1395 `subscriber_sex` = ?,
1396 `pid` = ?,
1397 `date` = ?,
1398 `accept_assignment` = ?,
1399 `policy_type` = ?,
1400 `date_end` = ?",
1402 $type,
1403 $provider,
1404 $policy_number,
1405 $group_number,
1406 $plan_name,
1407 $subscriber_lname,
1408 $subscriber_mname,
1409 $subscriber_fname,
1410 $subscriber_relationship,
1411 $subscriber_ss,
1412 $subscriber_DOB,
1413 $subscriber_street,
1414 $subscriber_postal_code,
1415 $subscriber_city,
1416 $subscriber_state,
1417 $subscriber_country,
1418 $subscriber_phone,
1419 $subscriber_employer,
1420 $subscriber_employer_city,
1421 $subscriber_employer_street,
1422 $subscriber_employer_postal_code,
1423 $subscriber_employer_state,
1424 $subscriber_employer_country,
1425 $copay,
1426 $subscriber_sex,
1427 $pid,
1428 $effective_date,
1429 $accept_assignment,
1430 $policy_type,
1431 $effective_date_end
1437 // This is used internally only.
1438 function updateInsuranceData($id, $new)
1440 $fields = sqlListFields("insurance_data");
1441 $use = array();
1443 foreach ($new as $key => $value) {
1444 if (in_array($key, $fields)) {
1445 $use[$key] = $value;
1449 $sqlBindArray = [];
1450 $sql = "UPDATE insurance_data SET ";
1451 foreach ($use as $key => $value) {
1452 $sql .= "`" . $key . "` = ?, ";
1453 array_push($sqlBindArray, $value);
1456 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1457 array_push($sqlBindArray, $id);
1459 sqlStatement($sql, $sqlBindArray);
1462 function newHistoryData($pid, $new = false)
1464 $socialHistoryService = new SocialHistoryService();
1466 $insertionRecord = $new;
1467 if (!is_array(($insertionRecord))) {
1468 $insertionRecord = [
1469 'pid' => $pid
1472 $socialHistoryService->create($insertionRecord);
1475 function updateHistoryData($pid, $new)
1477 $socialHistoryService = new SocialHistoryService();
1478 return $socialHistoryService->updateHistoryDataForPatientPid($pid, $new);
1481 // Returns Age
1482 // in months if < 2 years old
1483 // in years if > 2 years old
1484 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1485 // (optional) nowYMD is a date in YYYYMMDD format
1486 function getPatientAge($dobYMD, $nowYMD = null)
1488 $patientService = new PatientService();
1489 return $patientService->getPatientAge($dobYMD, $nowYMD);
1493 * Wrapper to make sure the clinical rules dates formats corresponds to the
1494 * format expected by getPatientAgeYMD
1496 * @param string $dob date of birth
1497 * @param string $target date to calculate age on
1498 * @return array containing
1499 * age - decimal age in years
1500 * age_in_months - decimal age in months
1501 * ageinYMD - formatted string #y #m #d */
1502 function parseAgeInfo($dob, $target)
1504 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1505 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1507 // Prepare target (Y-M-D H:M:S)
1508 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1510 return getPatientAgeYMD($dateDOB, $dateTarget);
1515 * @param type $dob
1516 * @param type $date
1517 * @return array containing
1518 * age - decimal age in years
1519 * age_in_months - decimal age in months
1520 * ageinYMD - formatted string #y #m #d
1522 function getPatientAgeYMD($dob, $date = null)
1524 $service = new PatientService();
1525 return $service->getPatientAgeYMD($dob, $date);
1528 // Returns Age in days
1529 // in months if < 2 years old
1530 // in years if > 2 years old
1531 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1532 // (optional) nowYMD is a date in YYYYMMDD format
1533 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1535 $age = -1;
1537 // strip any dashes from the DOB
1538 $dobYMD = preg_replace("/-/", "", $dobYMD);
1539 $dobDay = substr($dobYMD, 6, 2);
1540 $dobMonth = substr($dobYMD, 4, 2);
1541 $dobYear = substr($dobYMD, 0, 4);
1543 // set the 'now' date values
1544 if ($nowYMD == null) {
1545 $nowDay = date("d");
1546 $nowMonth = date("m");
1547 $nowYear = date("Y");
1548 } else {
1549 $nowDay = substr($nowYMD, 6, 2);
1550 $nowMonth = substr($nowYMD, 4, 2);
1551 $nowYear = substr($nowYMD, 0, 4);
1554 // do the date math
1555 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1556 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1557 $timediff = $nowtime - $dobtime;
1558 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1560 return $age;
1563 * Returns a string to be used to display a patient's age
1565 * @param type $dobYMD
1566 * @param type $asOfYMD
1567 * @return string suitable for displaying patient's age based on preferences
1569 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1571 $service = new PatientService();
1572 return $service->getPatientAgeDisplay($dobYMD, $asOfYMD);
1574 function dateToDB($date)
1576 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1577 return $date;
1581 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1582 * for the given patient on the given date.
1584 * @param int The PID of the patient.
1585 * @param string Date in yyyy-mm-dd format.
1586 * @return array Array of 0-3 insurance_data rows.
1588 function getEffectiveInsurances($patient_id, $encdate)
1590 $insarr = array();
1591 foreach (array('primary','secondary','tertiary') as $instype) {
1592 $tmp = sqlQuery(
1593 "SELECT * FROM insurance_data " .
1594 "WHERE pid = ? AND type = ? " .
1595 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1596 array($patient_id, $instype, $encdate)
1598 if (empty($tmp['provider'])) {
1599 break;
1602 $insarr[] = $tmp;
1605 return $insarr;
1609 * Get all requisition insurance companies
1614 function getAllinsurances($pid)
1616 $insarr = array();
1617 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1618 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1619 b.name, c.line1, c.line2, c.city, c.state, c.zip
1620 FROM `insurance_data` AS a
1621 RIGHT JOIN insurance_companies AS b
1622 ON a.provider = b.id
1623 RIGHT JOIN addresses AS c
1624 ON a.provider = c.foreign_id
1625 WHERE a.pid = ? ";
1626 $inco = sqlStatement($sql, array($pid));
1628 while ($icl = sqlFetchArray($inco)) {
1629 $insarr[] = $icl;
1631 return $insarr;
1635 * Get the patient's balance due. Normally this excludes amounts that are out
1636 * to insurance. If you want to include what insurance owes, set the second
1637 * parameter to true.
1639 * @param int The PID of the patient.
1640 * @param boolean Indicates if amounts owed by insurance are to be included.
1641 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1642 * @return number The balance.
1644 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1646 $balance = 0;
1647 $bindarray = array($pid);
1648 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1649 "last_level_closed, stmt_count " .
1650 "FROM form_encounter WHERE pid = ?";
1651 if ($eid) {
1652 $sqlstatement .= " AND encounter = ?";
1653 array_push($bindarray, $eid);
1655 $feres = sqlStatement($sqlstatement, $bindarray);
1656 while ($ferow = sqlFetchArray($feres)) {
1657 $encounter = $ferow['encounter'];
1658 $dos = substr($ferow['date'], 0, 10);
1659 $insarr = getEffectiveInsurances($pid, $dos);
1660 $inscount = count($insarr);
1661 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1662 // It's out to insurance so only the co-pay might be due.
1663 $brow = sqlQuery(
1664 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1665 "pid = ? AND encounter = ? AND " .
1666 "code_type = 'copay' AND activity = 1",
1667 array($pid, $encounter)
1669 $drow = sqlQuery(
1670 "SELECT SUM(pay_amount) AS payments " .
1671 "FROM ar_activity WHERE " .
1672 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1673 array($pid, $encounter)
1675 // going to comment this out for now since computing future copays doesn't
1676 // equate to cash in hand, which shows in the Billing widget in dashboard 4-23-21
1677 // $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1678 $copay = 0;
1680 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1681 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1682 $ptbal = $copay + $amt - $pay;
1683 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1684 $balance += $ptbal;
1686 } else {
1687 // Including insurance or not out to insurance, everything is due.
1688 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1689 "pid = ? AND encounter = ? AND " .
1690 "activity = 1", array($pid, $encounter));
1691 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1692 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1693 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1694 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1695 "pid = ? AND encounter = ?", array($pid, $encounter));
1696 $balance += $brow['amount'] + $srow['amount']
1697 - $drow['payments'] - $drow['adjustments'];
1701 return sprintf('%01.2f', $balance);
1704 function get_patient_balance_excluding($pid, $excluded = -1)
1706 // We join form_encounter here to make sure we only count amounts for
1707 // encounters that exist. We've had some trouble before with encounters
1708 // that were deleted but leaving line items in the database.
1709 $brow = sqlQuery(
1710 "SELECT SUM(b.fee) AS amount " .
1711 "FROM billing AS b, form_encounter AS fe WHERE " .
1712 "b.pid = ? AND b.encounter != 0 AND b.encounter != ? AND b.activity = 1 AND " .
1713 "fe.pid = b.pid AND fe.encounter = b.encounter",
1714 array($pid, $excluded)
1716 $srow = sqlQuery(
1717 "SELECT SUM(s.fee) AS amount " .
1718 "FROM drug_sales AS s, form_encounter AS fe WHERE " .
1719 "s.pid = ? AND s.encounter != 0 AND s.encounter != ? AND " .
1720 "fe.pid = s.pid AND fe.encounter = s.encounter",
1721 array($pid, $excluded)
1723 $drow = sqlQuery(
1724 "SELECT SUM(a.pay_amount) AS payments, " .
1725 "SUM(a.adj_amount) AS adjustments " .
1726 "FROM ar_activity AS a, form_encounter AS fe WHERE " .
1727 "a.deleted IS NULL AND a.pid = ? AND a.encounter != 0 AND a.encounter != ? AND " .
1728 "fe.pid = a.pid AND fe.encounter = a.encounter",
1729 array($pid, $excluded)
1731 return sprintf(
1732 '%01.2f',
1733 $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments']
1737 // Function to check if patient is deceased.
1738 // Param:
1739 // $pid - patient id
1740 // $date - date checking if deceased (will default to current date if blank)
1741 // Return:
1742 // If deceased, then will return the number of
1743 // days that patient has been deceased and the deceased date.
1744 // If not deceased, then will return false.
1745 function is_patient_deceased($pid, $date = '')
1748 // Set date to current if not set
1749 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1751 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1752 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1753 "FROM `patient_data` " .
1754 "WHERE `pid` = ? AND " .
1755 dateEmptySql('deceased_date', true, true) .
1756 "AND `deceased_date` <= ?", array($date,$pid,$date));
1758 if (empty($results)) {
1759 // Patient is alive, so return false
1760 return false;
1761 } else {
1762 // Patient is dead, so return the number of days patient has been deceased.
1763 // Don't let it be zero days or else will confuse calls to this function.
1764 if ($results['days_deceased'] === 0) {
1765 $results['days_deceased'] = 1;
1768 return $results;
1772 // This computes, sets and returns the dup score for the given patient.
1774 function updateDupScore($pid)
1776 $row = sqlQuery(
1777 "SELECT MAX(" . getDupScoreSQL() . ") AS dupscore " .
1778 "FROM patient_data AS p1, patient_data AS p2 WHERE " .
1779 "p1.pid = ? AND p2.pid < p1.pid",
1780 array($pid)
1782 $dupscore = empty($row['dupscore']) ? 0 : $row['dupscore'];
1783 sqlStatement(
1784 "UPDATE patient_data SET dupscore = ? WHERE pid = ?",
1785 array($dupscore, $pid)
1787 return $dupscore;