3 * patient.inc includes functions for manipulating patient information.
6 * @link http://www.open-emr.org
7 * @author Brady Miller <brady.g.miller@gmail.com>
8 * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>
9 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
13 use OpenEMR\Services\FacilityService;
15 $facilityService = new FacilityService();
17 // These are for sports team use:
18 $PLAYER_FITNESSES = array(
21 xl('Restricted Training'),
25 xl('International Duty')
27 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
29 // Hard-coding this array because its values and meanings are fixed by the 837p
30 // standard and we don't want people messing with them.
31 $policy_types = array(
33 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
34 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
35 '14' => xl('No-fault Insurance including Auto is Primary'),
36 '15' => xl('Worker`s Compensation'),
37 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
38 '41' => xl('Black Lung'),
39 '42' => xl('Veteran`s Administration'),
40 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
41 '47' => xl('Other Liability Insurance is Primary'),
45 * Get a patient's demographic data.
47 * @param int $pid The PID of the patient
48 * @param string $given an optional subsection of the patient's demographic
50 * @return array The requested subsection of a patient's demographic data.
51 * If no subsection was given, returns everything, with the
52 * date of birth as the last field.
54 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
56 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
57 return sqlQuery($sql, array($pid));
60 function getLanguages()
62 $returnval = array('','english');
63 $sql = "select distinct lower(language) as language from patient_data";
64 $rez = sqlStatement($sql);
65 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
66 if (($row["language"] != "english") && ($row["language"] != "")) {
67 array_push($returnval, $row["language"]);
74 function getInsuranceProvider($ins_id)
77 $sql = "select name from insurance_companies where id=?";
78 $row = sqlQuery($sql, array($ins_id));
82 function getInsuranceProviders()
87 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
88 $rez = sqlStatement($sql);
89 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
90 $returnval[$row['id']] = $row['name'];
92 } // Please leave this here. I have a user who wants to see zip codes and PO
93 // box numbers listed along with the insurance company names, as many companies
94 // have different billing addresses for different plans. -- Rod Roark
97 $sql = "select insurance_companies.name, insurance_companies.id, " .
98 "addresses.zip, addresses.line1 " .
99 "from insurance_companies, addresses " .
100 "where addresses.foreign_id = insurance_companies.id " .
101 "order by insurance_companies.name, addresses.zip";
103 $rez = sqlStatement($sql);
105 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
106 preg_match("/\d+/", $row['line1'], $matches);
107 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
108 "," . $matches[0] . ")";
115 function getInsuranceProvidersExtra()
117 $returnval = array();
118 // add a global and if for where to allow inactive inscompanies
120 $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
121 addresses.state, addresses.zip
122 FROM insurance_companies, addresses
123 WHERE addresses.foreign_id = insurance_companies.id
124 AND insurance_companies.inactive != 1
125 ORDER BY insurance_companies.name, addresses.zip";
127 $rez = sqlStatement($sql);
129 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
130 switch ($GLOBALS['insurance_information']) {
131 case $GLOBALS['insurance_information'] = '0':
132 $returnval[$row['id']] = $row['name'];
134 case $GLOBALS['insurance_information'] = '1':
135 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
137 case $GLOBALS['insurance_information'] = '2':
138 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
140 case $GLOBALS['insurance_information'] = '3':
141 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
143 case $GLOBALS['insurance_information'] = '4':
144 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
145 ", " . $row['zip'] . ")";
147 case $GLOBALS['insurance_information'] = '5':
148 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
149 ", " . $row['state'] . ", " . $row['zip'] . ")";
151 case $GLOBALS['insurance_information'] = '6':
152 preg_match("/\d+/", $row['line1'], $matches);
153 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
154 "," . $matches[0] . ")";
162 function getProviders()
164 $returnval = array();
165 $sql = "select fname, lname, suffix from users where authorized = 1 and " .
166 "active = 1 and username != ''";
167 $rez = sqlStatement($sql);
168 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
169 if (($row["fname"] != "") && ($row["lname"] != "")) {
170 if ($row["suffix"] != "") {
171 $row["lname"] .= ", ".$row["suffix"];
174 array_push($returnval, $row["fname"] . " " . $row["lname"]);
181 // ----------------------------------------------------------------------------
182 // Get one facility row. If the ID is not specified, then get either the
183 // "main" (billing) facility, or the default facility of the currently
184 // logged-in user. This was created to support genFacilityTitle() but
185 // may find additional uses.
187 function getFacility($facid = 0)
189 global $facilityService;
194 $facility = $facilityService->getById($facid);
195 } else if ($facid == 0) {
196 $facility = $facilityService->getPrimaryBillingLocation();
198 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
204 // Generate a report title including report name and facility name, address
207 function genFacilityTitle($repname = '', $facid = 0)
210 $s .= "<table class='ftitletable'>\n";
213 $s .= " <td class='ftitlecell1'>$repname</td>\n";
215 $s .= " <td class='ftitlecell1'>$logo</td>\n";
216 $s .= " <td class='ftitlecellm'>$repname</td>\n";
218 $s .= " <td class='ftitlecell2'>\n";
219 $r = getFacility($facid);
221 $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
223 $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
226 if ($r['city'] || $r['state'] || $r['postal_code']) {
229 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
237 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
240 if ($r['postal_code']) {
241 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
247 if ($r['country_code']) {
248 $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
251 if (preg_match('/[1-9]/', $r['phone'])) {
252 $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
265 returns all facilities or just the id for the first one
266 (FACILITY FILTERING (lemonsoftware))
268 @param string - if 'first' return first facility ordered by id
269 @return array | int for 'first' case
271 function getFacilities($first = '')
273 global $facilityService;
275 $fres = $facilityService->getAll();
277 if ($first == 'first') {
278 return $fres[0]['id'];
285 GET SERVICE FACILITIES
287 returns all service_location facilities or just the id for the first one
288 (FACILITY FILTERING (CHEMED))
290 @param string - if 'first' return first facility ordered by id
291 @return array | int for 'first' case
293 function getServiceFacilities($first = '')
295 global $facilityService;
297 $fres = $facilityService->getAllServiceLocations();
299 if ($first == 'first') {
300 return $fres[0]['id'];
306 //(CHEMED) facility filter
307 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
310 if ($providers_only === 'any') {
311 $param1 = " AND authorized = 1 AND active = 1 ";
312 } else if ($providers_only) {
313 $param1 = " AND authorized = 1 AND calendar = 1 ";
316 //--------------------------------
317 //(CHEMED) facility filter
320 if ($GLOBALS['restrict_user_facility']) {
321 $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))";
323 $param2 = " AND facility_id = '" . add_escape_custom($facility) . "'' ";
327 //--------------------------------
330 if ($providerID == "%") {
334 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
335 "from users where username != '' and active = 1 and id $command '" .
336 add_escape_custom($providerID) . "' " . $param1 . $param2;
337 // sort by last name -- JRM June 2008
338 $query .= " ORDER BY lname, fname ";
339 $rez = sqlStatement($query);
340 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
341 $returnval[$iter]=$row;
344 //if only one result returned take the key/value pairs in array [0] and merge them down into
345 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
348 $akeys = array_keys($returnval[0]);
349 foreach ($akeys as $key) {
350 $returnval[0][$key] = $returnval[0][$key];
357 //same as above but does not reduce if only 1 row returned
358 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
361 if ($providers_only) {
362 $param1 = "AND authorized=1";
366 if ($providerID == "%") {
370 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
371 "from users where active = 1 and username != '' and id $command '" .
372 add_escape_custom($providerID) . "' " . $param1;
374 $rez = sqlStatement($query);
375 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
376 $returnval[$iter]=$row;
382 function getProviderName($providerID)
384 $pi = getProviderInfo($providerID, 'any');
385 if (strlen($pi[0]["lname"]) > 0) {
386 if (strlen($pi[0]["suffix"]) > 0) {
387 $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
390 return $pi[0]['fname'] . " " . $pi[0]['lname'];
396 function getProviderId($providerName)
398 $query = "select id from users where username = ?";
399 $rez = sqlStatement($query, array($providerName));
400 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
401 $returnval[$iter]=$row;
407 function getEthnoRacials()
409 $returnval = array("");
410 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
411 $rez = sqlStatement($sql);
412 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
413 if (($row["ethnoracial"] != "")) {
414 array_push($returnval, $row["ethnoracial"]);
421 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
424 if ($dateStart && $dateEnd) {
425 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
426 } else if ($dateStart && !$dateEnd) {
427 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
428 } else if (!$dateStart && $dateEnd) {
429 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
431 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
434 if ($given == 'tobacco') {
435 $res = sqlQuery("select $given from history_data where pid = ? and tobacco is not null and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
441 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
442 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
444 $sql = "select $given from insurance_data as insd " .
445 "left join insurance_companies as ic on ic.id = insd.provider " .
446 "where pid = ? and type = ? order by date DESC limit 1";
447 return sqlQuery($sql, array($pid, $type));
450 function getInsuranceDataByDate(
454 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
456 // this must take the date in the following manner: YYYY-MM-DD
457 // this function recalls the insurance value that was most recently enterred from the
458 // given date. it will call up most recent records up to and on the date given,
459 // but not records enterred after the given date
460 $sql = "select $given from insurance_data as insd " .
461 "left join insurance_companies as ic on ic.id = provider " .
462 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
463 "type=? order by date DESC limit 1";
464 return sqlQuery($sql, array($pid,$date,$type));
467 function getEmployerData($pid, $given = "*")
469 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
470 return sqlQuery($sql, array($pid));
473 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
475 // When the limit is exceeded, find out what the unlimited count would be.
476 $GLOBALS['PATIENT_INC_COUNT'] = $count;
477 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
478 if ($limit != "all") {
479 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
480 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
485 * Allow the last name to be followed by a comma and some part of a first name(can
486 * also place middle name after the first name with a space separating them)
487 * Allows comma alone followed by some part of a first name(can also place middle name
488 * after the first name with a space separating them).
489 * Allows comma alone preceded by some part of a last name.
490 * If no comma or space, then will search both last name and first name.
491 * If the first letter of either name is capital, searches for name starting
492 * with given substring (the expected behavior). If it is lower case, it
493 * searches for the substring anywhere in the name. This applies to either
494 * last name, first name, and middle name.
495 * Also allows first name followed by middle and/or last name when separated by spaces.
496 * @param string $term
497 * @param string $given
498 * @param string $orderby
499 * @param string $limit
500 * @param string $start
503 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")
505 $names = getPatientNameSplit($term);
507 foreach ($names as $key => $val) {
509 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
510 $names[$key] = '%' . $val . '%';
512 $names[$key] = $val . '%';
517 // Debugging section below
518 //if(array_key_exists('first',$names)) {
519 // error_log("first name search term :".$names['first']);
521 //if(array_key_exists('middle',$names)) {
522 // error_log("middle name search term :".$names['middle']);
524 //if(array_key_exists('last',$names)) {
525 // error_log("last name search term :".$names['last']);
527 // Debugging section above
529 $sqlBindArray = array();
530 if (array_key_exists('last', $names) && $names['last'] == '') {
531 // Do not search last name
532 $where = "fname LIKE ? ";
533 array_push($sqlBindArray, $names['first']);
534 if ($names['middle'] != '') {
535 $where .= "AND mname LIKE ? ";
536 array_push($sqlBindArray, $names['middle']);
538 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
539 // Do not search first name or middle name
540 $where = "lname LIKE ? ";
541 array_push($sqlBindArray, $names['last']);
542 } elseif ($names['first'] == '' && $names['last'] != '') {
543 // Search both first name and last name with same term
544 $names['first'] = $names['last'];
545 $where = "lname LIKE ? OR fname LIKE ? ";
546 array_push($sqlBindArray, $names['last'], $names['first']);
547 } elseif ($names['middle'] != '') {
548 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
549 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
551 $where = "lname LIKE ? AND fname LIKE ? ";
552 array_push($sqlBindArray, $names['last'], $names['first']);
555 if (!empty($GLOBALS['pt_restrict_field'])) {
556 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
557 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
558 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
559 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
560 array_push($sqlBindArray, $_SESSION{"authUser"});
564 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
565 if ($limit != "all") {
566 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
569 $rez = sqlStatement($sql, $sqlBindArray);
572 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
573 $returnval[$iter] = $row;
576 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
580 * Accept a string used by a search function expected to find a patient name,
581 * then split up the string if a comma or space exists. Return an array having
582 * from 1 to 3 elements, named first, middle, and last.
583 * See above getPatientLnames() function for details on how the splitting occurs.
584 * @param string $term
587 function getPatientNameSplit($term)
590 if (strpos($term, ',') !== false) {
591 $names = explode(',', $term);
592 $n['last'] = $names[0];
593 if (strpos(trim($names[1]), ' ') !== false) {
594 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
596 $n['first'] = $names[1];
598 } elseif (strpos($term, ' ') !== false) {
599 $names = explode(' ', $term);
600 if (count($names) == 1) {
601 $n['last'] = $names[0];
602 } elseif (count($names) == 3) {
603 $n['first'] = $names[0];
604 $n['middle'] = $names[1];
605 $n['last'] = $names[2];
607 // This will handle first and last name or first followed by
608 // multiple names only using just the last of the names in the list.
609 $n['first'] = $names[0];
610 $n['last'] = end($names);
614 if (empty($n['last'])) {
619 // Trim whitespace off the names before returning
620 foreach ($n as $key => $val) {
621 $n[$key] = trim($val);
624 return $n; // associative array containing names
627 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")
630 $sqlBindArray = array();
631 $where = "pubpid LIKE ? ";
632 array_push($sqlBindArray, $pid."%");
633 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
634 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
635 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
636 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
637 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
638 array_push($sqlBindArray, $_SESSION{"authUser"});
642 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
643 if ($limit != "all") {
644 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
647 $rez = sqlStatement($sql, $sqlBindArray);
648 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
649 $returnval[$iter]=$row;
652 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
656 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")
658 $layoutCols = sqlStatement(
659 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
663 $sqlBindArray = array();
665 for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
670 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
671 array_push($sqlBindArray, "%".$searchTerm."%");
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 function getByPatientDemographicsFilter(
691 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
692 $orderby = "lname ASC, fname ASC",
695 $search_service_code = ''
698 $layoutCols = explode('~', $searchFields);
699 $sqlBindArray = array();
702 foreach ($layoutCols as $val) {
712 $where .= " ".add_escape_custom($val)." = ? ";
713 array_push($sqlBindArray, $searchTerm);
715 $where .= " ".add_escape_custom($val)." like ? ";
716 array_push($sqlBindArray, $searchTerm."%");
722 // If no search terms, ensure valid syntax.
727 // If a non-empty service code was given, then restrict to patients who
728 // have been provided that service. Since the code is used in a LIKE
729 // clause, % and _ wildcards are supported.
730 if ($search_service_code) {
731 $where = "( $where ) AND " .
732 "( SELECT COUNT(*) FROM billing AS b WHERE " .
733 "b.pid = patient_data.pid AND " .
734 "b.activity = 1 AND " .
735 "b.code_type != 'COPAY' AND " .
738 array_push($sqlBindArray, $search_service_code);
741 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
742 if ($limit != "all") {
743 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
746 $rez = sqlStatement($sql, $sqlBindArray);
747 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
748 $returnval[$iter]=$row;
751 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
755 // return a collection of Patient PIDs
756 // new arg style by JRM March 2008
757 // 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")
758 function getPatientPID($args)
761 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
762 $orderby = "lname ASC, fname ASC";
766 // alter default values if defined in the passed in args
767 if (isset($args['pid'])) {
771 if (isset($args['given'])) {
772 $given = $args['given'];
775 if (isset($args['orderby'])) {
776 $orderby = $args['orderby'];
779 if (isset($args['limit'])) {
780 $limit = $args['limit'];
783 if (isset($args['start'])) {
784 $start = $args['start'];
790 } elseif (empty($pid)) {
794 if (strstr($pid, "%")) {
798 $sql="select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
799 if ($limit != "all") {
800 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
803 $rez = sqlStatement($sql);
804 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
805 $returnval[$iter]=$row;
811 /* return a patient's name in the format LAST, FIRST */
812 function getPatientName($pid)
818 $patientData = getPatientPID(array("pid"=>$pid));
819 if (empty($patientData[0]['lname'])) {
823 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
827 /* find patient data by DOB */
828 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
830 $sqlBindArray = array();
831 $where = "DOB like ? ";
832 array_push($sqlBindArray, $DOB."%");
833 if (!empty($GLOBALS['pt_restrict_field'])) {
834 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
835 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
836 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
837 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
838 array_push($sqlBindArray, $_SESSION{"authUser"});
842 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
844 if ($limit != "all") {
845 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
848 $rez = sqlStatement($sql, $sqlBindArray);
849 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
850 $returnval[$iter]=$row;
853 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
857 /* find patient data by SSN */
858 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
860 $sqlBindArray = array();
861 $where = "ss LIKE ?";
862 array_push($sqlBindArray, $ss."%");
863 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
864 if ($limit != "all") {
865 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
868 $rez = sqlStatement($sql, $sqlBindArray);
869 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
870 $returnval[$iter]=$row;
873 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
877 //(CHEMED) Search by phone number
878 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
880 $phone = preg_replace("/[[:punct:]]/", "", $phone);
881 $sqlBindArray = array();
882 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
883 array_push($sqlBindArray, $phone);
884 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
885 if ($limit != "all") {
886 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
889 $rez = sqlStatement($sql, $sqlBindArray);
890 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
891 $returnval[$iter]=$row;
894 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
898 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
900 $sql="select $given from patient_data order by $orderby";
902 if ($limit != "all") {
903 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
906 $rez = sqlStatement($sql);
907 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
908 $returnval[$iter]=$row;
914 //----------------------input functions
915 function newPatientData(
934 $contact_relationship = "",
941 $migrantseasonal = "",
943 $monthly_income = "",
945 $financial_review = "",
959 $drivers_license = "",
966 $referral_source = '';
968 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
969 // Check for brain damage:
970 if ($db_id != $rez['id']) {
971 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
972 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
976 $fitness = $rez['fitness'];
977 $referral_source = $rez['referral_source'];
980 // Get the default price level.
981 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
982 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
983 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
985 $query = ("replace into patient_data set
986 id='" . add_escape_custom($db_id) . "',
987 title='" . add_escape_custom($title) . "',
988 fname='" . add_escape_custom($fname) . "',
989 lname='" . add_escape_custom($lname) . "',
990 mname='" . add_escape_custom($mname) . "',
991 sex='" . add_escape_custom($sex) . "',
992 DOB='" . add_escape_custom($DOB) . "',
993 street='" . add_escape_custom($street) . "',
994 postal_code='" . add_escape_custom($postal_code) . "',
995 city='" . add_escape_custom($city) . "',
996 state='" . add_escape_custom($state) . "',
997 country_code='" . add_escape_custom($country_code) . "',
998 drivers_license='" . add_escape_custom($drivers_license) . "',
999 ss='" . add_escape_custom($ss) . "',
1000 occupation='" . add_escape_custom($occupation) . "',
1001 phone_home='" . add_escape_custom($phone_home) . "',
1002 phone_biz='" . add_escape_custom($phone_biz) . "',
1003 phone_contact='" . add_escape_custom($phone_contact) . "',
1004 status='" . add_escape_custom($status) . "',
1005 contact_relationship='" . add_escape_custom($contact_relationship) . "',
1006 referrer='" . add_escape_custom($referrer) . "',
1007 referrerID='" . add_escape_custom($referrerID) . "',
1008 email='" . add_escape_custom($email) . "',
1009 language='" . add_escape_custom($language) . "',
1010 ethnoracial='" . add_escape_custom($ethnoracial) . "',
1011 interpretter='" . add_escape_custom($interpretter) . "',
1012 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1013 family_size='" . add_escape_custom($family_size) . "',
1014 monthly_income='" . add_escape_custom($monthly_income) . "',
1015 homeless='" . add_escape_custom($homeless) . "',
1016 financial_review='" . add_escape_custom($financial_review) . "',
1017 pubpid='" . add_escape_custom($pubpid) . "',
1018 pid= '" . add_escape_custom($pid) . "',
1019 providerID = '" . add_escape_custom($providerID) . "',
1020 genericname1 = '" . add_escape_custom($genericname1) . "',
1021 genericval1 = '" . add_escape_custom($genericval1) . "',
1022 genericname2 = '" . add_escape_custom($genericname2) . "',
1023 genericval2 = '" . add_escape_custom($genericval2) . "',
1024 billing_note= '" . add_escape_custom($billing_note) . "',
1025 phone_cell = '" . add_escape_custom($phone_cell) . "',
1026 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1027 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1028 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1029 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1030 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1031 squad = '" . add_escape_custom($squad) . "',
1032 fitness='" . add_escape_custom($fitness) . "',
1033 referral_source='" . add_escape_custom($referral_source) . "',
1034 regdate='" . add_escape_custom($regdate) . "',
1035 pricelevel='" . add_escape_custom($pricelevel) . "',
1038 $id = sqlInsert($query);
1041 // find the last inserted id for new patient case
1042 $db_id = getSqlLastID();
1045 $foo = sqlQuery("select pid from patient_data where id=? order by date limit 0,1", array($id));
1050 // Supported input date formats are:
1052 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1054 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1056 function fixDate($date, $default = "0000-00-00")
1058 $fixed_date = $default;
1059 $date = trim($date);
1060 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1061 $dmy = preg_split("'[/.-]'", $date);
1063 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1065 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1066 if ($dmy[2] < 1000) {
1070 if ($dmy[2] < 1910) {
1075 // phone_country_code indicates format of ambiguous input dates.
1076 if ($GLOBALS['phone_country_code'] == 1) {
1077 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1079 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1087 function pdValueOrNull($key, $value)
1089 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1090 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1091 (empty($value) || $value == '0000-00-00')) {
1094 return "'" . add_escape_custom($value) . "'";
1098 // Create or update patient data from an array.
1100 function updatePatientData($pid, $new, $create = false)
1102 /*******************************************************************
1103 $real = getPatientData($pid);
1104 foreach ($new as $key => $value)
1105 $real[$key] = $value;
1106 $real['date'] = "'+NOW()+'";
1108 $sql = "insert into patient_data set ";
1109 foreach ($real as $key => $value)
1110 $sql .= $key." = '$value', ";
1111 $sql = substr($sql, 0, -2);
1112 return sqlInsert($sql);
1113 *******************************************************************/
1115 // The above was broken, though seems intent to insert a new patient_data
1116 // row for each update. A good idea, but nothing is doing that yet so
1117 // the code below does not yet attempt it.
1120 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1121 foreach ($new as $key => $value) {
1126 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1129 $db_id = sqlInsert($sql);
1131 $db_id = $new['id'];
1132 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1133 // Check for brain damage:
1134 if ($pid != $rez['pid']) {
1135 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1136 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1140 $sql = "UPDATE patient_data SET date = NOW()";
1141 foreach ($new as $key => $value) {
1142 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1145 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1152 function newEmployerData(
1162 return sqlInsert("insert into employer_data set
1163 name='" . add_escape_custom($name) . "',
1164 street='" . add_escape_custom($street) . "',
1165 postal_code='" . add_escape_custom($postal_code) . "',
1166 city='" . add_escape_custom($city) . "',
1167 state='" . add_escape_custom($state) . "',
1168 country='" . add_escape_custom($country) . "',
1169 pid='" . add_escape_custom($pid) . "',
1174 // Create or update employer data from an array.
1176 function updateEmployerData($pid, $new, $create = false)
1178 $colnames = array('name','street','city','state','postal_code','country');
1181 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1182 foreach ($colnames as $key) {
1183 $value = isset($new[$key]) ? $new[$key] : '';
1184 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1187 return sqlInsert("INSERT INTO employer_data SET $set");
1190 $old = getEmployerData($pid);
1192 foreach ($colnames as $key) {
1193 $value = empty($old[$key]) ? '' : $old[$key];
1194 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1195 $value = $new[$key];
1199 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1203 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1204 return sqlInsert("INSERT INTO employer_data SET $set");
1211 // This updates or adds the given insurance data info, while retaining any
1212 // previously added insurance_data rows that should be preserved.
1213 // This does not directly support the maintenance of non-current insurance.
1215 function newInsuranceData(
1219 $policy_number = "",
1222 $subscriber_lname = "",
1223 $subscriber_mname = "",
1224 $subscriber_fname = "",
1225 $subscriber_relationship = "",
1226 $subscriber_ss = "",
1227 $subscriber_DOB = "",
1228 $subscriber_street = "",
1229 $subscriber_postal_code = "",
1230 $subscriber_city = "",
1231 $subscriber_state = "",
1232 $subscriber_country = "",
1233 $subscriber_phone = "",
1234 $subscriber_employer = "",
1235 $subscriber_employer_street = "",
1236 $subscriber_employer_city = "",
1237 $subscriber_employer_postal_code = "",
1238 $subscriber_employer_state = "",
1239 $subscriber_employer_country = "",
1241 $subscriber_sex = "",
1242 $effective_date = "0000-00-00",
1243 $accept_assignment = "TRUE",
1247 if (strlen($type) <= 0) {
1251 // If empty dates were passed, then zero them.
1252 if (empty($effective_date)) {
1253 $effective_date = '0000-00-00';
1255 if (empty($subscriber_DOB)) {
1256 $subscriber_DOB = '0000-00-00';
1259 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1260 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1261 $idrow = sqlFetchArray($idres);
1263 // Replace the most recent entry in any of the following cases:
1264 // * Its effective date is >= this effective date.
1265 // * It is the first entry and it has no (insurance) provider.
1266 // * There is no encounter that is earlier than the new effective date but
1267 // on or after the old effective date.
1268 // Otherwise insert a new entry.
1272 if (strcmp($idrow['date'], $effective_date) > 0) {
1275 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1278 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1279 "WHERE pid = ? AND date < ? AND " .
1280 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1281 if ($ferow['count'] == 0) {
1289 // TBD: This is a bit dangerous in that a typo in entering the effective
1290 // date can wipe out previous insurance history. So we want some data
1291 // entry validation somewhere.
1292 sqlStatement("DELETE FROM insurance_data WHERE " .
1293 "pid = ? AND type = ? AND date >= ? AND " .
1294 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1297 $data['type'] = $type;
1298 $data['provider'] = $provider;
1299 $data['policy_number'] = $policy_number;
1300 $data['group_number'] = $group_number;
1301 $data['plan_name'] = $plan_name;
1302 $data['subscriber_lname'] = $subscriber_lname;
1303 $data['subscriber_mname'] = $subscriber_mname;
1304 $data['subscriber_fname'] = $subscriber_fname;
1305 $data['subscriber_relationship'] = $subscriber_relationship;
1306 $data['subscriber_ss'] = $subscriber_ss;
1307 $data['subscriber_DOB'] = $subscriber_DOB;
1308 $data['subscriber_street'] = $subscriber_street;
1309 $data['subscriber_postal_code'] = $subscriber_postal_code;
1310 $data['subscriber_city'] = $subscriber_city;
1311 $data['subscriber_state'] = $subscriber_state;
1312 $data['subscriber_country'] = $subscriber_country;
1313 $data['subscriber_phone'] = $subscriber_phone;
1314 $data['subscriber_employer'] = $subscriber_employer;
1315 $data['subscriber_employer_city'] = $subscriber_employer_city;
1316 $data['subscriber_employer_street'] = $subscriber_employer_street;
1317 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1318 $data['subscriber_employer_state'] = $subscriber_employer_state;
1319 $data['subscriber_employer_country'] = $subscriber_employer_country;
1320 $data['copay'] = $copay;
1321 $data['subscriber_sex'] = $subscriber_sex;
1322 $data['pid'] = $pid;
1323 $data['date'] = $effective_date;
1324 $data['accept_assignment'] = $accept_assignment;
1325 $data['policy_type'] = $policy_type;
1326 updateInsuranceData($idrow['id'], $data);
1327 return $idrow['id'];
1329 return sqlInsert("INSERT INTO insurance_data SET
1330 type = '" . add_escape_custom($type) . "',
1331 provider = '" . add_escape_custom($provider) . "',
1332 policy_number = '" . add_escape_custom($policy_number) . "',
1333 group_number = '" . add_escape_custom($group_number) . "',
1334 plan_name = '" . add_escape_custom($plan_name) . "',
1335 subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1336 subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1337 subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1338 subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1339 subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1340 subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1341 subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1342 subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1343 subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1344 subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1345 subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1346 subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1347 subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1348 subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1349 subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1350 subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1351 subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1352 subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1353 copay = '" . add_escape_custom($copay) . "',
1354 subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1355 pid = '" . add_escape_custom($pid) . "',
1356 date = '" . add_escape_custom($effective_date) . "',
1357 accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1358 policy_type = '" . add_escape_custom($policy_type) . "'
1363 // This is used internally only.
1364 function updateInsuranceData($id, $new)
1366 $fields = sqlListFields("insurance_data");
1369 foreach ($new as $key => $value) {
1370 if (in_array($key, $fields)) {
1371 $use[$key] = $value;
1375 $sql = "UPDATE insurance_data SET ";
1376 foreach ($use as $key => $value) {
1377 $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1380 $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1385 function newHistoryData($pid, $new = false)
1387 $arraySqlBind = array();
1388 $sql = "insert into history_data set pid = ?, date = NOW()";
1389 array_push($arraySqlBind, $pid);
1391 foreach ($new as $key => $value) {
1392 array_push($arraySqlBind, $value);
1393 $sql .= ", `$key` = ?";
1397 return sqlInsert($sql, $arraySqlBind);
1400 function updateHistoryData($pid, $new)
1402 $real = getHistoryData($pid);
1403 foreach ($new as $key => $value) {
1404 $real[$key] = $value;
1408 // need to unset date, so can reset it below
1409 unset($real['date']);
1411 $arraySqlBind = array();
1412 $sql = "insert into history_data set `date` = NOW(), ";
1413 foreach ($real as $key => $value) {
1414 array_push($arraySqlBind, $value);
1415 $sql .= "`$key` = ?, ";
1418 $sql = substr($sql, 0, -2);
1420 return sqlInsert($sql, $arraySqlBind);
1424 // in months if < 2 years old
1425 // in years if > 2 years old
1426 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1427 // (optional) nowYMD is a date in YYYYMMDD format
1428 function getPatientAge($dobYMD, $nowYMD = null)
1430 // strip any dashes from the DOB
1431 $dobYMD = preg_replace("/-/", "", $dobYMD);
1432 $dobDay = substr($dobYMD, 6, 2);
1433 $dobMonth = substr($dobYMD, 4, 2);
1434 $dobYear = substr($dobYMD, 0, 4);
1436 // set the 'now' date values
1437 if ($nowYMD == null) {
1438 $nowDay = date("d");
1439 $nowMonth = date("m");
1440 $nowYear = date("Y");
1442 $nowDay = substr($nowYMD, 6, 2);
1443 $nowMonth = substr($nowYMD, 4, 2);
1444 $nowYear = substr($nowYMD, 0, 4);
1447 $dayDiff = $nowDay - $dobDay;
1448 $monthDiff = $nowMonth - $dobMonth;
1449 $yearDiff = $nowYear - $dobYear;
1451 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1453 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1458 if ($ageInMonths > 24) {
1460 if (($monthDiff == 0) && ($dayDiff < 0)) {
1462 } else if ($monthDiff < 0) {
1466 $age = "$ageInMonths " . xl('month');
1473 * Wrapper to make sure the clinical rules dates formats corresponds to the
1474 * format expected by getPatientAgeYMD
1476 * @param string $dob date of birth
1477 * @param string $target date to calculate age on
1478 * @return array containing
1479 * age - decimal age in years
1480 * age_in_months - decimal age in months
1481 * ageinYMD - formatted string #y #m #d */
1482 function parseAgeInfo($dob, $target)
1484 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1485 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1487 // Prepare target (Y-M-D H:M:S)
1488 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1490 return getPatientAgeYMD($dateDOB, $dateTarget);
1497 * @return array containing
1498 * age - decimal age in years
1499 * age_in_months - decimal age in months
1500 * ageinYMD - formatted string #y #m #d
1502 function getPatientAgeYMD($dob, $date = null)
1505 if ($date == null) {
1506 $daynow = date("d");
1507 $monthnow = date("m");
1508 $yearnow = date("Y");
1509 $datenow=$yearnow.$monthnow.$daynow;
1511 $datenow=preg_replace("/-/", "", $date);
1512 $yearnow=substr($datenow, 0, 4);
1513 $monthnow=substr($datenow, 4, 2);
1514 $daynow=substr($datenow, 6, 2);
1515 $datenow=$yearnow.$monthnow.$daynow;
1518 $dob=preg_replace("/-/", "", $dob);
1519 $dobyear=substr($dob, 0, 4);
1520 $dobmonth=substr($dob, 4, 2);
1521 $dobday=substr($dob, 6, 2);
1522 $dob=$dobyear.$dobmonth.$dobday;
1524 //to compensate for 30, 31, 28, 29 days/month
1525 $mo=$monthnow; //to avoid confusion with later calculation
1527 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1528 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1529 } // look at April, June, September, November for calculation. These months only have 30 days.
1530 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1531 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1532 if (is_int($check_leap_Y)) {
1534 } //If it true then this is the leap year
1537 } //otherwise, it is not a leap year.
1540 } // other months have 31 days
1542 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1543 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1544 $age_year = $yearnow - $dobyear - 1;
1545 if ($daynow < $dobday) {
1546 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1547 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1549 $months_since_birthday=12 - $dobmonth + $monthnow;
1550 $days_since_dobday=$daynow - $dobday;
1552 } else // if patient has had birthday this calandar year
1554 $age_year = $yearnow - $dobyear;
1555 if ($daynow < $dobday) {
1556 $months_since_birthday=$monthnow - $dobmonth -1;
1557 $days_since_dobday=$nd - $dobday + $daynow;
1559 $months_since_birthday=$monthnow - $dobmonth;
1560 $days_since_dobday=$daynow - $dobday;
1564 $day_as_month_decimal = $days_since_dobday / 30;
1565 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1566 $month_as_year_decimal = $months_since_birthday_float / 12;
1567 $age_float = $age_year + $month_as_year_decimal;
1569 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1570 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1571 $age = round($age_float, 2);
1573 // round the years to 2 floating points
1574 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1575 return compact('age', 'age_in_months', 'ageinYMD');
1578 // Returns Age in days
1579 // in months if < 2 years old
1580 // in years if > 2 years old
1581 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1582 // (optional) nowYMD is a date in YYYYMMDD format
1583 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1587 // strip any dashes from the DOB
1588 $dobYMD = preg_replace("/-/", "", $dobYMD);
1589 $dobDay = substr($dobYMD, 6, 2);
1590 $dobMonth = substr($dobYMD, 4, 2);
1591 $dobYear = substr($dobYMD, 0, 4);
1593 // set the 'now' date values
1594 if ($nowYMD == null) {
1595 $nowDay = date("d");
1596 $nowMonth = date("m");
1597 $nowYear = date("Y");
1599 $nowDay = substr($nowYMD, 6, 2);
1600 $nowMonth = substr($nowYMD, 4, 2);
1601 $nowYear = substr($nowYMD, 0, 4);
1605 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1606 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1607 $timediff = $nowtime - $dobtime;
1608 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1613 * Returns a string to be used to display a patient's age
1615 * @param type $dobYMD
1616 * @param type $asOfYMD
1617 * @return string suitable for displaying patient's age based on preferences
1619 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1621 if ($GLOBALS['age_display_format']=='1') {
1622 $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1623 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1624 return $ageYMD['ageinYMD'];
1626 return getPatientAge($dobYMD, $asOfYMD);
1629 return getPatientAge($dobYMD, $asOfYMD);
1632 function dateToDB($date)
1634 $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1639 // ----------------------------------------------------------------------------
1641 * DROPDOWN FOR COUNTRIES
1643 * build a dropdown with all countries from geo_country_reference
1645 * @param int $selected - id for selected record
1646 * @param string $name - the name/id for select form
1647 * @return void - just echo the html encoded string
1649 function dropdown_countries($selected = 0, $name = 'country_code')
1651 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1653 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1654 while ($row = sqlFetchArray($r)) {
1655 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1656 $string .= "<option value='" . attr($row['countries_id']) . "' $sufix>" . text($row['countries_name']) . "</option>";
1659 $string .= '</select>';
1664 // ----------------------------------------------------------------------------
1666 * DROPDOWN FOR YES/NO
1668 * build a dropdown with two options (yes - 1, no - 0)
1670 * @param int $selected - id for selected record
1671 * @param string $name - the name/id for select form
1672 * @return void - just echo the html encoded string
1674 function dropdown_yesno($selected = 0, $name = 'yesno')
1676 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1678 $selected = (int)$selected;
1679 if ($selected == 0) {
1680 $sel1 = 'selected="selected"';
1683 $sel2 = 'selected="selected"';
1687 $string .= "<option value='0' $sel1>" .xlt('No'). "</option>";
1688 $string .= "<option value='1' $sel2>" .xlt('Yes'). "</option>";
1689 $string .= '</select>';
1694 // ----------------------------------------------------------------------------
1696 * DROPDOWN FOR MALE/FEMALE options
1698 * build a dropdown with three options (unselected/male/female)
1700 * @param int $selected - id for selected record
1701 * @param string $name - the name/id for select form
1702 * @return void - just echo the html encoded string
1704 function dropdown_sex($selected = 0, $name = 'sex')
1706 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1708 if ($selected == 1) {
1709 $sel1 = 'selected="selected"';
1712 } else if ($selected == 2) {
1713 $sel2 = 'selected="selected"';
1717 $sel0 = 'selected="selected"';
1722 $string .= "<option value='0' $sel0>" .xlt('Unselected'). "</option>";
1723 $string .= "<option value='1' $sel1>" .xlt('Male'). "</option>";
1724 $string .= "<option value='2' $sel2>" .xlt('Female'). "</option>";
1725 $string .= '</select>';
1730 // ----------------------------------------------------------------------------
1732 * DROPDOWN FOR MARITAL STATUS
1734 * build a dropdown with marital status
1736 * @param int $selected - id for selected record
1737 * @param string $name - the name/id for select form
1738 * @return void - just echo the html encoded string
1740 function dropdown_marital($selected = 0, $name = 'status')
1742 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1744 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1746 foreach ($statii as $st) {
1747 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1748 $string .= '<option value="' . attr($st) . '" '.$sel.' >' .xlt($st). '</option>';
1751 $string .= '</select>';
1756 // ----------------------------------------------------------------------------
1758 * DROPDOWN FOR PROVIDERS
1760 * build a dropdown with all providers
1762 * @param int $selected - id for selected record
1763 * @param string $name - the name/id for select form
1764 * @return void - just echo the html encoded string
1766 function dropdown_providers($selected = 0, $name = 'status')
1768 $provideri = getProviderInfo();
1770 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1771 $string .= '<option value="">' .xlt('Unassigned'). '</option>';
1772 foreach ($provideri as $s) {
1773 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1774 $string .= '<option value="' . attr($s['id']) . '" '.$sel.' >' . text(ucwords($s['fname']." ".$s['lname'])) . '</option>';
1777 $string .= '</select>';
1782 // ----------------------------------------------------------------------------
1784 * DROPDOWN FOR INSURANCE COMPANIES
1786 * build a dropdown with all insurers
1788 * @param int $selected - id for selected record
1789 * @param string $name - the name/id for select form
1790 * @return void - just echo the html encoded string
1792 function dropdown_insurance($selected = 0, $name = 'iprovider')
1794 $insurancei = getInsuranceProviders();
1796 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1797 $string .= '<option value="0">Onbekend</option>';
1798 foreach ($insurancei as $iid => $iname) {
1799 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1800 $string .= '<option value="' . attr($iid) . '" '.$sel.' >' . text($iname) . '(' . text($iid) . ')</option>';
1803 $string .= '</select>';
1809 // ----------------------------------------------------------------------------
1813 * return the name or the country code, function of arguments
1815 * @param int $country_code
1816 * @param string $country_name
1817 * @return string | int - name or code
1819 function country_code($country_code = 0, $country_name = '')
1822 $sqlBindArray = array();
1823 if ($country_code) {
1824 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = ?";
1825 array_push($sqlBindArray, $country_code);
1827 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = ?";
1828 array_push($sqlBindArray, $country_name);
1831 $db = $GLOBALS['adodb']['db'];
1832 $result = $db->Execute($sql, $sqlBindArray);
1833 if ($result && !$result->EOF) {
1834 $strint = $result->fields['res'];
1840 function DBToDate($date)
1842 $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1847 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1848 * for the given patient on the given date.
1850 * @param int The PID of the patient.
1851 * @param string Date in yyyy-mm-dd format.
1852 * @return array Array of 0-3 insurance_data rows.
1854 function getEffectiveInsurances($patient_id, $encdate)
1857 foreach (array('primary','secondary','tertiary') as $instype) {
1859 "SELECT * FROM insurance_data " .
1860 "WHERE pid = ? AND type = ? " .
1861 "AND date <= ? ORDER BY date DESC LIMIT 1",
1862 array($patient_id, $instype, $encdate)
1864 if (empty($tmp['provider'])) {
1875 * Get all requisition insurance companies
1880 function getAllinsurances($pid)
1883 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1884 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1885 b.name, c.line1, c.line2, c.city, c.state, c.zip
1886 FROM `insurance_data` AS a
1887 RIGHT JOIN insurance_companies AS b
1888 ON a.provider = b.id
1889 RIGHT JOIN addresses AS c
1890 ON a.provider = c.foreign_id
1892 $inco = sqlStatement($sql, array($pid));
1894 while ($icl = sqlFetchArray($inco)) {
1901 * Get the patient's balance due. Normally this excludes amounts that are out
1902 * to insurance. If you want to include what insurance owes, set the second
1903 * parameter to true.
1905 * @param int The PID of the patient.
1906 * @param boolean Indicates if amounts owed by insurance are to be included.
1907 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1908 * @return number The balance.
1910 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1913 $bindarray = array($pid);
1914 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1915 "last_level_closed, stmt_count " .
1916 "FROM form_encounter WHERE pid = ?";
1918 $sqlstatement .= " AND encounter = ?";
1919 array_push($bindarray, $eid);
1921 $feres = sqlStatement($sqlstatement, $bindarray);
1922 while ($ferow = sqlFetchArray($feres)) {
1923 $encounter = $ferow['encounter'];
1924 $dos = substr($ferow['date'], 0, 10);
1925 $insarr = getEffectiveInsurances($pid, $dos);
1926 $inscount = count($insarr);
1927 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1928 // It's out to insurance so only the co-pay might be due.
1930 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1931 "pid = ? AND encounter = ? AND " .
1932 "code_type = 'copay' AND activity = 1",
1933 array($pid, $encounter)
1936 "SELECT SUM(pay_amount) AS payments " .
1937 "FROM ar_activity WHERE " .
1938 "pid = ? AND encounter = ? AND payer_type = 0",
1939 array($pid, $encounter)
1941 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1946 // Including insurance or not out to insurance, everything is due.
1947 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1948 "pid = ? AND encounter = ? AND " .
1949 "activity = 1", array($pid, $encounter));
1950 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1951 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1952 "pid = ? AND encounter = ?", array($pid, $encounter));
1953 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1954 "pid = ? AND encounter = ?", array($pid, $encounter));
1955 $balance += $brow['amount'] + $srow['amount']
1956 - $drow['payments'] - $drow['adjustments'];
1960 return sprintf('%01.2f', $balance);
1963 // Function to check if patient is deceased.
1965 // $pid - patient id
1966 // $date - date checking if deceased (will default to current date if blank)
1968 // If deceased, then will return the number of
1969 // days that patient has been deceased and the deceased date.
1970 // If not deceased, then will return false.
1971 function is_patient_deceased($pid, $date = '')
1974 // Set date to current if not set
1975 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1977 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1978 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1979 "FROM `patient_data` " .
1980 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND
1981 `deceased_date` <= ?", array($date,$pid,$date));
1983 if (empty($results)) {
1984 // Patient is alive, so return false
1987 // Patient is dead, so return the number of days patient has been deceased.
1988 // Don't let it be zero days or else will confuse calls to this function.
1989 if ($results['days_deceased'] === 0) {
1990 $results['days_deceased'] = 1;