4 * patient.inc includes functions for manipulating patient information.
7 * @link http://www.open-emr.org
8 * @author Brady Miller <brady.g.miller@gmail.com>
9 * @author Sherwin Gaddis <sherwingaddis@gmail.com>
10 * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>
11 * @copyright Copyright (c) 2019 Sherwin Gaddis <sherwingaddis@gmail.com>
12 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
15 use OpenEMR\Common\Uuid\UuidRegistry;
16 use OpenEMR\Services\FacilityService;
18 $facilityService = new FacilityService();
20 // These are for sports team use:
21 $PLAYER_FITNESSES = array(
24 xl('Restricted Training'),
28 xl('International Duty')
30 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
32 // Hard-coding this array because its values and meanings are fixed by the 837p
33 // standard and we don't want people messing with them.
34 $policy_types = array(
36 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
37 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
38 '14' => xl('No-fault Insurance including Auto is Primary'),
39 '15' => xl('Worker`s Compensation'),
40 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
41 '41' => xl('Black Lung'),
42 '42' => xl('Veteran`s Administration'),
43 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
44 '47' => xl('Other Liability Insurance is Primary'),
48 * Get a patient's demographic data.
50 * @param int $pid The PID of the patient
51 * @param string $given an optional subsection of the patient's demographic
53 * @return array The requested subsection of a patient's demographic data.
54 * If no subsection was given, returns everything, with the
55 * date of birth as the last field.
57 // To prevent sql injection on this function, if a variable is used for $given parameter, then
58 // it needs to be escaped via whitelisting prior to using this function.
59 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
61 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
62 return sqlQuery($sql, array($pid));
65 function getInsuranceProvider($ins_id)
68 $sql = "select name from insurance_companies where id=?";
69 $row = sqlQuery($sql, array($ins_id));
73 function getInsuranceProviders()
78 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
79 $rez = sqlStatement($sql);
80 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
81 $returnval[$row['id']] = $row['name'];
83 } else { // Please leave this here. I have a user who wants to see zip codes and PO
84 // box numbers listed along with the insurance company names, as many companies
85 // have different billing addresses for different plans. -- Rod Roark
86 $sql = "select insurance_companies.name, insurance_companies.id, " .
87 "addresses.zip, addresses.line1 " .
88 "from insurance_companies, addresses " .
89 "where addresses.foreign_id = insurance_companies.id " .
90 "order by insurance_companies.name, addresses.zip";
92 $rez = sqlStatement($sql);
94 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
95 preg_match("/\d+/", $row['line1'], $matches);
96 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
97 "," . $matches[0] . ")";
104 function getInsuranceProvidersExtra()
106 $returnval = array();
107 // add a global and if for where to allow inactive inscompanies
109 $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
110 addresses.state, addresses.zip
111 FROM insurance_companies, addresses
112 WHERE addresses.foreign_id = insurance_companies.id
113 AND insurance_companies.inactive != 1
114 ORDER BY insurance_companies.name, addresses.zip";
116 $rez = sqlStatement($sql);
118 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
119 switch ($GLOBALS['insurance_information']) {
120 case $GLOBALS['insurance_information'] = '0':
121 $returnval[$row['id']] = $row['name'];
123 case $GLOBALS['insurance_information'] = '1':
124 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
126 case $GLOBALS['insurance_information'] = '2':
127 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
129 case $GLOBALS['insurance_information'] = '3':
130 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
132 case $GLOBALS['insurance_information'] = '4':
133 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
134 ", " . $row['zip'] . ")";
136 case $GLOBALS['insurance_information'] = '5':
137 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
138 ", " . $row['state'] . ", " . $row['zip'] . ")";
140 case $GLOBALS['insurance_information'] = '6':
141 preg_match("/\d+/", $row['line1'], $matches);
142 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
143 "," . $matches[0] . ")";
151 // ----------------------------------------------------------------------------
152 // Get one facility row. If the ID is not specified, then get either the
153 // "main" (billing) facility, or the default facility of the currently
154 // logged-in user. This was created to support genFacilityTitle() but
155 // may find additional uses.
157 function getFacility($facid = 0)
159 global $facilityService;
164 return $facilityService->getById($facid);
167 if ($GLOBALS['login_into_facility']) {
168 //facility is saved in sessions
169 $facility = $facilityService->getById($_SESSION['facilityId']);
172 $facility = $facilityService->getPrimaryBillingLocation();
174 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
181 // Generate a report title including report name and facility name, address
184 function genFacilityTitle($repname = '', $facid = 0, $logo = '')
187 $s .= "<table class='ftitletable'>\n";
190 $s .= " <td class='ftitlecell1'>" . text($repname) . "</td>\n";
192 $s .= " <td class='ftitlecell1'>" . $logo . "</td>\n";
193 $s .= " <td class='ftitlecellm'>" . text($repname) . "</td>\n";
195 $s .= " <td class='ftitlecell2'>\n";
196 $r = getFacility($facid);
198 $s .= "<b>" . text($r['name']) . "</b>\n";
200 $s .= "<br />" . text($r['street']) . "\n";
203 if ($r['city'] || $r['state'] || $r['postal_code']) {
206 $s .= text($r['city']);
214 $s .= text($r['state']);
217 if ($r['postal_code']) {
218 $s .= " " . text($r['postal_code']);
224 if ($r['country_code']) {
225 $s .= "<br />" . text($r['country_code']) . "\n";
228 if (preg_match('/[1-9]/', $r['phone'])) {
229 $s .= "<br />" . text($r['phone']) . "\n";
242 returns all facilities or just the id for the first one
243 (FACILITY FILTERING (lemonsoftware))
245 @param string - if 'first' return first facility ordered by id
246 @return array | int for 'first' case
248 function getFacilities($first = '')
250 global $facilityService;
252 $fres = $facilityService->getAllFacility();
254 if ($first == 'first') {
255 return $fres[0]['id'];
261 //(CHEMED) facility filter
262 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
265 if ($providers_only === 'any') {
266 $param1 = " AND authorized = 1 AND active = 1 ";
267 } elseif ($providers_only) {
268 $param1 = " AND authorized = 1 AND calendar = 1 ";
271 //--------------------------------
272 //(CHEMED) facility filter
275 if ($GLOBALS['restrict_user_facility']) {
276 $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))";
278 $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
282 //--------------------------------
285 if ($providerID == "%") {
289 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
290 "from users where username != '' and active = 1 and id $command '" .
291 add_escape_custom($providerID) . "' " . $param1 . $param2;
292 // sort by last name -- JRM June 2008
293 $query .= " ORDER BY lname, fname ";
294 $rez = sqlStatement($query);
295 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
296 $returnval[$iter] = $row;
299 //if only one result returned take the key/value pairs in array [0] and merge them down into
300 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
303 $akeys = array_keys($returnval[0]);
304 foreach ($akeys as $key) {
305 $returnval[0][$key] = $returnval[0][$key];
312 function getProviderName($providerID, $provider_only = 'any')
314 $pi = getProviderInfo($providerID, $provider_only);
315 if (strlen($pi[0]["lname"]) > 0) {
316 if (strlen($pi[0]["suffix"]) > 0) {
317 $pi[0]["lname"] .= ", " . $pi[0]["suffix"];
320 return $pi[0]['fname'] . " " . $pi[0]['lname'];
326 function getProviderId($providerName)
328 $query = "select id from users where username = ?";
329 $rez = sqlStatement($query, array($providerName));
330 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
331 $returnval[$iter] = $row;
337 // To prevent sql injection on this function, if a variable is used for $given parameter, then
338 // it needs to be escaped via whitelisting prior to using this function; see lines 2020-2121 of
339 // library/clinical_rules.php script for example of this.
340 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
343 if ($given == 'tobacco') {
344 $where = 'tobacco is not null and';
347 if ($dateStart && $dateEnd) {
348 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
349 } elseif ($dateStart && !$dateEnd) {
350 $res = sqlQuery("select $given from history_data where $where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
351 } elseif (!$dateStart && $dateEnd) {
352 $res = sqlQuery("select $given from history_data where $where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
354 $res = sqlQuery("select $given from history_data where $where pid=? order by date DESC limit 0,1", array($pid));
360 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
361 // To prevent sql injection on this function, if a variable is used for $given parameter, then
362 // it needs to be escaped via whitelisting prior to using this function.
363 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
365 $sql = "select $given from insurance_data as insd " .
366 "left join insurance_companies as ic on ic.id = insd.provider " .
367 "where pid = ? and type = ? order by date DESC limit 1";
368 return sqlQuery($sql, array($pid, $type));
371 // To prevent sql injection on this function, if a variable is used for $given parameter, then
372 // it needs to be escaped via whitelisting prior to using this function.
373 function getInsuranceDataByDate(
377 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
379 // this must take the date in the following manner: YYYY-MM-DD
380 // this function recalls the insurance value that was most recently enterred from the
381 // given date. it will call up most recent records up to and on the date given,
382 // but not records enterred after the given date
383 $sql = "select $given from insurance_data as insd " .
384 "left join insurance_companies as ic on ic.id = provider " .
385 "where pid = ? and (date_format(date,'%Y-%m-%d') <= ? OR date IS NULL) and " .
386 "type=? order by date DESC limit 1";
387 return sqlQuery($sql, array($pid,$date,$type));
390 // To prevent sql injection on this function, if a variable is used for $given parameter, then
391 // it needs to be escaped via whitelisting prior to using this function.
392 function getEmployerData($pid, $given = "*")
394 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
395 return sqlQuery($sql, array($pid));
398 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
400 // When the limit is exceeded, find out what the unlimited count would be.
401 $GLOBALS['PATIENT_INC_COUNT'] = $count;
402 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
403 if ($limit != "all") {
404 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
405 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
410 * Allow the last name to be followed by a comma and some part of a first name(can
411 * also place middle name after the first name with a space separating them)
412 * Allows comma alone followed by some part of a first name(can also place middle name
413 * after the first name with a space separating them).
414 * Allows comma alone preceded by some part of a last name.
415 * If no comma or space, then will search both last name and first name.
416 * If the first letter of either name is capital, searches for name starting
417 * with given substring (the expected behavior). If it is lower case, it
418 * searches for the substring anywhere in the name. This applies to either
419 * last name, first name, and middle name.
420 * Also allows first name followed by middle and/or last name when separated by spaces.
421 * @param string $term
422 * @param string $given
423 * @param string $orderby
424 * @param string $limit
425 * @param string $start
428 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
429 // it needs to be escaped via whitelisting prior to using this function.
430 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")
432 $names = getPatientNameSplit($term);
434 foreach ($names as $key => $val) {
436 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
437 $names[$key] = '%' . $val . '%';
439 $names[$key] = $val . '%';
444 // Debugging section below
445 //if(array_key_exists('first',$names)) {
446 // error_log("first name search term :".$names['first']);
448 //if(array_key_exists('middle',$names)) {
449 // error_log("middle name search term :".$names['middle']);
451 //if(array_key_exists('last',$names)) {
452 // error_log("last name search term :".$names['last']);
454 // Debugging section above
456 $sqlBindArray = array();
457 if (array_key_exists('last', $names) && $names['last'] == '') {
458 // Do not search last name
459 $where = "fname LIKE ? ";
460 array_push($sqlBindArray, $names['first']);
461 if ($names['middle'] != '') {
462 $where .= "AND mname LIKE ? ";
463 array_push($sqlBindArray, $names['middle']);
465 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
466 // Do not search first name or middle name
467 $where = "lname LIKE ? ";
468 array_push($sqlBindArray, $names['last']);
469 } elseif ($names['first'] == '' && $names['last'] != '') {
470 // Search both first name and last name with same term
471 $names['first'] = $names['last'];
472 $where = "lname LIKE ? OR fname LIKE ? ";
473 array_push($sqlBindArray, $names['last'], $names['first']);
474 } elseif ($names['middle'] != '') {
475 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
476 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
478 $where = "lname LIKE ? AND fname LIKE ? ";
479 array_push($sqlBindArray, $names['last'], $names['first']);
482 if (!empty($GLOBALS['pt_restrict_field'])) {
483 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
484 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
485 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
486 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
487 array_push($sqlBindArray, $_SESSION["authUser"]);
491 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
492 if ($limit != "all") {
493 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
496 $rez = sqlStatement($sql, $sqlBindArray);
498 $returnval = array();
499 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
500 $returnval[$iter] = $row;
503 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
507 * Accept a string used by a search function expected to find a patient name,
508 * then split up the string if a comma or space exists. Return an array having
509 * from 1 to 3 elements, named first, middle, and last.
510 * See above getPatientLnames() function for details on how the splitting occurs.
511 * @param string $term
514 function getPatientNameSplit($term)
517 if (strpos($term, ',') !== false) {
518 $names = explode(',', $term);
519 $n['last'] = $names[0];
520 if (strpos(trim($names[1]), ' ') !== false) {
521 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
523 $n['first'] = $names[1];
525 } elseif (strpos($term, ' ') !== false) {
526 $names = explode(' ', $term);
527 if (count($names) == 1) {
528 $n['last'] = $names[0];
529 } elseif (count($names) == 3) {
530 $n['first'] = $names[0];
531 $n['middle'] = $names[1];
532 $n['last'] = $names[2];
534 // This will handle first and last name or first followed by
535 // multiple names only using just the last of the names in the list.
536 $n['first'] = $names[0];
537 $n['last'] = end($names);
541 if (empty($n['last'])) {
546 // Trim whitespace off the names before returning
547 foreach ($n as $key => $val) {
548 $n[$key] = trim($val);
551 return $n; // associative array containing names
554 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
555 // it needs to be escaped via whitelisting prior to using this function.
556 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")
559 $sqlBindArray = array();
560 $where = "pubpid LIKE ? ";
561 array_push($sqlBindArray, $pid . "%");
562 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
563 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
564 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
565 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
566 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
567 array_push($sqlBindArray, $_SESSION["authUser"]);
571 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
572 if ($limit != "all") {
573 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
576 $rez = sqlStatement($sql, $sqlBindArray);
577 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
578 $returnval[$iter] = $row;
581 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
585 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
586 // it needs to be escaped via whitelisting prior to using this function.
587 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")
589 $layoutCols = sqlStatement(
590 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
594 $sqlBindArray = array();
596 for ($iter = 0; $row = sqlFetchArray($layoutCols); $iter++) {
601 $where .= " " . add_escape_custom($row["field_id"]) . " like ? ";
602 array_push($sqlBindArray, "%" . $searchTerm . "%");
605 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
606 if ($limit != "all") {
607 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
610 $rez = sqlStatement($sql, $sqlBindArray);
611 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
612 $returnval[$iter] = $row;
615 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
619 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
620 // it needs to be escaped via whitelisting prior to using this function.
621 function getByPatientDemographicsFilter(
624 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
625 $orderby = "lname ASC, fname ASC",
628 $search_service_code = ''
631 $layoutCols = explode('~', $searchFields);
632 $sqlBindArray = array();
635 foreach ($layoutCols as $val) {
645 $where .= " " . add_escape_custom($val) . " = ? ";
646 array_push($sqlBindArray, $searchTerm);
648 $where .= " " . add_escape_custom($val) . " like ? ";
649 array_push($sqlBindArray, $searchTerm . "%");
655 // If no search terms, ensure valid syntax.
660 // If a non-empty service code was given, then restrict to patients who
661 // have been provided that service. Since the code is used in a LIKE
662 // clause, % and _ wildcards are supported.
663 if ($search_service_code) {
664 $where = "( $where ) AND " .
665 "( SELECT COUNT(*) FROM billing AS b WHERE " .
666 "b.pid = patient_data.pid AND " .
667 "b.activity = 1 AND " .
668 "b.code_type != 'COPAY' AND " .
671 array_push($sqlBindArray, $search_service_code);
674 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
675 if ($limit != "all") {
676 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
679 $rez = sqlStatement($sql, $sqlBindArray);
680 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
681 $returnval[$iter] = $row;
684 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
688 // return a collection of Patient PIDs
689 // new arg style by JRM March 2008
690 // 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")
691 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
692 // it needs to be escaped via whitelisting prior to using this function.
693 function getPatientPID($args)
696 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
697 $orderby = "lname ASC, fname ASC";
701 // alter default values if defined in the passed in args
702 if (isset($args['pid'])) {
706 if (isset($args['given'])) {
707 $given = $args['given'];
710 if (isset($args['orderby'])) {
711 $orderby = $args['orderby'];
714 if (isset($args['limit'])) {
715 $limit = $args['limit'];
718 if (isset($args['start'])) {
719 $start = $args['start'];
725 } elseif (empty($pid)) {
729 if (strstr($pid, "%")) {
733 $sql = "select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
734 if ($limit != "all") {
735 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
738 $rez = sqlStatement($sql);
739 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
740 $returnval[$iter] = $row;
746 /* return a patient's name in the format LAST, FIRST */
747 function getPatientName($pid)
753 $patientData = getPatientPID(array("pid" => $pid));
754 if (empty($patientData[0]['lname'])) {
758 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
762 /* return a patient's name in the format FIRST LAST */
763 function getPatientNameFirstLast($pid)
769 $patientData = getPatientPID(array("pid" => $pid));
770 if (empty($patientData[0]['lname'])) {
774 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
778 /* find patient data by DOB */
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 getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
783 $sqlBindArray = array();
784 $where = "DOB like ? ";
785 array_push($sqlBindArray, $DOB . "%");
786 if (!empty($GLOBALS['pt_restrict_field'])) {
787 if ($_SESSION["authUser"] != 'admin' || $GLOBALS['pt_restrict_admin']) {
788 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
789 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
790 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
791 array_push($sqlBindArray, $_SESSION["authUser"]);
795 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
797 if ($limit != "all") {
798 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
801 $rez = sqlStatement($sql, $sqlBindArray);
802 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
803 $returnval[$iter] = $row;
806 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
810 /* find patient data by SSN */
811 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
812 // it needs to be escaped via whitelisting prior to using this function.
813 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
815 $sqlBindArray = array();
816 $where = "ss LIKE ?";
817 array_push($sqlBindArray, $ss . "%");
818 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
819 if ($limit != "all") {
820 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
823 $rez = sqlStatement($sql, $sqlBindArray);
824 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
825 $returnval[$iter] = $row;
828 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
832 //(CHEMED) Search by phone number
833 // To prevent sql injection on this function, if a variable is used for $given OR $orderby parameter, then
834 // it needs to be escaped via whitelisting prior to using this function.
835 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
837 $phone = preg_replace("/[[:punct:]]/", "", $phone);
838 $sqlBindArray = array();
839 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
840 array_push($sqlBindArray, $phone);
841 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
842 if ($limit != "all") {
843 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
846 $rez = sqlStatement($sql, $sqlBindArray);
847 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
848 $returnval[$iter] = $row;
851 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
855 //----------------------input functions
856 function newPatientData(
875 $contact_relationship = "",
882 $migrantseasonal = "",
884 $monthly_income = "",
886 $financial_review = "",
900 $drivers_license = "",
907 $referral_source = '';
909 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
910 // Check for brain damage:
911 if ($db_id != $rez['id']) {
912 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
913 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
917 $fitness = $rez['fitness'];
918 $referral_source = $rez['referral_source'];
921 // Get the default price level.
922 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
923 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
924 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
926 $query = ("replace into patient_data set
927 id='" . add_escape_custom($db_id) . "',
928 title='" . add_escape_custom($title) . "',
929 fname='" . add_escape_custom($fname) . "',
930 lname='" . add_escape_custom($lname) . "',
931 mname='" . add_escape_custom($mname) . "',
932 sex='" . add_escape_custom($sex) . "',
933 DOB='" . add_escape_custom($DOB) . "',
934 street='" . add_escape_custom($street) . "',
935 postal_code='" . add_escape_custom($postal_code) . "',
936 city='" . add_escape_custom($city) . "',
937 state='" . add_escape_custom($state) . "',
938 country_code='" . add_escape_custom($country_code) . "',
939 drivers_license='" . add_escape_custom($drivers_license) . "',
940 ss='" . add_escape_custom($ss) . "',
941 occupation='" . add_escape_custom($occupation) . "',
942 phone_home='" . add_escape_custom($phone_home) . "',
943 phone_biz='" . add_escape_custom($phone_biz) . "',
944 phone_contact='" . add_escape_custom($phone_contact) . "',
945 status='" . add_escape_custom($status) . "',
946 contact_relationship='" . add_escape_custom($contact_relationship) . "',
947 referrer='" . add_escape_custom($referrer) . "',
948 referrerID='" . add_escape_custom($referrerID) . "',
949 email='" . add_escape_custom($email) . "',
950 language='" . add_escape_custom($language) . "',
951 ethnoracial='" . add_escape_custom($ethnoracial) . "',
952 interpretter='" . add_escape_custom($interpretter) . "',
953 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
954 family_size='" . add_escape_custom($family_size) . "',
955 monthly_income='" . add_escape_custom($monthly_income) . "',
956 homeless='" . add_escape_custom($homeless) . "',
957 financial_review='" . add_escape_custom($financial_review) . "',
958 pubpid='" . add_escape_custom($pubpid) . "',
959 pid= '" . add_escape_custom($pid) . "',
960 providerID = '" . add_escape_custom($providerID) . "',
961 genericname1 = '" . add_escape_custom($genericname1) . "',
962 genericval1 = '" . add_escape_custom($genericval1) . "',
963 genericname2 = '" . add_escape_custom($genericname2) . "',
964 genericval2 = '" . add_escape_custom($genericval2) . "',
965 billing_note= '" . add_escape_custom($billing_note) . "',
966 phone_cell = '" . add_escape_custom($phone_cell) . "',
967 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
968 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
969 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
970 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
971 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
972 squad = '" . add_escape_custom($squad) . "',
973 fitness='" . add_escape_custom($fitness) . "',
974 referral_source='" . add_escape_custom($referral_source) . "',
975 regdate='" . add_escape_custom($regdate) . "',
976 pricelevel='" . add_escape_custom($pricelevel) . "',
979 $id = sqlInsert($query);
982 // find the last inserted id for new patient case
986 $foo = sqlQuery("select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1", array($id));
988 // set uuid if not set yet (if this was an insert and not an update)
989 if (empty($foo['uuid'])) {
990 $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();
991 sqlStatementNoLog("UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?", [$uuid, $id]);
997 // Supported input date formats are:
999 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1001 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1003 function fixDate($date, $default = "0000-00-00")
1005 $fixed_date = $default;
1006 $date = trim($date);
1007 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1008 $dmy = preg_split("'[/.-]'", $date);
1010 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1012 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1013 if ($dmy[2] < 1000) {
1017 if ($dmy[2] < 1910) {
1022 // phone_country_code indicates format of ambiguous input dates.
1023 if ($GLOBALS['phone_country_code'] == 1) {
1024 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1026 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1034 function pdValueOrNull($key, $value)
1037 ($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1038 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1039 (empty($value) || $value == '0000-00-00')
1043 return "'" . add_escape_custom($value) . "'";
1047 // Create or update patient data from an array.
1049 function updatePatientData($pid, $new, $create = false)
1051 /*******************************************************************
1052 $real = getPatientData($pid);
1053 foreach ($new as $key => $value)
1054 $real[$key] = $value;
1055 $real['date'] = "'+NOW()+'";
1057 $sql = "insert into patient_data set ";
1058 foreach ($real as $key => $value)
1059 $sql .= $key." = '$value', ";
1060 $sql = substr($sql, 0, -2);
1061 return sqlInsert($sql);
1062 *******************************************************************/
1064 // The above was broken, though seems intent to insert a new patient_data
1065 // row for each update. A good idea, but nothing is doing that yet so
1066 // the code below does not yet attempt it.
1069 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1070 foreach ($new as $key => $value) {
1075 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1078 // add a uuid for the new patient
1079 $sql .= ", `uuid` ='" . add_escape_custom((new UuidRegistry(['table_name' => 'patient_data']))->createUuid()) . "'";
1081 $db_id = sqlInsert($sql);
1083 $db_id = $new['id'];
1084 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1085 // Check for brain damage:
1086 if ($pid != $rez['pid']) {
1087 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1088 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1092 $sql = "UPDATE patient_data SET date = NOW()";
1093 foreach ($new as $key => $value) {
1094 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1097 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1104 function newEmployerData(
1114 return sqlInsert("insert into employer_data set
1115 name='" . add_escape_custom($name) . "',
1116 street='" . add_escape_custom($street) . "',
1117 postal_code='" . add_escape_custom($postal_code) . "',
1118 city='" . add_escape_custom($city) . "',
1119 state='" . add_escape_custom($state) . "',
1120 country='" . add_escape_custom($country) . "',
1121 pid='" . add_escape_custom($pid) . "',
1126 // Create or update employer data from an array.
1128 function updateEmployerData($pid, $new, $create = false)
1130 $colnames = array('name','street','city','state','postal_code','country');
1133 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1134 foreach ($colnames as $key) {
1135 $value = isset($new[$key]) ? $new[$key] : '';
1136 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1139 return sqlInsert("INSERT INTO employer_data SET $set");
1142 $old = getEmployerData($pid);
1144 foreach ($colnames as $key) {
1145 $value = empty($old[$key]) ? '' : $old[$key];
1146 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1147 $value = $new[$key];
1151 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1155 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1156 return sqlInsert("INSERT INTO employer_data SET $set");
1163 // This updates or adds the given insurance data info, while retaining any
1164 // previously added insurance_data rows that should be preserved.
1165 // This does not directly support the maintenance of non-current insurance.
1167 function newInsuranceData(
1171 $policy_number = "",
1174 $subscriber_lname = "",
1175 $subscriber_mname = "",
1176 $subscriber_fname = "",
1177 $subscriber_relationship = "",
1178 $subscriber_ss = "",
1179 $subscriber_DOB = null,
1180 $subscriber_street = "",
1181 $subscriber_postal_code = "",
1182 $subscriber_city = "",
1183 $subscriber_state = "",
1184 $subscriber_country = "",
1185 $subscriber_phone = "",
1186 $subscriber_employer = "",
1187 $subscriber_employer_street = "",
1188 $subscriber_employer_city = "",
1189 $subscriber_employer_postal_code = "",
1190 $subscriber_employer_state = "",
1191 $subscriber_employer_country = "",
1193 $subscriber_sex = "",
1194 $effective_date = null,
1195 $accept_assignment = "TRUE",
1199 if (strlen($type) <= 0) {
1203 // If empty dates were passed, then null.
1204 if (empty($effective_date)) {
1205 $effective_date = null;
1207 if (empty($subscriber_DOB)) {
1208 $subscriber_DOB = null;
1211 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1212 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1213 $idrow = sqlFetchArray($idres);
1215 // Replace the most recent entry in any of the following cases:
1216 // * Its effective date is >= this effective date.
1217 // * It is the first entry and it has no (insurance) provider.
1218 // * There is no encounter that is earlier than the new effective date but
1219 // on or after the old effective date.
1220 // Otherwise insert a new entry.
1224 // convert date from null to "0000-00-00" for below strcmp and query
1225 $temp_idrow_date = (!empty($idrow['date'])) ? $idrow['date'] : "0000-00-00";
1226 $temp_effective_date = (!empty($effective_date)) ? $effective_date : "0000-00-00";
1227 if (strcmp($temp_idrow_date, $temp_effective_date) > 0) {
1230 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1233 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1234 "WHERE pid = ? AND date < ? AND " .
1235 "date >= ?", array($pid, $temp_effective_date . " 00:00:00", $temp_idrow_date . " 00:00:00"));
1236 if ($ferow['count'] == 0) {
1244 // TBD: This is a bit dangerous in that a typo in entering the effective
1245 // date can wipe out previous insurance history. So we want some data
1246 // entry validation somewhere.
1247 if ($effective_date === null) {
1248 sqlStatement("DELETE FROM insurance_data WHERE " .
1249 "pid = ? AND type = ? AND " .
1250 "id != ?", array($pid, $type, $idrow['id']));
1252 sqlStatement("DELETE FROM insurance_data WHERE " .
1253 "pid = ? AND type = ? AND date >= ? AND " .
1254 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1258 $data['type'] = $type;
1259 $data['provider'] = $provider;
1260 $data['policy_number'] = $policy_number;
1261 $data['group_number'] = $group_number;
1262 $data['plan_name'] = $plan_name;
1263 $data['subscriber_lname'] = $subscriber_lname;
1264 $data['subscriber_mname'] = $subscriber_mname;
1265 $data['subscriber_fname'] = $subscriber_fname;
1266 $data['subscriber_relationship'] = $subscriber_relationship;
1267 $data['subscriber_ss'] = $subscriber_ss;
1268 $data['subscriber_DOB'] = $subscriber_DOB;
1269 $data['subscriber_street'] = $subscriber_street;
1270 $data['subscriber_postal_code'] = $subscriber_postal_code;
1271 $data['subscriber_city'] = $subscriber_city;
1272 $data['subscriber_state'] = $subscriber_state;
1273 $data['subscriber_country'] = $subscriber_country;
1274 $data['subscriber_phone'] = $subscriber_phone;
1275 $data['subscriber_employer'] = $subscriber_employer;
1276 $data['subscriber_employer_city'] = $subscriber_employer_city;
1277 $data['subscriber_employer_street'] = $subscriber_employer_street;
1278 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1279 $data['subscriber_employer_state'] = $subscriber_employer_state;
1280 $data['subscriber_employer_country'] = $subscriber_employer_country;
1281 $data['copay'] = $copay;
1282 $data['subscriber_sex'] = $subscriber_sex;
1283 $data['pid'] = $pid;
1284 $data['date'] = $effective_date;
1285 $data['accept_assignment'] = $accept_assignment;
1286 $data['policy_type'] = $policy_type;
1287 updateInsuranceData($idrow['id'], $data);
1288 return $idrow['id'];
1291 "INSERT INTO `insurance_data` SET `type` = ?,
1293 `policy_number` = ?,
1296 `subscriber_lname` = ?,
1297 `subscriber_mname` = ?,
1298 `subscriber_fname` = ?,
1299 `subscriber_relationship` = ?,
1300 `subscriber_ss` = ?,
1301 `subscriber_DOB` = ?,
1302 `subscriber_street` = ?,
1303 `subscriber_postal_code` = ?,
1304 `subscriber_city` = ?,
1305 `subscriber_state` = ?,
1306 `subscriber_country` = ?,
1307 `subscriber_phone` = ?,
1308 `subscriber_employer` = ?,
1309 `subscriber_employer_city` = ?,
1310 `subscriber_employer_street` = ?,
1311 `subscriber_employer_postal_code` = ?,
1312 `subscriber_employer_state` = ?,
1313 `subscriber_employer_country` = ?,
1315 `subscriber_sex` = ?,
1318 `accept_assignment` = ?,
1329 $subscriber_relationship,
1333 $subscriber_postal_code,
1336 $subscriber_country,
1338 $subscriber_employer,
1339 $subscriber_employer_city,
1340 $subscriber_employer_street,
1341 $subscriber_employer_postal_code,
1342 $subscriber_employer_state,
1343 $subscriber_employer_country,
1355 // This is used internally only.
1356 function updateInsuranceData($id, $new)
1358 $fields = sqlListFields("insurance_data");
1361 foreach ($new as $key => $value) {
1362 if (in_array($key, $fields)) {
1363 $use[$key] = $value;
1368 $sql = "UPDATE insurance_data SET ";
1369 foreach ($use as $key => $value) {
1370 $sql .= "`" . $key . "` = ?, ";
1371 array_push($sqlBindArray, $value);
1374 $sql = substr($sql, 0, -2) . " WHERE id = ?";
1375 array_push($sqlBindArray, $id);
1377 sqlStatement($sql, $sqlBindArray);
1380 function newHistoryData($pid, $new = false)
1382 $arraySqlBind = array();
1383 $sql = "insert into history_data set pid = ?, date = NOW()";
1384 array_push($arraySqlBind, $pid);
1386 foreach ($new as $key => $value) {
1387 array_push($arraySqlBind, $value);
1388 $sql .= ", `$key` = ?";
1392 return sqlInsert($sql, $arraySqlBind);
1395 function updateHistoryData($pid, $new)
1397 $real = getHistoryData($pid);
1398 foreach ($new as $key => $value) {
1399 $real[$key] = $value;
1403 // need to unset date, so can reset it below
1404 unset($real['date']);
1406 $arraySqlBind = array();
1407 $sql = "insert into history_data set `date` = NOW(), ";
1408 foreach ($real as $key => $value) {
1409 array_push($arraySqlBind, $value);
1410 $sql .= "`$key` = ?, ";
1413 $sql = substr($sql, 0, -2);
1415 return sqlInsert($sql, $arraySqlBind);
1419 // in months if < 2 years old
1420 // in years if > 2 years old
1421 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1422 // (optional) nowYMD is a date in YYYYMMDD format
1423 function getPatientAge($dobYMD, $nowYMD = null)
1425 // strip any dashes from the DOB
1426 $dobYMD = preg_replace("/-/", "", $dobYMD);
1427 $dobDay = substr($dobYMD, 6, 2);
1428 $dobMonth = substr($dobYMD, 4, 2);
1429 $dobYear = (int) substr($dobYMD, 0, 4);
1431 // set the 'now' date values
1432 if ($nowYMD == null) {
1433 $nowDay = date("d");
1434 $nowMonth = date("m");
1435 $nowYear = date("Y");
1437 $nowDay = substr($nowYMD, 6, 2);
1438 $nowMonth = substr($nowYMD, 4, 2);
1439 $nowYear = substr($nowYMD, 0, 4);
1442 $dayDiff = $nowDay - $dobDay;
1443 $monthDiff = $nowMonth - $dobMonth;
1444 $yearDiff = $nowYear - $dobYear;
1446 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear * 12) + $dobMonth);
1448 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1453 if ($ageInMonths > 24) {
1455 if (($monthDiff == 0) && ($dayDiff < 0)) {
1457 } elseif ($monthDiff < 0) {
1461 $age = "$ageInMonths " . xl('month');
1468 * Wrapper to make sure the clinical rules dates formats corresponds to the
1469 * format expected by getPatientAgeYMD
1471 * @param string $dob date of birth
1472 * @param string $target date to calculate age on
1473 * @return array containing
1474 * age - decimal age in years
1475 * age_in_months - decimal age in months
1476 * ageinYMD - formatted string #y #m #d */
1477 function parseAgeInfo($dob, $target)
1479 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1480 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1482 // Prepare target (Y-M-D H:M:S)
1483 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1485 return getPatientAgeYMD($dateDOB, $dateTarget);
1492 * @return array containing
1493 * age - decimal age in years
1494 * age_in_months - decimal age in months
1495 * ageinYMD - formatted string #y #m #d
1497 function getPatientAgeYMD($dob, $date = null)
1500 if ($date == null) {
1501 $daynow = date("d");
1502 $monthnow = date("m");
1503 $yearnow = date("Y");
1504 $datenow = $yearnow . $monthnow . $daynow;
1506 $datenow = preg_replace("/-/", "", $date);
1507 $yearnow = substr($datenow, 0, 4);
1508 $monthnow = substr($datenow, 4, 2);
1509 $daynow = substr($datenow, 6, 2);
1510 $datenow = $yearnow . $monthnow . $daynow;
1513 $dob = preg_replace("/-/", "", $dob);
1514 $dobyear = substr($dob, 0, 4);
1515 $dobmonth = substr($dob, 4, 2);
1516 $dobday = substr($dob, 6, 2);
1517 $dob = $dobyear . $dobmonth . $dobday;
1519 //to compensate for 30, 31, 28, 29 days/month
1520 $mo = $monthnow; //to avoid confusion with later calculation
1522 if ($mo == 05 or $mo == 07 or $mo == 10 or $mo == 12) { // determined by monthnow-1
1523 $nd = 30; // nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1524 } elseif ($mo == 03) { // look at April, June, September, November for calculation. These months only have 30 days.
1525 // for march, look to the month of February for calculation, check for leap year
1526 $check_leap_Y = $yearnow / 4; // To check if this is a leap year.
1527 if (is_int($check_leap_Y)) { // If it true then this is the leap year
1529 } else { // otherwise, it is not a leap year.
1532 } else { // other months have 31 days
1536 $bdthisyear = $yearnow . $dobmonth . $dobday; //Date current year's birthday falls on
1537 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1538 $age_year = $yearnow - $dobyear - 1;
1539 if ($daynow < $dobday) {
1540 $months_since_birthday = 12 - $dobmonth + $monthnow - 1;
1541 $days_since_dobday = $nd - $dobday + $daynow; //did not take into account for month with 31 days
1543 $months_since_birthday = 12 - $dobmonth + $monthnow;
1544 $days_since_dobday = $daynow - $dobday;
1546 } else // if patient has had birthday this calandar year
1548 $age_year = $yearnow - $dobyear;
1549 if ($daynow < $dobday) {
1550 $months_since_birthday = $monthnow - $dobmonth - 1;
1551 $days_since_dobday = $nd - $dobday + $daynow;
1553 $months_since_birthday = $monthnow - $dobmonth;
1554 $days_since_dobday = $daynow - $dobday;
1558 $day_as_month_decimal = $days_since_dobday / 30;
1559 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1560 $month_as_year_decimal = $months_since_birthday_float / 12;
1561 $age_float = $age_year + $month_as_year_decimal;
1563 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1564 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1565 $age = round($age_float, 2);
1567 // round the years to 2 floating points
1568 $ageinYMD = $age_year . "y " . $months_since_birthday . "m " . $days_since_dobday . "d";
1569 return compact('age', 'age_in_months', 'ageinYMD');
1572 // Returns Age in days
1573 // in months if < 2 years old
1574 // in years if > 2 years old
1575 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1576 // (optional) nowYMD is a date in YYYYMMDD format
1577 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1581 // strip any dashes from the DOB
1582 $dobYMD = preg_replace("/-/", "", $dobYMD);
1583 $dobDay = substr($dobYMD, 6, 2);
1584 $dobMonth = substr($dobYMD, 4, 2);
1585 $dobYear = substr($dobYMD, 0, 4);
1587 // set the 'now' date values
1588 if ($nowYMD == null) {
1589 $nowDay = date("d");
1590 $nowMonth = date("m");
1591 $nowYear = date("Y");
1593 $nowDay = substr($nowYMD, 6, 2);
1594 $nowMonth = substr($nowYMD, 4, 2);
1595 $nowYear = substr($nowYMD, 0, 4);
1599 $dobtime = strtotime($dobYear . "-" . $dobMonth . "-" . $dobDay);
1600 $nowtime = strtotime($nowYear . "-" . $nowMonth . "-" . $nowDay);
1601 $timediff = $nowtime - $dobtime;
1602 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1607 * Returns a string to be used to display a patient's age
1609 * @param type $dobYMD
1610 * @param type $asOfYMD
1611 * @return string suitable for displaying patient's age based on preferences
1613 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1615 if ($GLOBALS['age_display_format'] == '1') {
1616 $ageYMD = getPatientAgeYMD($dobYMD, $asOfYMD);
1617 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age'] <= $GLOBALS['age_display_limit']) {
1618 return $ageYMD['ageinYMD'];
1620 return getPatientAge($dobYMD, $asOfYMD);
1623 return getPatientAge($dobYMD, $asOfYMD);
1626 function dateToDB($date)
1628 $date = substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
1633 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1634 * for the given patient on the given date.
1636 * @param int The PID of the patient.
1637 * @param string Date in yyyy-mm-dd format.
1638 * @return array Array of 0-3 insurance_data rows.
1640 function getEffectiveInsurances($patient_id, $encdate)
1643 foreach (array('primary','secondary','tertiary') as $instype) {
1645 "SELECT * FROM insurance_data " .
1646 "WHERE pid = ? AND type = ? " .
1647 "AND (date <= ? OR date IS NULL) ORDER BY date DESC LIMIT 1",
1648 array($patient_id, $instype, $encdate)
1650 if (empty($tmp['provider'])) {
1661 * Get all requisition insurance companies
1666 function getAllinsurances($pid)
1669 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1670 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1671 b.name, c.line1, c.line2, c.city, c.state, c.zip
1672 FROM `insurance_data` AS a
1673 RIGHT JOIN insurance_companies AS b
1674 ON a.provider = b.id
1675 RIGHT JOIN addresses AS c
1676 ON a.provider = c.foreign_id
1678 $inco = sqlStatement($sql, array($pid));
1680 while ($icl = sqlFetchArray($inco)) {
1687 * Get the patient's balance due. Normally this excludes amounts that are out
1688 * to insurance. If you want to include what insurance owes, set the second
1689 * parameter to true.
1691 * @param int The PID of the patient.
1692 * @param boolean Indicates if amounts owed by insurance are to be included.
1693 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1694 * @return number The balance.
1696 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1699 $bindarray = array($pid);
1700 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1701 "last_level_closed, stmt_count " .
1702 "FROM form_encounter WHERE pid = ?";
1704 $sqlstatement .= " AND encounter = ?";
1705 array_push($bindarray, $eid);
1707 $feres = sqlStatement($sqlstatement, $bindarray);
1708 while ($ferow = sqlFetchArray($feres)) {
1709 $encounter = $ferow['encounter'];
1710 $dos = substr($ferow['date'], 0, 10);
1711 $insarr = getEffectiveInsurances($pid, $dos);
1712 $inscount = count($insarr);
1713 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1714 // It's out to insurance so only the co-pay might be due.
1716 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1717 "pid = ? AND encounter = ? AND " .
1718 "code_type = 'copay' AND activity = 1",
1719 array($pid, $encounter)
1722 "SELECT SUM(pay_amount) AS payments " .
1723 "FROM ar_activity WHERE " .
1724 "deleted IS NULL AND pid = ? AND encounter = ? AND payer_type = 0",
1725 array($pid, $encounter)
1727 $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1728 $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1729 $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1730 $ptbal = $copay + $amt - $pay;
1731 if ($ptbal) { // @TODO check if we want to show patient payment credits.
1735 // Including insurance or not out to insurance, everything is due.
1736 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1737 "pid = ? AND encounter = ? AND " .
1738 "activity = 1", array($pid, $encounter));
1739 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1740 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1741 "deleted IS NULL AND pid = ? AND encounter = ?", array($pid, $encounter));
1742 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1743 "pid = ? AND encounter = ?", array($pid, $encounter));
1744 $balance += $brow['amount'] + $srow['amount']
1745 - $drow['payments'] - $drow['adjustments'];
1749 return sprintf('%01.2f', $balance);
1752 // Function to check if patient is deceased.
1754 // $pid - patient id
1755 // $date - date checking if deceased (will default to current date if blank)
1757 // If deceased, then will return the number of
1758 // days that patient has been deceased and the deceased date.
1759 // If not deceased, then will return false.
1760 function is_patient_deceased($pid, $date = '')
1763 // Set date to current if not set
1764 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1766 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1767 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1768 "FROM `patient_data` " .
1769 "WHERE `pid` = ? AND " .
1770 dateEmptySql('deceased_date', true, true) .
1771 "AND `deceased_date` <= ?", array($date,$pid,$date));
1773 if (empty($results)) {
1774 // Patient is alive, so return false
1777 // Patient is dead, so return the number of days patient has been deceased.
1778 // Don't let it be zero days or else will confuse calls to this function.
1779 if ($results['days_deceased'] === 0) {
1780 $results['days_deceased'] = 1;