3 * patient.inc includes functions for manipulating patient information.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
11 use OpenEMR\Services\FacilityService;
13 $facilityService = new FacilityService();
15 // These are for sports team use:
16 $PLAYER_FITNESSES = array(
19 xl('Restricted Training'),
23 xl('International Duty')
25 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
27 // Hard-coding this array because its values and meanings are fixed by the 837p
28 // standard and we don't want people messing with them.
29 $policy_types = array(
31 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
32 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
33 '14' => xl('No-fault Insurance including Auto is Primary'),
34 '15' => xl('Worker`s Compensation'),
35 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
36 '41' => xl('Black Lung'),
37 '42' => xl('Veteran`s Administration'),
38 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
39 '47' => xl('Other Liability Insurance is Primary'),
43 * Get a patient's demographic data.
45 * @param int $pid The PID of the patient
46 * @param string $given an optional subsection of the patient's demographic
48 * @return array The requested subsection of a patient's demographic data.
49 * If no subsection was given, returns everything, with the
50 * date of birth as the last field.
52 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
54 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
55 return sqlQuery($sql, array($pid));
58 function getLanguages()
60 $returnval = array('','english');
61 $sql = "select distinct lower(language) as language from patient_data";
62 $rez = sqlStatement($sql);
63 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
64 if (($row["language"] != "english") && ($row["language"] != "")) {
65 array_push($returnval, $row["language"]);
72 function getInsuranceProvider($ins_id)
75 $sql = "select name from insurance_companies where id=?";
76 $row = sqlQuery($sql, array($ins_id));
80 function getInsuranceProviders()
85 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
86 $rez = sqlStatement($sql);
87 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
88 $returnval[$row['id']] = $row['name'];
90 } // Please leave this here. I have a user who wants to see zip codes and PO
91 // box numbers listed along with the insurance company names, as many companies
92 // have different billing addresses for different plans. -- Rod Roark
95 $sql = "select insurance_companies.name, insurance_companies.id, " .
96 "addresses.zip, addresses.line1 " .
97 "from insurance_companies, addresses " .
98 "where addresses.foreign_id = insurance_companies.id " .
99 "order by insurance_companies.name, addresses.zip";
101 $rez = sqlStatement($sql);
103 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
104 preg_match("/\d+/", $row['line1'], $matches);
105 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
106 "," . $matches[0] . ")";
113 function getInsuranceProvidersExtra()
115 $returnval = array();
116 // add a global and if for where to allow inactive inscompanies
118 $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
119 addresses.state, addresses.zip
120 FROM insurance_companies, addresses
121 WHERE addresses.foreign_id = insurance_companies.id
122 AND insurance_companies.inactive != 1
123 ORDER BY insurance_companies.name, addresses.zip";
125 $rez = sqlStatement($sql);
127 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
128 switch ($GLOBALS['insurance_information']) {
129 case $GLOBALS['insurance_information'] = '0':
130 $returnval[$row['id']] = $row['name'];
132 case $GLOBALS['insurance_information'] = '1':
133 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
135 case $GLOBALS['insurance_information'] = '2':
136 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
138 case $GLOBALS['insurance_information'] = '3':
139 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
141 case $GLOBALS['insurance_information'] = '4':
142 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
143 ", " . $row['zip'] . ")";
145 case $GLOBALS['insurance_information'] = '5':
146 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
147 ", " . $row['state'] . ", " . $row['zip'] . ")";
149 case $GLOBALS['insurance_information'] = '6':
150 preg_match("/\d+/", $row['line1'], $matches);
151 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
152 "," . $matches[0] . ")";
160 function getProviders()
162 $returnval = array();
163 $sql = "select fname, lname, suffix from users where authorized = 1 and " .
164 "active = 1 and username != ''";
165 $rez = sqlStatement($sql);
166 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
167 if (($row["fname"] != "") && ($row["lname"] != "")) {
168 if ($row["suffix"] != "") {
169 $row["lname"] .= ", ".$row["suffix"];
172 array_push($returnval, $row["fname"] . " " . $row["lname"]);
179 // ----------------------------------------------------------------------------
180 // Get one facility row. If the ID is not specified, then get either the
181 // "main" (billing) facility, or the default facility of the currently
182 // logged-in user. This was created to support genFacilityTitle() but
183 // may find additional uses.
185 function getFacility($facid = 0)
187 global $facilityService;
192 $facility = $facilityService->getById($facid);
193 } else if ($facid == 0) {
194 $facility = $facilityService->getPrimaryBillingLocation();
196 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
202 // Generate a report title including report name and facility name, address
205 function genFacilityTitle($repname = '', $facid = 0)
208 $s .= "<table class='ftitletable'>\n";
211 $s .= " <td class='ftitlecell1'>$repname</td>\n";
213 $s .= " <td class='ftitlecell1'>$logo</td>\n";
214 $s .= " <td class='ftitlecellm'>$repname</td>\n";
216 $s .= " <td class='ftitlecell2'>\n";
217 $r = getFacility($facid);
219 $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
221 $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
224 if ($r['city'] || $r['state'] || $r['postal_code']) {
227 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
235 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
238 if ($r['postal_code']) {
239 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
245 if ($r['country_code']) {
246 $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
249 if (preg_match('/[1-9]/', $r['phone'])) {
250 $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
263 returns all facilities or just the id for the first one
264 (FACILITY FILTERING (lemonsoftware))
266 @param string - if 'first' return first facility ordered by id
267 @return array | int for 'first' case
269 function getFacilities($first = '')
271 global $facilityService;
273 $fres = $facilityService->getAll();
275 if ($first == 'first') {
276 return $fres[0]['id'];
283 GET SERVICE FACILITIES
285 returns all service_location facilities or just the id for the first one
286 (FACILITY FILTERING (CHEMED))
288 @param string - if 'first' return first facility ordered by id
289 @return array | int for 'first' case
291 function getServiceFacilities($first = '')
293 global $facilityService;
295 $fres = $facilityService->getAllServiceLocations();
297 if ($first == 'first') {
298 return $fres[0]['id'];
304 //(CHEMED) facility filter
305 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
308 if ($providers_only === 'any') {
309 $param1 = " AND authorized = 1 AND active = 1 ";
310 } else if ($providers_only) {
311 $param1 = " AND authorized = 1 AND calendar = 1 ";
314 //--------------------------------
315 //(CHEMED) facility filter
318 if ($GLOBALS['restrict_user_facility']) {
319 $param2 = " AND (facility_id = $facility
323 where tablename = 'users'
328 $param2 = " AND facility_id = $facility ";
332 //--------------------------------
335 if ($providerID == "%") {
339 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
340 "from users where username != '' and active = 1 and id $command '" .
341 add_escape_custom($providerID) . "' " . $param1 . $param2;
342 // sort by last name -- JRM June 2008
343 $query .= " ORDER BY lname, fname ";
344 $rez = sqlStatement($query);
345 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
346 $returnval[$iter]=$row;
349 //if only one result returned take the key/value pairs in array [0] and merge them down into
350 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
353 $akeys = array_keys($returnval[0]);
354 foreach ($akeys as $key) {
355 $returnval[0][$key] = $returnval[0][$key];
362 //same as above but does not reduce if only 1 row returned
363 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
366 if ($providers_only) {
367 $param1 = "AND authorized=1";
371 if ($providerID == "%") {
375 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
376 "from users where active = 1 and username != '' and id $command '" .
377 add_escape_custom($providerID) . "' " . $param1;
379 $rez = sqlStatement($query);
380 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
381 $returnval[$iter]=$row;
387 function getProviderName($providerID)
389 $pi = getProviderInfo($providerID, 'any');
390 if (strlen($pi[0]["lname"]) > 0) {
391 if (strlen($pi[0]["suffix"]) > 0) {
392 $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
395 return $pi[0]['fname'] . " " . $pi[0]['lname'];
401 function getProviderId($providerName)
403 $query = "select id from users where username = ?";
404 $rez = sqlStatement($query, array($providerName));
405 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
406 $returnval[$iter]=$row;
412 function getEthnoRacials()
414 $returnval = array("");
415 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
416 $rez = sqlStatement($sql);
417 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
418 if (($row["ethnoracial"] != "")) {
419 array_push($returnval, $row["ethnoracial"]);
426 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
429 if ($dateStart && $dateEnd) {
430 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
431 } else if ($dateStart && !$dateEnd) {
432 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
433 } else if (!$dateStart && $dateEnd) {
434 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
436 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
439 if ($given == 'tobacco') {
440 $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));
446 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
447 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
449 $sql = "select $given from insurance_data as insd " .
450 "left join insurance_companies as ic on ic.id = insd.provider " .
451 "where pid = ? and type = ? order by date DESC limit 1";
452 return sqlQuery($sql, array($pid, $type));
455 function getInsuranceDataByDate(
459 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
461 // this must take the date in the following manner: YYYY-MM-DD
462 // this function recalls the insurance value that was most recently enterred from the
463 // given date. it will call up most recent records up to and on the date given,
464 // but not records enterred after the given date
465 $sql = "select $given from insurance_data as insd " .
466 "left join insurance_companies as ic on ic.id = provider " .
467 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
468 "type=? order by date DESC limit 1";
469 return sqlQuery($sql, array($pid,$date,$type));
472 function getEmployerData($pid, $given = "*")
474 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
475 return sqlQuery($sql, array($pid));
478 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
480 // When the limit is exceeded, find out what the unlimited count would be.
481 $GLOBALS['PATIENT_INC_COUNT'] = $count;
482 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
483 if ($limit != "all") {
484 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
485 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
490 * Allow the last name to be followed by a comma and some part of a first name(can
491 * also place middle name after the first name with a space separating them)
492 * Allows comma alone followed by some part of a first name(can also place middle name
493 * after the first name with a space separating them).
494 * Allows comma alone preceded by some part of a last name.
495 * If no comma or space, then will search both last name and first name.
496 * If the first letter of either name is capital, searches for name starting
497 * with given substring (the expected behavior). If it is lower case, it
498 * searches for the substring anywhere in the name. This applies to either
499 * last name, first name, and middle name.
500 * Also allows first name followed by middle and/or last name when separated by spaces.
501 * @param string $term
502 * @param string $given
503 * @param string $orderby
504 * @param string $limit
505 * @param string $start
508 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")
510 $names = getPatientNameSplit($term);
512 foreach ($names as $key => $val) {
514 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
515 $names[$key] = '%' . $val . '%';
517 $names[$key] = $val . '%';
522 // Debugging section below
523 //if(array_key_exists('first',$names)) {
524 // error_log("first name search term :".$names['first']);
526 //if(array_key_exists('middle',$names)) {
527 // error_log("middle name search term :".$names['middle']);
529 //if(array_key_exists('last',$names)) {
530 // error_log("last name search term :".$names['last']);
532 // Debugging section above
534 $sqlBindArray = array();
535 if (array_key_exists('last', $names) && $names['last'] == '') {
536 // Do not search last name
537 $where = "fname LIKE ? ";
538 array_push($sqlBindArray, $names['first']);
539 if ($names['middle'] != '') {
540 $where .= "AND mname LIKE ? ";
541 array_push($sqlBindArray, $names['middle']);
543 } elseif (array_key_exists('first', $names) && $names['first'] == '') {
544 // Do not search first name or middle name
545 $where = "lname LIKE ? ";
546 array_push($sqlBindArray, $names['last']);
547 } elseif ($names['first'] == '' && $names['last'] != '') {
548 // Search both first name and last name with same term
549 $names['first'] = $names['last'];
550 $where = "lname LIKE ? OR fname LIKE ? ";
551 array_push($sqlBindArray, $names['last'], $names['first']);
552 } elseif ($names['middle'] != '') {
553 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
554 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
556 $where = "lname LIKE ? AND fname LIKE ? ";
557 array_push($sqlBindArray, $names['last'], $names['first']);
560 if (!empty($GLOBALS['pt_restrict_field'])) {
561 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
562 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
563 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
564 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
565 array_push($sqlBindArray, $_SESSION{"authUser"});
569 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
570 if ($limit != "all") {
571 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
574 $rez = sqlStatement($sql, $sqlBindArray);
577 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
578 $returnval[$iter] = $row;
581 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
585 * Accept a string used by a search function expected to find a patient name,
586 * then split up the string if a comma or space exists. Return an array having
587 * from 1 to 3 elements, named first, middle, and last.
588 * See above getPatientLnames() function for details on how the splitting occurs.
589 * @param string $term
592 function getPatientNameSplit($term)
595 if (strpos($term, ',') !== false) {
596 $names = explode(',', $term);
597 $n['last'] = $names[0];
598 if (strpos(trim($names[1]), ' ') !== false) {
599 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
601 $n['first'] = $names[1];
603 } elseif (strpos($term, ' ') !== false) {
604 $names = explode(' ', $term);
605 if (count($names) == 1) {
606 $n['last'] = $names[0];
607 } elseif (count($names) == 3) {
608 $n['first'] = $names[0];
609 $n['middle'] = $names[1];
610 $n['last'] = $names[2];
612 // This will handle first and last name or first followed by
613 // multiple names only using just the last of the names in the list.
614 $n['first'] = $names[0];
615 $n['last'] = end($names);
619 if (empty($n['last'])) {
624 // Trim whitespace off the names before returning
625 foreach ($n as $key => $val) {
626 $n[$key] = trim($val);
629 return $n; // associative array containing names
632 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")
635 $sqlBindArray = array();
636 $where = "pubpid LIKE ? ";
637 array_push($sqlBindArray, $pid."%");
638 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
639 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
640 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
641 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
642 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
643 array_push($sqlBindArray, $_SESSION{"authUser"});
647 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
648 if ($limit != "all") {
649 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
652 $rez = sqlStatement($sql, $sqlBindArray);
653 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
654 $returnval[$iter]=$row;
657 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
661 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")
663 $layoutCols = sqlStatement(
664 "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
668 $sqlBindArray = array();
670 for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
675 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
676 array_push($sqlBindArray, "%".$searchTerm."%");
679 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
680 if ($limit != "all") {
681 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
684 $rez = sqlStatement($sql, $sqlBindArray);
685 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
686 $returnval[$iter]=$row;
689 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
693 function getByPatientDemographicsFilter(
696 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
697 $orderby = "lname ASC, fname ASC",
700 $search_service_code = ''
703 $layoutCols = explode('~', $searchFields);
704 $sqlBindArray = array();
707 foreach ($layoutCols as $val) {
717 $where .= " ".add_escape_custom($val)." = ? ";
718 array_push($sqlBindArray, $searchTerm);
720 $where .= " ".add_escape_custom($val)." like ? ";
721 array_push($sqlBindArray, $searchTerm."%");
727 // If no search terms, ensure valid syntax.
732 // If a non-empty service code was given, then restrict to patients who
733 // have been provided that service. Since the code is used in a LIKE
734 // clause, % and _ wildcards are supported.
735 if ($search_service_code) {
736 $where = "( $where ) AND " .
737 "( SELECT COUNT(*) FROM billing AS b WHERE " .
738 "b.pid = patient_data.pid AND " .
739 "b.activity = 1 AND " .
740 "b.code_type != 'COPAY' AND " .
743 array_push($sqlBindArray, $search_service_code);
746 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
747 if ($limit != "all") {
748 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
751 $rez = sqlStatement($sql, $sqlBindArray);
752 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
753 $returnval[$iter]=$row;
756 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
760 // return a collection of Patient PIDs
761 // new arg style by JRM March 2008
762 // 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")
763 function getPatientPID($args)
766 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
767 $orderby = "lname ASC, fname ASC";
771 // alter default values if defined in the passed in args
772 if (isset($args['pid'])) {
776 if (isset($args['given'])) {
777 $given = $args['given'];
780 if (isset($args['orderby'])) {
781 $orderby = $args['orderby'];
784 if (isset($args['limit'])) {
785 $limit = $args['limit'];
788 if (isset($args['start'])) {
789 $start = $args['start'];
795 } elseif (empty($pid)) {
799 if (strstr($pid, "%")) {
803 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
804 if ($limit != "all") {
805 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
808 $rez = sqlStatement($sql);
809 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
810 $returnval[$iter]=$row;
816 /* return a patient's name in the format LAST, FIRST */
817 function getPatientName($pid)
823 $patientData = getPatientPID(array("pid"=>$pid));
824 if (empty($patientData[0]['lname'])) {
828 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
832 /* find patient data by DOB */
833 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
835 $DOB = fixDate($DOB, $DOB);
836 $sqlBindArray = array();
837 $where = "DOB like ? ";
838 array_push($sqlBindArray, $DOB."%");
839 if (!empty($GLOBALS['pt_restrict_field'])) {
840 if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
841 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
842 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
843 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
844 array_push($sqlBindArray, $_SESSION{"authUser"});
848 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
850 if ($limit != "all") {
851 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
854 $rez = sqlStatement($sql, $sqlBindArray);
855 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
856 $returnval[$iter]=$row;
859 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
863 /* find patient data by SSN */
864 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
866 $sqlBindArray = array();
867 $where = "ss LIKE ?";
868 array_push($sqlBindArray, $ss."%");
869 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
870 if ($limit != "all") {
871 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
874 $rez = sqlStatement($sql, $sqlBindArray);
875 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
876 $returnval[$iter]=$row;
879 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
883 //(CHEMED) Search by phone number
884 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
886 $phone = preg_replace("/[[:punct:]]/", "", $phone);
887 $sqlBindArray = array();
888 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
889 array_push($sqlBindArray, $phone);
890 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
891 if ($limit != "all") {
892 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
895 $rez = sqlStatement($sql, $sqlBindArray);
896 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
897 $returnval[$iter]=$row;
900 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
904 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
906 $sql="select $given from patient_data order by $orderby";
908 if ($limit != "all") {
909 $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
912 $rez = sqlStatement($sql);
913 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
914 $returnval[$iter]=$row;
920 //----------------------input functions
921 function newPatientData(
940 $contact_relationship = "",
947 $migrantseasonal = "",
949 $monthly_income = "",
951 $financial_review = "",
965 $drivers_license = "",
971 $DOB = fixDate($DOB);
972 $regdate = fixDate($regdate);
975 $referral_source = '';
977 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
978 // Check for brain damage:
979 if ($db_id != $rez['id']) {
980 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
981 $rez['id'] . "' to '$db_id' for pid '$pid'";
985 $fitness = $rez['fitness'];
986 $referral_source = $rez['referral_source'];
989 // Get the default price level.
990 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
991 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
992 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
994 $query = ("replace into patient_data set
1003 postal_code='$postal_code',
1006 country_code='$country_code',
1007 drivers_license='$drivers_license',
1009 occupation='$occupation',
1010 phone_home='$phone_home',
1011 phone_biz='$phone_biz',
1012 phone_contact='$phone_contact',
1014 contact_relationship='$contact_relationship',
1015 referrer='$referrer',
1016 referrerID='$referrerID',
1018 language='$language',
1019 ethnoracial='$ethnoracial',
1020 interpretter='$interpretter',
1021 migrantseasonal='$migrantseasonal',
1022 family_size='$family_size',
1023 monthly_income='$monthly_income',
1024 homeless='$homeless',
1025 financial_review='$financial_review',
1028 providerID = '$providerID',
1029 genericname1 = '$genericname1',
1030 genericval1 = '$genericval1',
1031 genericname2 = '$genericname2',
1032 genericval2 = '$genericval2',
1033 billing_note= '$billing_note',
1034 phone_cell = '$phone_cell',
1035 pharmacy_id = '$pharmacy_id',
1036 hipaa_mail = '$hipaa_mail',
1037 hipaa_voice = '$hipaa_voice',
1038 hipaa_notice = '$hipaa_notice',
1039 hipaa_message = '$hipaa_message',
1042 referral_source='$referral_source',
1044 pricelevel='$pricelevel',
1047 $id = sqlInsert($query);
1050 // find the last inserted id for new patient case
1051 $db_id = getSqlLastID();
1054 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1059 // Supported input date formats are:
1061 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
1063 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1065 function fixDate($date, $default = "0000-00-00")
1067 $fixed_date = $default;
1068 $date = trim($date);
1069 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1070 $dmy = preg_split("'[/.-]'", $date);
1072 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1074 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1075 if ($dmy[2] < 1000) {
1079 if ($dmy[2] < 1910) {
1084 // phone_country_code indicates format of ambiguous input dates.
1085 if ($GLOBALS['phone_country_code'] == 1) {
1086 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1088 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1096 function pdValueOrNull($key, $value)
1098 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1099 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1100 (empty($value) || $value == '0000-00-00')) {
1103 return "'" . add_escape_custom($value) . "'";
1107 // Create or update patient data from an array.
1109 function updatePatientData($pid, $new, $create = false)
1111 /*******************************************************************
1112 $real = getPatientData($pid);
1113 $new['DOB'] = fixDate($new['DOB']);
1114 while(list($key, $value) = each ($new))
1115 $real[$key] = $value;
1116 $real['date'] = "'+NOW()+'";
1118 $sql = "insert into patient_data set ";
1119 while(list($key, $value) = each($real))
1120 $sql .= $key." = '$value', ";
1121 $sql = substr($sql, 0, -2);
1122 return sqlInsert($sql);
1123 *******************************************************************/
1125 // The above was broken, though seems intent to insert a new patient_data
1126 // row for each update. A good idea, but nothing is doing that yet so
1127 // the code below does not yet attempt it.
1129 $new['DOB'] = fixDate($new['DOB']);
1132 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1133 foreach ($new as $key => $value) {
1138 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1141 $db_id = sqlInsert($sql);
1143 $db_id = $new['id'];
1144 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1145 // Check for brain damage:
1146 if ($pid != $rez['pid']) {
1147 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1148 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1152 $sql = "UPDATE patient_data SET date = NOW()";
1153 foreach ($new as $key => $value) {
1154 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1157 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1164 function newEmployerData(
1174 return sqlInsert("insert into employer_data set
1177 postal_code='$postal_code',
1186 // Create or update employer data from an array.
1188 function updateEmployerData($pid, $new, $create = false)
1190 $colnames = array('name','street','city','state','postal_code','country');
1193 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1194 foreach ($colnames as $key) {
1195 $value = isset($new[$key]) ? $new[$key] : '';
1196 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1199 return sqlInsert("INSERT INTO employer_data SET $set");
1202 $old = getEmployerData($pid);
1204 foreach ($colnames as $key) {
1205 $value = empty($old[$key]) ? '' : $old[$key];
1206 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1207 $value = $new[$key];
1211 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1215 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1216 return sqlInsert("INSERT INTO employer_data SET $set");
1223 // This updates or adds the given insurance data info, while retaining any
1224 // previously added insurance_data rows that should be preserved.
1225 // This does not directly support the maintenance of non-current insurance.
1227 function newInsuranceData(
1231 $policy_number = "",
1234 $subscriber_lname = "",
1235 $subscriber_mname = "",
1236 $subscriber_fname = "",
1237 $subscriber_relationship = "",
1238 $subscriber_ss = "",
1239 $subscriber_DOB = "",
1240 $subscriber_street = "",
1241 $subscriber_postal_code = "",
1242 $subscriber_city = "",
1243 $subscriber_state = "",
1244 $subscriber_country = "",
1245 $subscriber_phone = "",
1246 $subscriber_employer = "",
1247 $subscriber_employer_street = "",
1248 $subscriber_employer_city = "",
1249 $subscriber_employer_postal_code = "",
1250 $subscriber_employer_state = "",
1251 $subscriber_employer_country = "",
1253 $subscriber_sex = "",
1254 $effective_date = "0000-00-00",
1255 $accept_assignment = "TRUE",
1259 if (strlen($type) <= 0) {
1263 // If a bad date was passed, err on the side of caution.
1264 $effective_date = fixDate($effective_date, date('Y-m-d'));
1266 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1267 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1268 $idrow = sqlFetchArray($idres);
1270 // Replace the most recent entry in any of the following cases:
1271 // * Its effective date is >= this effective date.
1272 // * It is the first entry and it has no (insurance) provider.
1273 // * There is no encounter that is earlier than the new effective date but
1274 // on or after the old effective date.
1275 // Otherwise insert a new entry.
1279 if (strcmp($idrow['date'], $effective_date) > 0) {
1282 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1285 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1286 "WHERE pid = ? AND date < ? AND " .
1287 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1288 if ($ferow['count'] == 0) {
1296 // TBD: This is a bit dangerous in that a typo in entering the effective
1297 // date can wipe out previous insurance history. So we want some data
1298 // entry validation somewhere.
1299 sqlStatement("DELETE FROM insurance_data WHERE " .
1300 "pid = ? AND type = ? AND date >= ? AND " .
1301 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1304 $data['type'] = $type;
1305 $data['provider'] = $provider;
1306 $data['policy_number'] = $policy_number;
1307 $data['group_number'] = $group_number;
1308 $data['plan_name'] = $plan_name;
1309 $data['subscriber_lname'] = $subscriber_lname;
1310 $data['subscriber_mname'] = $subscriber_mname;
1311 $data['subscriber_fname'] = $subscriber_fname;
1312 $data['subscriber_relationship'] = $subscriber_relationship;
1313 $data['subscriber_ss'] = $subscriber_ss;
1314 $data['subscriber_DOB'] = $subscriber_DOB;
1315 $data['subscriber_street'] = $subscriber_street;
1316 $data['subscriber_postal_code'] = $subscriber_postal_code;
1317 $data['subscriber_city'] = $subscriber_city;
1318 $data['subscriber_state'] = $subscriber_state;
1319 $data['subscriber_country'] = $subscriber_country;
1320 $data['subscriber_phone'] = $subscriber_phone;
1321 $data['subscriber_employer'] = $subscriber_employer;
1322 $data['subscriber_employer_city'] = $subscriber_employer_city;
1323 $data['subscriber_employer_street'] = $subscriber_employer_street;
1324 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1325 $data['subscriber_employer_state'] = $subscriber_employer_state;
1326 $data['subscriber_employer_country'] = $subscriber_employer_country;
1327 $data['copay'] = $copay;
1328 $data['subscriber_sex'] = $subscriber_sex;
1329 $data['pid'] = $pid;
1330 $data['date'] = $effective_date;
1331 $data['accept_assignment'] = $accept_assignment;
1332 $data['policy_type'] = $policy_type;
1333 updateInsuranceData($idrow['id'], $data);
1334 return $idrow['id'];
1336 return sqlInsert("INSERT INTO insurance_data SET
1337 type = '" . add_escape_custom($type) . "',
1338 provider = '" . add_escape_custom($provider) . "',
1339 policy_number = '" . add_escape_custom($policy_number) . "',
1340 group_number = '" . add_escape_custom($group_number) . "',
1341 plan_name = '" . add_escape_custom($plan_name) . "',
1342 subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1343 subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1344 subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1345 subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1346 subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1347 subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1348 subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1349 subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1350 subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1351 subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1352 subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1353 subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1354 subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1355 subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1356 subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1357 subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1358 subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1359 subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1360 copay = '" . add_escape_custom($copay) . "',
1361 subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1362 pid = '" . add_escape_custom($pid) . "',
1363 date = '" . add_escape_custom($effective_date) . "',
1364 accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1365 policy_type = '" . add_escape_custom($policy_type) . "'
1370 // This is used internally only.
1371 function updateInsuranceData($id, $new)
1373 $fields = sqlListFields("insurance_data");
1376 while (list($key, $value) = each($new)) {
1377 if (in_array($key, $fields)) {
1378 $use[$key] = $value;
1382 $sql = "UPDATE insurance_data SET ";
1383 while (list($key, $value) = each($use)) {
1384 $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1387 $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1392 function newHistoryData($pid, $new = false)
1394 $arraySqlBind = array();
1395 $sql = "insert into history_data set pid = ?, date = NOW()";
1396 array_push($arraySqlBind, $pid);
1398 while (list($key, $value) = each($new)) {
1399 array_push($arraySqlBind, $value);
1400 $sql .= ", `$key` = ?";
1404 return sqlInsert($sql, $arraySqlBind);
1407 function updateHistoryData($pid, $new)
1409 $real = getHistoryData($pid);
1410 while (list($key, $value) = each($new)) {
1411 $real[$key] = $value;
1415 // need to unset date, so can reset it below
1416 unset($real['date']);
1418 $arraySqlBind = array();
1419 $sql = "insert into history_data set `date` = NOW(), ";
1420 while (list($key, $value) = each($real)) {
1421 array_push($arraySqlBind, $value);
1422 $sql .= "`$key` = ?, ";
1425 $sql = substr($sql, 0, -2);
1427 return sqlInsert($sql, $arraySqlBind);
1431 // in months if < 2 years old
1432 // in years if > 2 years old
1433 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1434 // (optional) nowYMD is a date in YYYYMMDD format
1435 function getPatientAge($dobYMD, $nowYMD = null)
1437 // strip any dashes from the DOB
1438 $dobYMD = preg_replace("/-/", "", $dobYMD);
1439 $dobDay = substr($dobYMD, 6, 2);
1440 $dobMonth = substr($dobYMD, 4, 2);
1441 $dobYear = substr($dobYMD, 0, 4);
1443 // set the 'now' date values
1444 if ($nowYMD == null) {
1445 $nowDay = date("d");
1446 $nowMonth = date("m");
1447 $nowYear = date("Y");
1449 $nowDay = substr($nowYMD, 6, 2);
1450 $nowMonth = substr($nowYMD, 4, 2);
1451 $nowYear = substr($nowYMD, 0, 4);
1454 $dayDiff = $nowDay - $dobDay;
1455 $monthDiff = $nowMonth - $dobMonth;
1456 $yearDiff = $nowYear - $dobYear;
1458 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1460 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1465 if ($ageInMonths > 24) {
1467 if (($monthDiff == 0) && ($dayDiff < 0)) {
1469 } else if ($monthDiff < 0) {
1473 $age = "$ageInMonths " . xl('month');
1480 * Wrapper to make sure the clinical rules dates formats corresponds to the
1481 * format expected by getPatientAgeYMD
1483 * @param string $dob date of birth
1484 * @param string $target date to calculate age on
1485 * @return array containing
1486 * age - decimal age in years
1487 * age_in_months - decimal age in months
1488 * ageinYMD - formatted string #y #m #d */
1489 function parseAgeInfo($dob, $target)
1491 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1492 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1494 // Prepare target (Y-M-D H:M:S)
1495 $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1497 return getPatientAgeYMD($dateDOB, $dateTarget);
1504 * @return array containing
1505 * age - decimal age in years
1506 * age_in_months - decimal age in months
1507 * ageinYMD - formatted string #y #m #d
1509 function getPatientAgeYMD($dob, $date = null)
1512 if ($date == null) {
1513 $daynow = date("d");
1514 $monthnow = date("m");
1515 $yearnow = date("Y");
1516 $datenow=$yearnow.$monthnow.$daynow;
1518 $datenow=preg_replace("/-/", "", $date);
1519 $yearnow=substr($datenow, 0, 4);
1520 $monthnow=substr($datenow, 4, 2);
1521 $daynow=substr($datenow, 6, 2);
1522 $datenow=$yearnow.$monthnow.$daynow;
1525 $dob=preg_replace("/-/", "", $dob);
1526 $dobyear=substr($dob, 0, 4);
1527 $dobmonth=substr($dob, 4, 2);
1528 $dobday=substr($dob, 6, 2);
1529 $dob=$dobyear.$dobmonth.$dobday;
1531 //to compensate for 30, 31, 28, 29 days/month
1532 $mo=$monthnow; //to avoid confusion with later calculation
1534 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1535 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1536 } // look at April, June, September, November for calculation. These months only have 30 days.
1537 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1538 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1539 if (is_int($check_leap_Y)) {
1541 } //If it true then this is the leap year
1544 } //otherwise, it is not a leap year.
1547 } // other months have 31 days
1549 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1550 if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1551 $age_year = $yearnow - $dobyear - 1;
1552 if ($daynow < $dobday) {
1553 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1554 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1556 $months_since_birthday=12 - $dobmonth + $monthnow;
1557 $days_since_dobday=$daynow - $dobday;
1559 } else // if patient has had birthday this calandar year
1561 $age_year = $yearnow - $dobyear;
1562 if ($daynow < $dobday) {
1563 $months_since_birthday=$monthnow - $dobmonth -1;
1564 $days_since_dobday=$nd - $dobday + $daynow;
1566 $months_since_birthday=$monthnow - $dobmonth;
1567 $days_since_dobday=$daynow - $dobday;
1571 $day_as_month_decimal = $days_since_dobday / 30;
1572 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1573 $month_as_year_decimal = $months_since_birthday_float / 12;
1574 $age_float = $age_year + $month_as_year_decimal;
1576 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1577 $age_in_months = round($age_in_months, 2); //round the months to xx.xx 2 floating points
1578 $age = round($age_float, 2);
1580 // round the years to 2 floating points
1581 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1582 return compact('age', 'age_in_months', 'ageinYMD');
1585 // Returns Age in days
1586 // in months if < 2 years old
1587 // in years if > 2 years old
1588 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1589 // (optional) nowYMD is a date in YYYYMMDD format
1590 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1594 // strip any dashes from the DOB
1595 $dobYMD = preg_replace("/-/", "", $dobYMD);
1596 $dobDay = substr($dobYMD, 6, 2);
1597 $dobMonth = substr($dobYMD, 4, 2);
1598 $dobYear = substr($dobYMD, 0, 4);
1600 // set the 'now' date values
1601 if ($nowYMD == null) {
1602 $nowDay = date("d");
1603 $nowMonth = date("m");
1604 $nowYear = date("Y");
1606 $nowDay = substr($nowYMD, 6, 2);
1607 $nowMonth = substr($nowYMD, 4, 2);
1608 $nowYear = substr($nowYMD, 0, 4);
1612 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1613 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1614 $timediff = $nowtime - $dobtime;
1615 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1620 * Returns a string to be used to display a patient's age
1622 * @param type $dobYMD
1623 * @param type $asOfYMD
1624 * @return string suitable for displaying patient's age based on preferences
1626 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1628 if ($GLOBALS['age_display_format']=='1') {
1629 $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1630 if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1631 return $ageYMD['ageinYMD'];
1633 return getPatientAge($dobYMD, $asOfYMD);
1636 return getPatientAge($dobYMD, $asOfYMD);
1639 function dateToDB($date)
1641 $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1646 // ----------------------------------------------------------------------------
1648 * DROPDOWN FOR COUNTRIES
1650 * build a dropdown with all countries from geo_country_reference
1652 * @param int $selected - id for selected record
1653 * @param string $name - the name/id for select form
1654 * @return void - just echo the html encoded string
1656 function dropdown_countries($selected = 0, $name = 'country_code')
1658 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1660 $string = "<select name='$name' id='$name'>";
1661 while ($row = sqlFetchArray($r)) {
1662 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1663 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1666 $string .= '</select>';
1671 // ----------------------------------------------------------------------------
1673 * DROPDOWN FOR YES/NO
1675 * build a dropdown with two options (yes - 1, no - 0)
1677 * @param int $selected - id for selected record
1678 * @param string $name - the name/id for select form
1679 * @return void - just echo the html encoded string
1681 function dropdown_yesno($selected = 0, $name = 'yesno')
1683 $string = "<select name='$name' id='$name'>";
1685 $selected = (int)$selected;
1686 if ($selected == 0) {
1687 $sel1 = 'selected="selected"';
1690 $sel2 = 'selected="selected"';
1694 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1695 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1696 $string .= '</select>';
1701 // ----------------------------------------------------------------------------
1703 * DROPDOWN FOR MALE/FEMALE options
1705 * build a dropdown with three options (unselected/male/female)
1707 * @param int $selected - id for selected record
1708 * @param string $name - the name/id for select form
1709 * @return void - just echo the html encoded string
1711 function dropdown_sex($selected = 0, $name = 'sex')
1713 $string = "<select name='$name' id='$name'>";
1715 if ($selected == 1) {
1716 $sel1 = 'selected="selected"';
1719 } else if ($selected == 2) {
1720 $sel2 = 'selected="selected"';
1724 $sel0 = 'selected="selected"';
1729 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1730 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1731 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1732 $string .= '</select>';
1737 // ----------------------------------------------------------------------------
1739 * DROPDOWN FOR MARITAL STATUS
1741 * build a dropdown with marital status
1743 * @param int $selected - id for selected record
1744 * @param string $name - the name/id for select form
1745 * @return void - just echo the html encoded string
1747 function dropdown_marital($selected = 0, $name = 'status')
1749 $string = "<select name='$name' id='$name'>";
1751 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1753 foreach ($statii as $st) {
1754 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1755 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1758 $string .= '</select>';
1763 // ----------------------------------------------------------------------------
1765 * DROPDOWN FOR PROVIDERS
1767 * build a dropdown with all providers
1769 * @param int $selected - id for selected record
1770 * @param string $name - the name/id for select form
1771 * @return void - just echo the html encoded string
1773 function dropdown_providers($selected = 0, $name = 'status')
1775 $provideri = getProviderInfo();
1777 $string = "<select name='$name' id='$name'>";
1778 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1779 foreach ($provideri as $s) {
1780 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1781 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1784 $string .= '</select>';
1789 // ----------------------------------------------------------------------------
1791 * DROPDOWN FOR INSURANCE COMPANIES
1793 * build a dropdown with all insurers
1795 * @param int $selected - id for selected record
1796 * @param string $name - the name/id for select form
1797 * @return void - just echo the html encoded string
1799 function dropdown_insurance($selected = 0, $name = 'iprovider')
1801 $insurancei = getInsuranceProviders();
1803 $string = "<select name='$name' id='$name'>";
1804 $string .= '<option value="0">Onbekend</option>';
1805 foreach ($insurancei as $iid => $iname) {
1806 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1807 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1810 $string .= '</select>';
1816 // ----------------------------------------------------------------------------
1820 * return the name or the country code, function of arguments
1822 * @param int $country_code
1823 * @param string $country_name
1824 * @return string | int - name or code
1826 function country_code($country_code = 0, $country_name = '')
1829 if ($country_code) {
1830 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1832 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1835 $db = $GLOBALS['adodb']['db'];
1836 $result = $db->Execute($sql);
1837 if ($result && !$result->EOF) {
1838 $strint = $result->fields['res'];
1844 function DBToDate($date)
1846 $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1851 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1852 * for the given patient on the given date.
1854 * @param int The PID of the patient.
1855 * @param string Date in yyyy-mm-dd format.
1856 * @return array Array of 0-3 insurance_data rows.
1858 function getEffectiveInsurances($patient_id, $encdate)
1861 foreach (array('primary','secondary','tertiary') as $instype) {
1863 "SELECT * FROM insurance_data " .
1864 "WHERE pid = ? AND type = ? " .
1865 "AND date <= ? ORDER BY date DESC LIMIT 1",
1866 array($patient_id, $instype, $encdate)
1868 if (empty($tmp['provider'])) {
1879 * Get the patient's balance due. Normally this excludes amounts that are out
1880 * to insurance. If you want to include what insurance owes, set the second
1881 * parameter to true.
1883 * @param int The PID of the patient.
1884 * @param boolean Indicates if amounts owed by insurance are to be included.
1885 * @return number The balance.
1887 function get_patient_balance($pid, $with_insurance = false)
1890 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1891 "last_level_closed, stmt_count " .
1892 "FROM form_encounter WHERE pid = ?", array($pid));
1893 while ($ferow = sqlFetchArray($feres)) {
1894 $encounter = $ferow['encounter'];
1895 $dos = substr($ferow['date'], 0, 10);
1896 $insarr = getEffectiveInsurances($pid, $dos);
1897 $inscount = count($insarr);
1898 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1899 // It's out to insurance so only the co-pay might be due.
1901 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1902 "pid = ? AND encounter = ? AND " .
1903 "code_type = 'copay' AND activity = 1",
1904 array($pid, $encounter)
1907 "SELECT SUM(pay_amount) AS payments " .
1908 "FROM ar_activity WHERE " .
1909 "pid = ? AND encounter = ? AND payer_type = 0",
1910 array($pid, $encounter)
1912 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1917 // Including insurance or not out to insurance, everything is due.
1918 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1919 "pid = ? AND encounter = ? AND " .
1920 "activity = 1", array($pid, $encounter));
1921 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1922 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1923 "pid = ? AND encounter = ?", array($pid, $encounter));
1924 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1925 "pid = ? AND encounter = ?", array($pid, $encounter));
1926 $balance += $brow['amount'] + $srow['amount']
1927 - $drow['payments'] - $drow['adjustments'];
1931 return sprintf('%01.2f', $balance);
1934 // Function to check if patient is deceased.
1936 // $pid - patient id
1937 // $date - date checking if deceased (will default to current date if blank)
1939 // If deceased, then will return the number of
1940 // days that patient has been deceased.
1941 // If not deceased, then will return false.
1942 function is_patient_deceased($pid, $date = '')
1945 // Set date to current if not set
1946 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1948 // Query for deceased status (gets days deceased if patient is deceased)
1949 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1950 "FROM `patient_data` " .
1951 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1953 if (empty($results)) {
1954 // Patient is alive, so return false
1957 // Patient is dead, so return the number of days patient has been deceased.
1958 // Don't let it be zero days or else will confuse calls to this function.
1959 if ($results['days_deceased'] === 0) {
1960 $results['days_deceased'] = 1;
1963 return $results['days_deceased'];