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 } elseif ($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 } elseif ($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 } elseif ($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 } elseif (!$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 /* return a patient's name in the format FIRST LAST */
828 function getPatientNameFirstLast($pid)
834 $patientData = getPatientPID(array("pid"=>$pid));
835 if (empty($patientData[0]['lname'])) {
839 $patientName = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
843 /* find patient data by DOB */
844 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
846 $sqlBindArray = array();
847 $where = "DOB like ? ";
848 array_push($sqlBindArray, $DOB."%");
849 if (!empty($GLOBALS['pt_restrict_field'])) {
850 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
851 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
852 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
853 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
854 array_push($sqlBindArray, $_SESSION{"authUser"});
858 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
860 if ($limit != "all") {
861 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
864 $rez = sqlStatement($sql, $sqlBindArray);
865 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
866 $returnval[$iter]=$row;
869 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
873 /* find patient data by SSN */
874 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
876 $sqlBindArray = array();
877 $where = "ss LIKE ?";
878 array_push($sqlBindArray, $ss."%");
879 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
880 if ($limit != "all") {
881 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
884 $rez = sqlStatement($sql, $sqlBindArray);
885 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
886 $returnval[$iter]=$row;
889 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
893 //(CHEMED) Search by phone number
894 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
896 $phone = preg_replace("/[[:punct:]]/", "", $phone);
897 $sqlBindArray = array();
898 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
899 array_push($sqlBindArray, $phone);
900 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
901 if ($limit != "all") {
902 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
905 $rez = sqlStatement($sql, $sqlBindArray);
906 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
907 $returnval[$iter]=$row;
910 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
914 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
916 $sql="select $given from patient_data order by $orderby";
918 if ($limit != "all") {
919 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
922 $rez = sqlStatement($sql);
923 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
924 $returnval[$iter]=$row;
930 //----------------------input functions
931 function newPatientData(
950 $contact_relationship = "",
957 $migrantseasonal = "",
959 $monthly_income = "",
961 $financial_review = "",
975 $drivers_license = "",
982 $referral_source = '';
984 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
985 // Check for brain damage:
986 if ($db_id != $rez['id']) {
987 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
988 text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
992 $fitness = $rez['fitness'];
993 $referral_source = $rez['referral_source'];
996 // Get the default price level.
997 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
998 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
999 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
1001 $query = ("replace into patient_data set
1002 id='" . add_escape_custom($db_id) . "',
1003 title='" . add_escape_custom($title) . "',
1004 fname='" . add_escape_custom($fname) . "',
1005 lname='" . add_escape_custom($lname) . "',
1006 mname='" . add_escape_custom($mname) . "',
1007 sex='" . add_escape_custom($sex) . "',
1008 DOB='" . add_escape_custom($DOB) . "',
1009 street='" . add_escape_custom($street) . "',
1010 postal_code='" . add_escape_custom($postal_code) . "',
1011 city='" . add_escape_custom($city) . "',
1012 state='" . add_escape_custom($state) . "',
1013 country_code='" . add_escape_custom($country_code) . "',
1014 drivers_license='" . add_escape_custom($drivers_license) . "',
1015 ss='" . add_escape_custom($ss) . "',
1016 occupation='" . add_escape_custom($occupation) . "',
1017 phone_home='" . add_escape_custom($phone_home) . "',
1018 phone_biz='" . add_escape_custom($phone_biz) . "',
1019 phone_contact='" . add_escape_custom($phone_contact) . "',
1020 status='" . add_escape_custom($status) . "',
1021 contact_relationship='" . add_escape_custom($contact_relationship) . "',
1022 referrer='" . add_escape_custom($referrer) . "',
1023 referrerID='" . add_escape_custom($referrerID) . "',
1024 email='" . add_escape_custom($email) . "',
1025 language='" . add_escape_custom($language) . "',
1026 ethnoracial='" . add_escape_custom($ethnoracial) . "',
1027 interpretter='" . add_escape_custom($interpretter) . "',
1028 migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1029 family_size='" . add_escape_custom($family_size) . "',
1030 monthly_income='" . add_escape_custom($monthly_income) . "',
1031 homeless='" . add_escape_custom($homeless) . "',
1032 financial_review='" . add_escape_custom($financial_review) . "',
1033 pubpid='" . add_escape_custom($pubpid) . "',
1034 pid= '" . add_escape_custom($pid) . "',
1035 providerID = '" . add_escape_custom($providerID) . "',
1036 genericname1 = '" . add_escape_custom($genericname1) . "',
1037 genericval1 = '" . add_escape_custom($genericval1) . "',
1038 genericname2 = '" . add_escape_custom($genericname2) . "',
1039 genericval2 = '" . add_escape_custom($genericval2) . "',
1040 billing_note= '" . add_escape_custom($billing_note) . "',
1041 phone_cell = '" . add_escape_custom($phone_cell) . "',
1042 pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1043 hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1044 hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1045 hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1046 hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1047 squad = '" . add_escape_custom($squad) . "',
1048 fitness='" . add_escape_custom($fitness) . "',
1049 referral_source='" . add_escape_custom($referral_source) . "',
1050 regdate='" . add_escape_custom($regdate) . "',
1051 pricelevel='" . add_escape_custom($pricelevel) . "',
1054 $id = sqlInsert($query);
1057 // find the last inserted id for new patient case
1058 $db_id = getSqlLastID();
1061 $foo = sqlQuery("select pid from patient_data where id=? order by date limit 0,1", array($id));
1066 // Supported input date formats are:
1068 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1070 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1072 function fixDate($date, $default = "0000-00-00")
1074 $fixed_date = $default;
1075 $date = trim($date);
1076 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1077 $dmy = preg_split("'[/.-]'", $date);
1079 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1081 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1082 if ($dmy[2] < 1000) {
1086 if ($dmy[2] < 1910) {
1091 // phone_country_code indicates format of ambiguous input dates.
1092 if ($GLOBALS['phone_country_code'] == 1) {
1093 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1095 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1103 function pdValueOrNull($key, $value)
1105 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1106 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1107 (empty($value) || $value == '0000-00-00')) {
1110 return "'" . add_escape_custom($value) . "'";
1114 // Create or update patient data from an array.
1116 function updatePatientData($pid, $new, $create = false)
1118 /*******************************************************************
1119 $real = getPatientData($pid);
1120 foreach ($new as $key => $value)
1121 $real[$key] = $value;
1122 $real['date'] = "'+NOW()+'";
1124 $sql = "insert into patient_data set ";
1125 foreach ($real as $key => $value)
1126 $sql .= $key." = '$value', ";
1127 $sql = substr($sql, 0, -2);
1128 return sqlInsert($sql);
1129 *******************************************************************/
1131 // The above was broken, though seems intent to insert a new patient_data
1132 // row for each update. A good idea, but nothing is doing that yet so
1133 // the code below does not yet attempt it.
1136 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1137 foreach ($new as $key => $value) {
1142 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1145 $db_id = sqlInsert($sql);
1147 $db_id = $new['id'];
1148 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1149 // Check for brain damage:
1150 if ($pid != $rez['pid']) {
1151 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1152 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1156 $sql = "UPDATE patient_data SET date = NOW()";
1157 foreach ($new as $key => $value) {
1158 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1161 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1168 function newEmployerData(
1178 return sqlInsert("insert into employer_data set
1179 name='" . add_escape_custom($name) . "',
1180 street='" . add_escape_custom($street) . "',
1181 postal_code='" . add_escape_custom($postal_code) . "',
1182 city='" . add_escape_custom($city) . "',
1183 state='" . add_escape_custom($state) . "',
1184 country='" . add_escape_custom($country) . "',
1185 pid='" . add_escape_custom($pid) . "',
1190 // Create or update employer data from an array.
1192 function updateEmployerData($pid, $new, $create = false)
1194 $colnames = array('name','street','city','state','postal_code','country');
1197 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1198 foreach ($colnames as $key) {
1199 $value = isset($new[$key]) ? $new[$key] : '';
1200 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1203 return sqlInsert("INSERT INTO employer_data SET $set");
1206 $old = getEmployerData($pid);
1208 foreach ($colnames as $key) {
1209 $value = empty($old[$key]) ? '' : $old[$key];
1210 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1211 $value = $new[$key];
1215 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1219 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1220 return sqlInsert("INSERT INTO employer_data SET $set");
1227 // This updates or adds the given insurance data info, while retaining any
1228 // previously added insurance_data rows that should be preserved.
1229 // This does not directly support the maintenance of non-current insurance.
1231 function newInsuranceData(
1235 $policy_number = "",
1238 $subscriber_lname = "",
1239 $subscriber_mname = "",
1240 $subscriber_fname = "",
1241 $subscriber_relationship = "",
1242 $subscriber_ss = "",
1243 $subscriber_DOB = "",
1244 $subscriber_street = "",
1245 $subscriber_postal_code = "",
1246 $subscriber_city = "",
1247 $subscriber_state = "",
1248 $subscriber_country = "",
1249 $subscriber_phone = "",
1250 $subscriber_employer = "",
1251 $subscriber_employer_street = "",
1252 $subscriber_employer_city = "",
1253 $subscriber_employer_postal_code = "",
1254 $subscriber_employer_state = "",
1255 $subscriber_employer_country = "",
1257 $subscriber_sex = "",
1258 $effective_date = "0000-00-00",
1259 $accept_assignment = "TRUE",
1263 if (strlen($type) <= 0) {
1267 // If empty dates were passed, then zero them.
1268 if (empty($effective_date)) {
1269 $effective_date = '0000-00-00';
1271 if (empty($subscriber_DOB)) {
1272 $subscriber_DOB = '0000-00-00';
1275 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1276 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1277 $idrow = sqlFetchArray($idres);
1279 // Replace the most recent entry in any of the following cases:
1280 // * Its effective date is >= this effective date.
1281 // * It is the first entry and it has no (insurance) provider.
1282 // * There is no encounter that is earlier than the new effective date but
1283 // on or after the old effective date.
1284 // Otherwise insert a new entry.
1288 if (strcmp($idrow['date'], $effective_date) > 0) {
1291 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1294 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1295 "WHERE pid = ? AND date < ? AND " .
1296 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1297 if ($ferow['count'] == 0) {
1305 // TBD: This is a bit dangerous in that a typo in entering the effective
1306 // date can wipe out previous insurance history. So we want some data
1307 // entry validation somewhere.
1308 sqlStatement("DELETE FROM insurance_data WHERE " .
1309 "pid = ? AND type = ? AND date >= ? AND " .
1310 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1313 $data['type'] = $type;
1314 $data['provider'] = $provider;
1315 $data['policy_number'] = $policy_number;
1316 $data['group_number'] = $group_number;
1317 $data['plan_name'] = $plan_name;
1318 $data['subscriber_lname'] = $subscriber_lname;
1319 $data['subscriber_mname'] = $subscriber_mname;
1320 $data['subscriber_fname'] = $subscriber_fname;
1321 $data['subscriber_relationship'] = $subscriber_relationship;
1322 $data['subscriber_ss'] = $subscriber_ss;
1323 $data['subscriber_DOB'] = $subscriber_DOB;
1324 $data['subscriber_street'] = $subscriber_street;
1325 $data['subscriber_postal_code'] = $subscriber_postal_code;
1326 $data['subscriber_city'] = $subscriber_city;
1327 $data['subscriber_state'] = $subscriber_state;
1328 $data['subscriber_country'] = $subscriber_country;
1329 $data['subscriber_phone'] = $subscriber_phone;
1330 $data['subscriber_employer'] = $subscriber_employer;
1331 $data['subscriber_employer_city'] = $subscriber_employer_city;
1332 $data['subscriber_employer_street'] = $subscriber_employer_street;
1333 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1334 $data['subscriber_employer_state'] = $subscriber_employer_state;
1335 $data['subscriber_employer_country'] = $subscriber_employer_country;
1336 $data['copay'] = $copay;
1337 $data['subscriber_sex'] = $subscriber_sex;
1338 $data['pid'] = $pid;
1339 $data['date'] = $effective_date;
1340 $data['accept_assignment'] = $accept_assignment;
1341 $data['policy_type'] = $policy_type;
1342 updateInsuranceData($idrow['id'], $data);
1343 return $idrow['id'];
1345 return sqlInsert("INSERT INTO insurance_data SET
1346 type = '" . add_escape_custom($type) . "',
1347 provider = '" . add_escape_custom($provider) . "',
1348 policy_number = '" . add_escape_custom($policy_number) . "',
1349 group_number = '" . add_escape_custom($group_number) . "',
1350 plan_name = '" . add_escape_custom($plan_name) . "',
1351 subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1352 subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1353 subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1354 subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1355 subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1356 subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1357 subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1358 subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1359 subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1360 subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1361 subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1362 subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1363 subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1364 subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1365 subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1366 subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1367 subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1368 subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1369 copay = '" . add_escape_custom($copay) . "',
1370 subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1371 pid = '" . add_escape_custom($pid) . "',
1372 date = '" . add_escape_custom($effective_date) . "',
1373 accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1374 policy_type = '" . add_escape_custom($policy_type) . "'
1379 // This is used internally only.
1380 function updateInsuranceData($id, $new)
1382 $fields = sqlListFields("insurance_data");
1385 foreach ($new as $key => $value) {
1386 if (in_array($key, $fields)) {
1387 $use[$key] = $value;
1391 $sql = "UPDATE insurance_data SET ";
1392 foreach ($use as $key => $value) {
1393 $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1396 $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1401 function newHistoryData($pid, $new = false)
1403 $arraySqlBind = array();
1404 $sql = "insert into history_data set pid = ?, date = NOW()";
1405 array_push($arraySqlBind, $pid);
1407 foreach ($new as $key => $value) {
1408 array_push($arraySqlBind, $value);
1409 $sql .= ", `$key` = ?";
1413 return sqlInsert($sql, $arraySqlBind);
1416 function updateHistoryData($pid, $new)
1418 $real = getHistoryData($pid);
1419 foreach ($new as $key => $value) {
1420 $real[$key] = $value;
1424 // need to unset date, so can reset it below
1425 unset($real['date']);
1427 $arraySqlBind = array();
1428 $sql = "insert into history_data set `date` = NOW(), ";
1429 foreach ($real as $key => $value) {
1430 array_push($arraySqlBind, $value);
1431 $sql .= "`$key` = ?, ";
1434 $sql = substr($sql, 0, -2);
1436 return sqlInsert($sql, $arraySqlBind);
1440 // in months if < 2 years old
1441 // in years if > 2 years old
1442 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1443 // (optional) nowYMD is a date in YYYYMMDD format
1444 function getPatientAge($dobYMD, $nowYMD = null)
1446 // strip any dashes from the DOB
1447 $dobYMD = preg_replace("/-/", "", $dobYMD);
1448 $dobDay = substr($dobYMD, 6, 2);
1449 $dobMonth = substr($dobYMD, 4, 2);
1450 $dobYear = substr($dobYMD, 0, 4);
1452 // set the 'now' date values
1453 if ($nowYMD == null) {
1454 $nowDay = date("d");
1455 $nowMonth = date("m");
1456 $nowYear = date("Y");
1458 $nowDay = substr($nowYMD, 6, 2);
1459 $nowMonth = substr($nowYMD, 4, 2);
1460 $nowYear = substr($nowYMD, 0, 4);
1463 $dayDiff = $nowDay - $dobDay;
1464 $monthDiff = $nowMonth - $dobMonth;
1465 $yearDiff = $nowYear - $dobYear;
1467 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1469 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1474 if ($ageInMonths > 24) {
1476 if (($monthDiff == 0) && ($dayDiff < 0)) {
1478 } elseif ($monthDiff < 0) {
1482 $age = "$ageInMonths " . xl('month');
1489 * Wrapper to make sure the clinical rules dates formats corresponds to the
1490 * format expected by getPatientAgeYMD
1492 * @param string $dob date of birth
1493 * @param string $target date to calculate age on
1494 * @return array containing
1495 * age - decimal age in years
1496 * age_in_months - decimal age in months
1497 * ageinYMD - formatted string #y #m #d */
1498 function parseAgeInfo($dob, $target)
1500 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1501 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1503 // Prepare target (Y-M-D H:M:S)
1504 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1506 return getPatientAgeYMD($dateDOB, $dateTarget);
1513 * @return array containing
1514 * age - decimal age in years
1515 * age_in_months - decimal age in months
1516 * ageinYMD - formatted string #y #m #d
1518 function getPatientAgeYMD($dob, $date = null)
1521 if ($date == null) {
1522 $daynow = date("d");
1523 $monthnow = date("m");
1524 $yearnow = date("Y");
1525 $datenow=$yearnow.$monthnow.$daynow;
1527 $datenow=preg_replace("/-/", "", $date);
1528 $yearnow=substr($datenow, 0, 4);
1529 $monthnow=substr($datenow, 4, 2);
1530 $daynow=substr($datenow, 6, 2);
1531 $datenow=$yearnow.$monthnow.$daynow;
1534 $dob=preg_replace("/-/", "", $dob);
1535 $dobyear=substr($dob, 0, 4);
1536 $dobmonth=substr($dob, 4, 2);
1537 $dobday=substr($dob, 6, 2);
1538 $dob=$dobyear.$dobmonth.$dobday;
1540 //to compensate for 30, 31, 28, 29 days/month
1541 $mo=$monthnow; //to avoid confusion with later calculation
1543 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1544 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1545 } // look at April, June, September, November for calculation. These months only have 30 days.
1546 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1547 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1548 if (is_int($check_leap_Y)) {
1550 } //If it true then this is the leap year
1553 } //otherwise, it is not a leap year.
1556 } // other months have 31 days
1558 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1559 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1560 $age_year = $yearnow - $dobyear - 1;
1561 if ($daynow < $dobday) {
1562 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1563 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1565 $months_since_birthday=12 - $dobmonth + $monthnow;
1566 $days_since_dobday=$daynow - $dobday;
1568 } else // if patient has had birthday this calandar year
1570 $age_year = $yearnow - $dobyear;
1571 if ($daynow < $dobday) {
1572 $months_since_birthday=$monthnow - $dobmonth -1;
1573 $days_since_dobday=$nd - $dobday + $daynow;
1575 $months_since_birthday=$monthnow - $dobmonth;
1576 $days_since_dobday=$daynow - $dobday;
1580 $day_as_month_decimal = $days_since_dobday / 30;
1581 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1582 $month_as_year_decimal = $months_since_birthday_float / 12;
1583 $age_float = $age_year + $month_as_year_decimal;
1585 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1586 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1587 $age = round($age_float, 2);
1589 // round the years to 2 floating points
1590 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1591 return compact('age', 'age_in_months', 'ageinYMD');
1594 // Returns Age in days
1595 // in months if < 2 years old
1596 // in years if > 2 years old
1597 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1598 // (optional) nowYMD is a date in YYYYMMDD format
1599 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1603 // strip any dashes from the DOB
1604 $dobYMD = preg_replace("/-/", "", $dobYMD);
1605 $dobDay = substr($dobYMD, 6, 2);
1606 $dobMonth = substr($dobYMD, 4, 2);
1607 $dobYear = substr($dobYMD, 0, 4);
1609 // set the 'now' date values
1610 if ($nowYMD == null) {
1611 $nowDay = date("d");
1612 $nowMonth = date("m");
1613 $nowYear = date("Y");
1615 $nowDay = substr($nowYMD, 6, 2);
1616 $nowMonth = substr($nowYMD, 4, 2);
1617 $nowYear = substr($nowYMD, 0, 4);
1621 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1622 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1623 $timediff = $nowtime - $dobtime;
1624 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1629 * Returns a string to be used to display a patient's age
1631 * @param type $dobYMD
1632 * @param type $asOfYMD
1633 * @return string suitable for displaying patient's age based on preferences
1635 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1637 if ($GLOBALS['age_display_format']=='1') {
1638 $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1639 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1640 return $ageYMD['ageinYMD'];
1642 return getPatientAge($dobYMD, $asOfYMD);
1645 return getPatientAge($dobYMD, $asOfYMD);
1648 function dateToDB($date)
1650 $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1655 // ----------------------------------------------------------------------------
1657 * DROPDOWN FOR COUNTRIES
1659 * build a dropdown with all countries from geo_country_reference
1661 * @param int $selected - id for selected record
1662 * @param string $name - the name/id for select form
1663 * @return void - just echo the html encoded string
1665 function dropdown_countries($selected = 0, $name = 'country_code')
1667 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1669 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1670 while ($row = sqlFetchArray($r)) {
1671 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1672 $string .= "<option value='" . attr($row['countries_id']) . "' $sufix>" . text($row['countries_name']) . "</option>";
1675 $string .= '</select>';
1680 // ----------------------------------------------------------------------------
1682 * DROPDOWN FOR YES/NO
1684 * build a dropdown with two options (yes - 1, no - 0)
1686 * @param int $selected - id for selected record
1687 * @param string $name - the name/id for select form
1688 * @return void - just echo the html encoded string
1690 function dropdown_yesno($selected = 0, $name = 'yesno')
1692 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1694 $selected = (int)$selected;
1695 if ($selected == 0) {
1696 $sel1 = 'selected="selected"';
1699 $sel2 = 'selected="selected"';
1703 $string .= "<option value='0' $sel1>" .xlt('No'). "</option>";
1704 $string .= "<option value='1' $sel2>" .xlt('Yes'). "</option>";
1705 $string .= '</select>';
1710 // ----------------------------------------------------------------------------
1712 * DROPDOWN FOR MALE/FEMALE options
1714 * build a dropdown with three options (unselected/male/female)
1716 * @param int $selected - id for selected record
1717 * @param string $name - the name/id for select form
1718 * @return void - just echo the html encoded string
1720 function dropdown_sex($selected = 0, $name = 'sex')
1722 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1724 if ($selected == 1) {
1725 $sel1 = 'selected="selected"';
1728 } elseif ($selected == 2) {
1729 $sel2 = 'selected="selected"';
1733 $sel0 = 'selected="selected"';
1738 $string .= "<option value='0' $sel0>" .xlt('Unselected'). "</option>";
1739 $string .= "<option value='1' $sel1>" .xlt('Male'). "</option>";
1740 $string .= "<option value='2' $sel2>" .xlt('Female'). "</option>";
1741 $string .= '</select>';
1746 // ----------------------------------------------------------------------------
1748 * DROPDOWN FOR MARITAL STATUS
1750 * build a dropdown with marital status
1752 * @param int $selected - id for selected record
1753 * @param string $name - the name/id for select form
1754 * @return void - just echo the html encoded string
1756 function dropdown_marital($selected = 0, $name = 'status')
1758 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1760 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1762 foreach ($statii as $st) {
1763 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1764 $string .= '<option value="' . attr($st) . '" '.$sel.' >' .xlt($st). '</option>';
1767 $string .= '</select>';
1772 // ----------------------------------------------------------------------------
1774 * DROPDOWN FOR PROVIDERS
1776 * build a dropdown with all providers
1778 * @param int $selected - id for selected record
1779 * @param string $name - the name/id for select form
1780 * @return void - just echo the html encoded string
1782 function dropdown_providers($selected = 0, $name = 'status')
1784 $provideri = getProviderInfo();
1786 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1787 $string .= '<option value="">' .xlt('Unassigned'). '</option>';
1788 foreach ($provideri as $s) {
1789 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1790 $string .= '<option value="' . attr($s['id']) . '" '.$sel.' >' . text(ucwords($s['fname']." ".$s['lname'])) . '</option>';
1793 $string .= '</select>';
1798 // ----------------------------------------------------------------------------
1800 * DROPDOWN FOR INSURANCE COMPANIES
1802 * build a dropdown with all insurers
1804 * @param int $selected - id for selected record
1805 * @param string $name - the name/id for select form
1806 * @return void - just echo the html encoded string
1808 function dropdown_insurance($selected = 0, $name = 'iprovider')
1810 $insurancei = getInsuranceProviders();
1812 $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1813 $string .= '<option value="0">Onbekend</option>';
1814 foreach ($insurancei as $iid => $iname) {
1815 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1816 $string .= '<option value="' . attr($iid) . '" '.$sel.' >' . text($iname) . '(' . text($iid) . ')</option>';
1819 $string .= '</select>';
1825 // ----------------------------------------------------------------------------
1829 * return the name or the country code, function of arguments
1831 * @param int $country_code
1832 * @param string $country_name
1833 * @return string | int - name or code
1835 function country_code($country_code = 0, $country_name = '')
1838 $sqlBindArray = array();
1839 if ($country_code) {
1840 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = ?";
1841 array_push($sqlBindArray, $country_code);
1843 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = ?";
1844 array_push($sqlBindArray, $country_name);
1847 $db = $GLOBALS['adodb']['db'];
1848 $result = $db->Execute($sql, $sqlBindArray);
1849 if ($result && !$result->EOF) {
1850 $strint = $result->fields['res'];
1856 function DBToDate($date)
1858 $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1863 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1864 * for the given patient on the given date.
1866 * @param int The PID of the patient.
1867 * @param string Date in yyyy-mm-dd format.
1868 * @return array Array of 0-3 insurance_data rows.
1870 function getEffectiveInsurances($patient_id, $encdate)
1873 foreach (array('primary','secondary','tertiary') as $instype) {
1875 "SELECT * FROM insurance_data " .
1876 "WHERE pid = ? AND type = ? " .
1877 "AND date <= ? ORDER BY date DESC LIMIT 1",
1878 array($patient_id, $instype, $encdate)
1880 if (empty($tmp['provider'])) {
1891 * Get all requisition insurance companies
1896 function getAllinsurances($pid)
1899 $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number,
1900 a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer,
1901 b.name, c.line1, c.line2, c.city, c.state, c.zip
1902 FROM `insurance_data` AS a
1903 RIGHT JOIN insurance_companies AS b
1904 ON a.provider = b.id
1905 RIGHT JOIN addresses AS c
1906 ON a.provider = c.foreign_id
1908 $inco = sqlStatement($sql, array($pid));
1910 while ($icl = sqlFetchArray($inco)) {
1917 * Get the patient's balance due. Normally this excludes amounts that are out
1918 * to insurance. If you want to include what insurance owes, set the second
1919 * parameter to true.
1921 * @param int The PID of the patient.
1922 * @param boolean Indicates if amounts owed by insurance are to be included.
1923 * @param int Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1924 * @return number The balance.
1926 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1929 $bindarray = array($pid);
1930 $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1931 "last_level_closed, stmt_count " .
1932 "FROM form_encounter WHERE pid = ?";
1934 $sqlstatement .= " AND encounter = ?";
1935 array_push($bindarray, $eid);
1937 $feres = sqlStatement($sqlstatement, $bindarray);
1938 while ($ferow = sqlFetchArray($feres)) {
1939 $encounter = $ferow['encounter'];
1940 $dos = substr($ferow['date'], 0, 10);
1941 $insarr = getEffectiveInsurances($pid, $dos);
1942 $inscount = count($insarr);
1943 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1944 // It's out to insurance so only the co-pay might be due.
1946 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1947 "pid = ? AND encounter = ? AND " .
1948 "code_type = 'copay' AND activity = 1",
1949 array($pid, $encounter)
1952 "SELECT SUM(pay_amount) AS payments " .
1953 "FROM ar_activity WHERE " .
1954 "pid = ? AND encounter = ? AND payer_type = 0",
1955 array($pid, $encounter)
1957 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1962 // Including insurance or not out to insurance, everything is due.
1963 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1964 "pid = ? AND encounter = ? AND " .
1965 "activity = 1", array($pid, $encounter));
1966 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1967 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1968 "pid = ? AND encounter = ?", array($pid, $encounter));
1969 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1970 "pid = ? AND encounter = ?", array($pid, $encounter));
1971 $balance += $brow['amount'] + $srow['amount']
1972 - $drow['payments'] - $drow['adjustments'];
1976 return sprintf('%01.2f', $balance);
1979 // Function to check if patient is deceased.
1981 // $pid - patient id
1982 // $date - date checking if deceased (will default to current date if blank)
1984 // If deceased, then will return the number of
1985 // days that patient has been deceased and the deceased date.
1986 // If not deceased, then will return false.
1987 function is_patient_deceased($pid, $date = '')
1990 // Set date to current if not set
1991 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1993 // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1994 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1995 "FROM `patient_data` " .
1996 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND
1997 `deceased_date` <= ?", array($date,$pid,$date));
1999 if (empty($results)) {
2000 // Patient is alive, so return false
2003 // Patient is dead, so return the number of days patient has been deceased.
2004 // Don't let it be zero days or else will confuse calls to this function.
2005 if ($results['days_deceased'] === 0) {
2006 $results['days_deceased'] = 1;