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.
12 // These are for sports team use:
13 $PLAYER_FITNESSES = array(
16 xl('Restricted Training'),
20 xl('International Duty')
22 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
24 // Hard-coding this array because its values and meanings are fixed by the 837p
25 // standard and we don't want people messing with them.
26 $policy_types = array(
28 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
29 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
30 '14' => xl('No-fault Insurance including Auto is Primary'),
31 '15' => xl('Worker`s Compensation'),
32 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
33 '41' => xl('Black Lung'),
34 '42' => xl('Veteran`s Administration'),
35 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
36 '47' => xl('Other Liability Insurance is Primary'),
40 * Get a patient's demographic data.
42 * @param int $pid The PID of the patient
43 * @param string $given an optional subsection of the patient's demographic
45 * @return array The requested subsection of a patient's demographic data.
46 * If no subsection was given, returns everything, with the
47 * date of birth as the last field.
49 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
50 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
51 return sqlQuery($sql, array($pid) );
54 function getLanguages() {
55 $returnval = array('','english');
56 $sql = "select distinct lower(language) as language from patient_data";
57 $rez = sqlStatement($sql);
58 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
59 if (($row["language"] != "english") && ($row["language"] != "")) {
60 array_push($returnval, $row["language"]);
66 function getInsuranceProvider($ins_id) {
68 $sql = "select name from insurance_companies where id=?";
69 $row = sqlQuery($sql,array($ins_id));
74 function getInsuranceProviders() {
78 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
79 $rez = sqlStatement($sql);
80 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
81 $returnval[$row['id']] = $row['name'];
85 // Please leave this here. I have a user who wants to see zip codes and PO
86 // box numbers listed along with the insurance company names, as many companies
87 // have different billing addresses for different plans. -- Rod Roark
90 $sql = "select insurance_companies.name, insurance_companies.id, " .
91 "addresses.zip, addresses.line1 " .
92 "from insurance_companies, addresses " .
93 "where addresses.foreign_id = insurance_companies.id " .
94 "order by insurance_companies.name, addresses.zip";
96 $rez = sqlStatement($sql);
98 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
99 preg_match("/\d+/", $row['line1'], $matches);
100 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
101 "," . $matches[0] . ")";
108 function getInsuranceProvidersExtra() {
109 $returnval = array();
110 // add a global and if for where to allow inactive inscompanies
112 $sql = "select insurance_companies.name, insurance_companies.id, " .
113 "addresses.zip, addresses.line1, addresses.state " .
114 "from insurance_companies, addresses " .
115 "where addresses.foreign_id = insurance_companies.id " .
116 "and insurance_companies.inactive != 1 " .
117 "order by insurance_companies.name, addresses.zip";
119 $rez = sqlStatement($sql);
121 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
122 switch ($GLOBALS['insurance_information']) {
123 case $GLOBALS['insurance_information'] = '0':
124 $returnval[$row['id']] = $row['name'];
126 case $GLOBALS['insurance_information'] = '1':
127 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
129 case $GLOBALS['insurance_information'] = '2':
130 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";
132 case $GLOBALS['insurance_information'] = '3':
133 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
135 case $GLOBALS['insurance_information'] = '4':
136 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
137 "," . $row['zip'] . ")";
139 case $GLOBALS['insurance_information'] = '5':
140 preg_match("/\d+/", $row['line1'], $matches);
141 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
142 "," . $matches[0] . ")";
150 function getProviders() {
151 $returnval = array("");
152 $sql = "select fname, lname, suffix from users where authorized = 1 and " .
153 "active = 1 and username != ''";
154 $rez = sqlStatement($sql);
155 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
156 if (($row["fname"] != "") && ($row["lname"] != "")) {
157 if ($row["suffix"] != "") $row["lname"] .= ", ".$row["suffix"];
158 array_push($returnval, $row["fname"] . " " . $row["lname"]);
164 // ----------------------------------------------------------------------------
165 // Get one facility row. If the ID is not specified, then get either the
166 // "main" (billing) facility, or the default facility of the currently
167 // logged-in user. This was created to support genFacilityTitle() but
168 // may find additional uses.
170 function getFacility($facid=0) {
172 //create a sql binding array
173 $sqlBindArray = array();
176 $query = "SELECT * FROM facility WHERE id = ?";
177 array_push($sqlBindArray,$facid);
179 else if ($facid == 0) {
180 $query = "SELECT * FROM facility ORDER BY " .
181 "billing_location DESC, service_location, id LIMIT 1";
184 $query = "SELECT facility.* FROM users, facility WHERE " .
185 "users.id = ? AND " .
186 "facility.id = users.facility_id";
187 array_push($sqlBindArray,$_SESSION['authUserID']);
189 return sqlQuery($query,$sqlBindArray);
192 // Generate a report title including report name and facility name, address
195 function genFacilityTitle($repname='', $facid=0) {
197 $s .= "<table class='ftitletable'>\n";
199 $s .= " <td class='ftitlecell1'>$repname</td>\n";
200 $s .= " <td class='ftitlecell2'>\n";
201 $r = getFacility($facid);
203 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
204 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
205 if ($r['city'] || $r['state'] || $r['postal_code']) {
207 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
209 if ($r['city']) $s .= ", \n";
210 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
212 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
215 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
216 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
227 returns all facilities or just the id for the first one
228 (FACILITY FILTERING (lemonsoftware))
230 @param string - if 'first' return first facility ordered by id
231 @return array | int for 'first' case
233 function getFacilities($first = '') {
234 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
236 while ( $row = sqlFetchArray($r) ) {
240 if ( $first == 'first') {
241 return $ret[0]['id'];
248 GET SERVICE FACILITIES
250 returns all service_location facilities or just the id for the first one
251 (FACILITY FILTERING (CHEMED))
253 @param string - if 'first' return first facility ordered by id
254 @return array | int for 'first' case
256 function getServiceFacilities($first = '') {
257 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
259 while ( $row = sqlFetchArray($r) ) {
263 if ( $first == 'first') {
264 return $ret[0]['id'];
270 //(CHEMED) facility filter
271 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
273 if ($providers_only === 'any') {
274 $param1 = " AND authorized = 1 AND active = 1 ";
276 else if ($providers_only) {
277 $param1 = " AND authorized = 1 AND calendar = 1 ";
280 //--------------------------------
281 //(CHEMED) facility filter
284 if ($GLOBALS['restrict_user_facility']) {
285 $param2 = " AND (facility_id = $facility
289 where tablename = 'users'
295 $param2 = " AND facility_id = $facility ";
298 //--------------------------------
301 if ($providerID == "%") {
304 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
305 "from users where username != '' and active = 1 and id $command '" .
306 add_escape_custom($providerID) . "' " . $param1 . $param2;
307 // sort by last name -- JRM June 2008
308 $query .= " ORDER BY lname, fname ";
309 $rez = sqlStatement($query);
310 for($iter=0; $row=sqlFetchArray($rez); $iter++)
311 $returnval[$iter]=$row;
313 //if only one result returned take the key/value pairs in array [0] and merge them down into
314 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
317 $akeys = array_keys($returnval[0]);
318 foreach($akeys as $key) {
319 $returnval[0][$key] = $returnval[0][$key];
325 //same as above but does not reduce if only 1 row returned
326 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
328 if ($providers_only) {
329 $param1 = "AND authorized=1";
332 if ($providerID == "%") {
335 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
336 "from users where active = 1 and username != '' and id $command '" .
337 add_escape_custom($providerID) . "' " . $param1;
339 $rez = sqlStatement($query);
340 for($iter=0; $row=sqlFetchArray($rez); $iter++)
341 $returnval[$iter]=$row;
346 function getProviderName($providerID) {
347 $pi = getProviderInfo($providerID, 'any');
348 if (strlen($pi[0]["lname"]) > 0) {
349 if (strlen($pi[0]["suffix"]) > 0) $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
350 return $pi[0]['fname'] . " " . $pi[0]['lname'];
355 function getProviderId($providerName) {
356 $query = "select id from users where username = ?";
357 $rez = sqlStatement($query, array($providerName) );
358 for($iter=0; $row=sqlFetchArray($rez); $iter++)
359 $returnval[$iter]=$row;
363 function getEthnoRacials() {
364 $returnval = array("");
365 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
366 $rez = sqlStatement($sql);
367 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
368 if (($row["ethnoracial"] != "")) {
369 array_push($returnval, $row["ethnoracial"]);
375 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
378 if ($dateStart && $dateEnd) {
379 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
381 else if ($dateStart && !$dateEnd) {
382 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
384 else if (!$dateStart && $dateEnd) {
385 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
388 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
391 if($given == 'tobacco'){
392 $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));
398 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
399 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
401 $sql = "select $given from insurance_data as insd " .
402 "left join insurance_companies as ic on ic.id = insd.provider " .
403 "where pid = ? and type = ? order by date DESC limit 1";
404 return sqlQuery($sql, array($pid, $type) );
407 function getInsuranceDataByDate($pid, $date, $type,
408 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
409 { // this must take the date in the following manner: YYYY-MM-DD
410 // this function recalls the insurance value that was most recently enterred from the
411 // given date. it will call up most recent records up to and on the date given,
412 // but not records enterred after the given date
413 $sql = "select $given from insurance_data as insd " .
414 "left join insurance_companies as ic on ic.id = provider " .
415 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
416 "type=? order by date DESC limit 1";
417 return sqlQuery($sql, array($pid,$date,$type) );
420 function getEmployerData($pid, $given = "*")
422 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
423 return sqlQuery($sql, array($pid) );
426 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
427 // When the limit is exceeded, find out what the unlimited count would be.
428 $GLOBALS['PATIENT_INC_COUNT'] = $count;
429 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
430 if ($limit != "all") {
431 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
432 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
437 * Allow the last name to be followed by a comma and some part of a first name(can
438 * also place middle name after the first name with a space separating them)
439 * Allows comma alone followed by some part of a first name(can also place middle name
440 * after the first name with a space separating them).
441 * Allows comma alone preceded by some part of a last name.
442 * If no comma or space, then will search both last name and first name.
443 * If the first letter of either name is capital, searches for name starting
444 * with given substring (the expected behavior). If it is lower case, it
445 * searches for the substring anywhere in the name. This applies to either
446 * last name, first name, and middle name.
447 * Also allows first name followed by middle and/or last name when separated by spaces.
448 * @param string $term
449 * @param string $given
450 * @param string $orderby
451 * @param string $limit
452 * @param string $start
455 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")
457 $names = getPatientNameSplit($term);
459 foreach ($names as $key => $val) {
461 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
462 $names[$key] = '%' . $val . '%';
464 $names[$key] = $val . '%';
469 // Debugging section below
470 //if(array_key_exists('first',$names)) {
471 // error_log("first name search term :".$names['first']);
473 //if(array_key_exists('middle',$names)) {
474 // error_log("middle name search term :".$names['middle']);
476 //if(array_key_exists('last',$names)) {
477 // error_log("last name search term :".$names['last']);
479 // Debugging section above
481 $sqlBindArray = array();
482 if(array_key_exists('last',$names) && $names['last'] == '') {
483 // Do not search last name
484 $where = "fname LIKE ? ";
485 array_push($sqlBindArray, $names['first']);
486 if ($names['middle'] != '') {
487 $where .= "AND mname LIKE ? ";
488 array_push($sqlBindArray, $names['middle']);
490 } elseif(array_key_exists('first',$names) && $names['first'] == '') {
491 // Do not search first name or middle name
492 $where = "lname LIKE ? ";
493 array_push($sqlBindArray, $names['last']);
494 } elseif($names['first'] == '' && $names['last'] != '') {
495 // Search both first name and last name with same term
496 $names['first'] = $names['last'];
497 $where = "lname LIKE ? OR fname LIKE ? ";
498 array_push($sqlBindArray, $names['last'], $names['first']);
499 } elseif ($names['middle'] != '') {
500 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
501 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
503 $where = "lname LIKE ? AND fname LIKE ? ";
504 array_push($sqlBindArray, $names['last'], $names['first']);
507 if (!empty($GLOBALS['pt_restrict_field'])) {
508 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
509 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
510 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
511 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
512 array_push($sqlBindArray, $_SESSION{"authUser"});
516 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
517 if ($limit != "all") $sql .= " LIMIT $start, $limit";
519 $rez = sqlStatement($sql, $sqlBindArray);
522 for($iter=0; $row=sqlFetchArray($rez); $iter++)
523 $returnval[$iter] = $row;
525 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
529 * Accept a string used by a search function expected to find a patient name,
530 * then split up the string if a comma or space exists. Return an array having
531 * from 1 to 3 elements, named first, middle, and last.
532 * See above getPatientLnames() function for details on how the splitting occurs.
533 * @param string $term
536 function getPatientNameSplit($term) {
538 if (strpos($term, ',') !== false) {
539 $names = explode(',', $term);
540 $n['last'] = $names[0];
541 if (strpos(trim($names[1]), ' ') !== false) {
542 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
544 $n['first'] = $names[1];
546 } elseif (strpos($term, ' ') !== false) {
547 $names = explode(' ', $term);
548 if (count($names) == 1) {
549 $n['last'] = $names[0];
550 } elseif (count($names) == 3) {
551 $n['first'] = $names[0];
552 $n['middle'] = $names[1];
553 $n['last'] = $names[2];
555 // This will handle first and last name or first followed by
556 // multiple names only using just the last of the names in the list.
557 $n['first'] = $names[0];
558 $n['last'] = end($names);
562 if(empty($n['last'])) $n['last'] = '%';
564 // Trim whitespace off the names before returning
565 foreach($n as $key => $val) {
566 $n[$key] = trim($val);
568 return $n; // associative array containing names
571 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")
574 $sqlBindArray = array();
575 $where = "pubpid LIKE ? ";
576 array_push($sqlBindArray, $pid."%");
577 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
578 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
579 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
580 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
581 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
582 array_push($sqlBindArray, $_SESSION{"authUser"});
586 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
587 if ($limit != "all") $sql .= " limit $start, $limit";
588 $rez = sqlStatement($sql, $sqlBindArray);
589 for($iter=0; $row=sqlFetchArray($rez); $iter++)
590 $returnval[$iter]=$row;
592 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
596 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")
598 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
600 $sqlBindArray = array();
602 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
606 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
607 array_push($sqlBindArray, "%".$searchTerm."%");
610 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
611 if ($limit != "all") $sql .= " limit $start, $limit";
612 $rez = sqlStatement($sql, $sqlBindArray);
613 for($iter=0; $row=sqlFetchArray($rez); $iter++)
614 $returnval[$iter]=$row;
615 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
619 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
620 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
621 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
623 $layoutCols = explode( '~', $searchFields );
624 $sqlBindArray = array();
627 foreach ($layoutCols as $val) {
628 if (empty($val)) continue;
633 $where .= " ".add_escape_custom($val)." = ? ";
634 array_push($sqlBindArray, $searchTerm);
637 $where .= " ".add_escape_custom($val)." like ? ";
638 array_push($sqlBindArray, $searchTerm."%");
643 // If no search terms, ensure valid syntax.
644 if ($i == 0) $where = "1 = 1";
646 // If a non-empty service code was given, then restrict to patients who
647 // have been provided that service. Since the code is used in a LIKE
648 // clause, % and _ wildcards are supported.
649 if ($search_service_code) {
650 $where = "( $where ) AND " .
651 "( SELECT COUNT(*) FROM billing AS b WHERE " .
652 "b.pid = patient_data.pid AND " .
653 "b.activity = 1 AND " .
654 "b.code_type != 'COPAY' AND " .
657 array_push($sqlBindArray, $search_service_code);
660 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
661 if ($limit != "all") $sql .= " limit $start, $limit";
662 $rez = sqlStatement($sql, $sqlBindArray);
663 for($iter=0; $row=sqlFetchArray($rez); $iter++)
664 $returnval[$iter]=$row;
665 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
669 // return a collection of Patient PIDs
670 // new arg style by JRM March 2008
671 // 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")
672 function getPatientPID($args)
675 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
676 $orderby = "lname ASC, fname ASC";
680 // alter default values if defined in the passed in args
681 if (isset($args['pid'])) { $pid = $args['pid']; }
682 if (isset($args['given'])) { $given = $args['given']; }
683 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
684 if (isset($args['limit'])) { $limit = $args['limit']; }
685 if (isset($args['start'])) { $start = $args['start']; }
688 if ($pid == -1) $pid = "%";
689 elseif (empty($pid)) $pid = "NULL";
691 if (strstr($pid,"%")) $command = "like";
693 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
694 if ($limit != "all") $sql .= " limit $start, $limit";
696 $rez = sqlStatement($sql);
697 for($iter=0; $row=sqlFetchArray($rez); $iter++)
698 $returnval[$iter]=$row;
703 /* return a patient's name in the format LAST, FIRST */
704 function getPatientName($pid) {
705 if (empty($pid)) return "";
706 $patientData = getPatientPID(array("pid"=>$pid));
707 if (empty($patientData[0]['lname'])) return "";
708 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
712 /* find patient data by DOB */
713 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
715 $DOB = fixDate($DOB, $DOB);
716 $sqlBindArray = array();
717 $where = "DOB like ? ";
718 array_push($sqlBindArray, $DOB."%");
719 if (!empty($GLOBALS['pt_restrict_field'])) {
720 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
721 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
722 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
723 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
724 array_push($sqlBindArray, $_SESSION{"authUser"});
728 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
730 if ($limit != "all") $sql .= " LIMIT $start, $limit";
732 $rez = sqlStatement($sql, $sqlBindArray);
733 for($iter=0; $row=sqlFetchArray($rez); $iter++)
734 $returnval[$iter]=$row;
736 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
740 /* find patient data by SSN */
741 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
743 $sqlBindArray = array();
744 $where = "ss LIKE ?";
745 array_push($sqlBindArray, $ss."%");
746 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
747 if ($limit != "all") $sql .= " LIMIT $start, $limit";
749 $rez = sqlStatement($sql, $sqlBindArray);
750 for($iter=0; $row=sqlFetchArray($rez); $iter++)
751 $returnval[$iter]=$row;
753 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
757 //(CHEMED) Search by phone number
758 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
760 $phone = preg_replace( "/[[:punct:]]/","", $phone );
761 $sqlBindArray = array();
762 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
763 array_push($sqlBindArray, $phone);
764 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
765 if ($limit != "all") $sql .= " LIMIT $start, $limit";
767 $rez = sqlStatement($sql, $sqlBindArray);
768 for($iter=0; $row=sqlFetchArray($rez); $iter++)
769 $returnval[$iter]=$row;
771 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
775 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
777 $sql="select $given from patient_data order by $orderby";
780 $sql .= " limit $start, $limit";
782 $rez = sqlStatement($sql);
783 for($iter=0; $row=sqlFetchArray($rez); $iter++)
784 $returnval[$iter]=$row;
789 //----------------------input functions
790 function newPatientData( $db_id="",
808 $contact_relationship = "",
815 $migrantseasonal = "",
817 $monthly_income = "",
819 $financial_review = "",
833 $drivers_license = "",
839 $DOB = fixDate($DOB);
840 $regdate = fixDate($regdate);
843 $referral_source = '';
845 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
846 // Check for brain damage:
847 if ($db_id != $rez['id']) {
848 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
849 $rez['id'] . "' to '$db_id' for pid '$pid'";
852 $fitness = $rez['fitness'];
853 $referral_source = $rez['referral_source'];
856 // Get the default price level.
857 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
858 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
859 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
861 $query = ("replace into patient_data set
870 postal_code='$postal_code',
873 country_code='$country_code',
874 drivers_license='$drivers_license',
876 occupation='$occupation',
877 phone_home='$phone_home',
878 phone_biz='$phone_biz',
879 phone_contact='$phone_contact',
881 contact_relationship='$contact_relationship',
882 referrer='$referrer',
883 referrerID='$referrerID',
885 language='$language',
886 ethnoracial='$ethnoracial',
887 interpretter='$interpretter',
888 migrantseasonal='$migrantseasonal',
889 family_size='$family_size',
890 monthly_income='$monthly_income',
891 homeless='$homeless',
892 financial_review='$financial_review',
895 providerID = '$providerID',
896 genericname1 = '$genericname1',
897 genericval1 = '$genericval1',
898 genericname2 = '$genericname2',
899 genericval2 = '$genericval2',
900 billing_note= '$billing_note';
901 phone_cell = '$phone_cell',
902 pharmacy_id = '$pharmacy_id',
903 hipaa_mail = '$hipaa_mail',
904 hipaa_voice = '$hipaa_voice',
905 hipaa_notice = '$hipaa_notice',
906 hipaa_message = '$hipaa_message',
909 referral_source='$referral_source',
911 pricelevel='$pricelevel',
914 $id = sqlInsert($query);
917 // find the last inserted id for new patient case
918 $db_id = getSqlLastID();
921 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
926 // Supported input date formats are:
928 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
930 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
932 function fixDate($date, $default="0000-00-00") {
933 $fixed_date = $default;
935 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
936 $dmy = preg_split("'[/.-]'", $date);
938 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
940 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
941 if ($dmy[2] < 1000) $dmy[2] += 1900;
942 if ($dmy[2] < 1910) $dmy[2] += 100;
944 // phone_country_code indicates format of ambiguous input dates.
945 if ($GLOBALS['phone_country_code'] == 1)
946 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
948 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
955 function pdValueOrNull($key, $value) {
956 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
957 substr($key, 0, 8) == 'userdate') &&
958 (empty($value) || $value == '0000-00-00'))
967 // Create or update patient data from an array.
969 function updatePatientData($pid, $new, $create=false)
971 /*******************************************************************
972 $real = getPatientData($pid);
973 $new['DOB'] = fixDate($new['DOB']);
974 while(list($key, $value) = each ($new))
975 $real[$key] = $value;
976 $real['date'] = "'+NOW()+'";
978 $sql = "insert into patient_data set ";
979 while(list($key, $value) = each($real))
980 $sql .= $key." = '$value', ";
981 $sql = substr($sql, 0, -2);
982 return sqlInsert($sql);
983 *******************************************************************/
985 // The above was broken, though seems intent to insert a new patient_data
986 // row for each update. A good idea, but nothing is doing that yet so
987 // the code below does not yet attempt it.
989 $new['DOB'] = fixDate($new['DOB']);
992 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
993 foreach ($new as $key => $value) {
994 if ($key == 'id') continue;
995 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
997 $db_id = sqlInsert($sql);
1000 $db_id = $new['id'];
1001 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1002 // Check for brain damage:
1003 if ($pid != $rez['pid']) {
1004 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1005 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1008 $sql = "UPDATE patient_data SET date = NOW()";
1009 foreach ($new as $key => $value) {
1010 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1012 $sql .= " WHERE id = '$db_id'";
1019 function newEmployerData( $pid,
1028 return sqlInsert("insert into employer_data set
1031 postal_code='$postal_code',
1040 // Create or update employer data from an array.
1042 function updateEmployerData($pid, $new, $create=false)
1044 $colnames = array('name','street','city','state','postal_code','country');
1047 $set .= "pid = '$pid', date = NOW()";
1048 foreach ($colnames as $key) {
1049 $value = isset($new[$key]) ? $new[$key] : '';
1050 $set .= ", `$key` = '$value'";
1052 return sqlInsert("INSERT INTO employer_data SET $set");
1056 $old = getEmployerData($pid);
1058 foreach ($colnames as $key) {
1059 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1060 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1061 $value = $new[$key];
1064 $set .= "`$key` = '$value', ";
1067 $set .= "pid = '$pid', date = NOW()";
1068 return sqlInsert("INSERT INTO employer_data SET $set");
1074 // This updates or adds the given insurance data info, while retaining any
1075 // previously added insurance_data rows that should be preserved.
1076 // This does not directly support the maintenance of non-current insurance.
1078 function newInsuranceData(
1082 $policy_number = "",
1085 $subscriber_lname = "",
1086 $subscriber_mname = "",
1087 $subscriber_fname = "",
1088 $subscriber_relationship = "",
1089 $subscriber_ss = "",
1090 $subscriber_DOB = "",
1091 $subscriber_street = "",
1092 $subscriber_postal_code = "",
1093 $subscriber_city = "",
1094 $subscriber_state = "",
1095 $subscriber_country = "",
1096 $subscriber_phone = "",
1097 $subscriber_employer = "",
1098 $subscriber_employer_street = "",
1099 $subscriber_employer_city = "",
1100 $subscriber_employer_postal_code = "",
1101 $subscriber_employer_state = "",
1102 $subscriber_employer_country = "",
1104 $subscriber_sex = "",
1105 $effective_date = "0000-00-00",
1106 $accept_assignment = "TRUE",
1109 if (strlen($type) <= 0) return FALSE;
1111 // If a bad date was passed, err on the side of caution.
1112 $effective_date = fixDate($effective_date, date('Y-m-d'));
1114 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1115 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1116 $idrow = sqlFetchArray($idres);
1118 // Replace the most recent entry in any of the following cases:
1119 // * Its effective date is >= this effective date.
1120 // * It is the first entry and it has no (insurance) provider.
1121 // * There is no encounter that is earlier than the new effective date but
1122 // on or after the old effective date.
1123 // Otherwise insert a new entry.
1127 if (strcmp($idrow['date'], $effective_date) > 0) {
1131 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1135 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1136 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1137 "date >= '" . $idrow['date'] . " 00:00:00'");
1138 if ($ferow['count'] == 0) $replace = true;
1145 // TBD: This is a bit dangerous in that a typo in entering the effective
1146 // date can wipe out previous insurance history. So we want some data
1147 // entry validation somewhere.
1148 sqlStatement("DELETE FROM insurance_data WHERE " .
1149 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1150 "id != " . $idrow['id']);
1153 $data['type'] = $type;
1154 $data['provider'] = $provider;
1155 $data['policy_number'] = $policy_number;
1156 $data['group_number'] = $group_number;
1157 $data['plan_name'] = $plan_name;
1158 $data['subscriber_lname'] = $subscriber_lname;
1159 $data['subscriber_mname'] = $subscriber_mname;
1160 $data['subscriber_fname'] = $subscriber_fname;
1161 $data['subscriber_relationship'] = $subscriber_relationship;
1162 $data['subscriber_ss'] = $subscriber_ss;
1163 $data['subscriber_DOB'] = $subscriber_DOB;
1164 $data['subscriber_street'] = $subscriber_street;
1165 $data['subscriber_postal_code'] = $subscriber_postal_code;
1166 $data['subscriber_city'] = $subscriber_city;
1167 $data['subscriber_state'] = $subscriber_state;
1168 $data['subscriber_country'] = $subscriber_country;
1169 $data['subscriber_phone'] = $subscriber_phone;
1170 $data['subscriber_employer'] = $subscriber_employer;
1171 $data['subscriber_employer_city'] = $subscriber_employer_city;
1172 $data['subscriber_employer_street'] = $subscriber_employer_street;
1173 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1174 $data['subscriber_employer_state'] = $subscriber_employer_state;
1175 $data['subscriber_employer_country'] = $subscriber_employer_country;
1176 $data['copay'] = $copay;
1177 $data['subscriber_sex'] = $subscriber_sex;
1178 $data['pid'] = $pid;
1179 $data['date'] = $effective_date;
1180 $data['accept_assignment'] = $accept_assignment;
1181 $data['policy_type'] = $policy_type;
1182 updateInsuranceData($idrow['id'], $data);
1183 return $idrow['id'];
1186 return sqlInsert("INSERT INTO insurance_data SET
1188 provider = '$provider',
1189 policy_number = '$policy_number',
1190 group_number = '$group_number',
1191 plan_name = '$plan_name',
1192 subscriber_lname = '$subscriber_lname',
1193 subscriber_mname = '$subscriber_mname',
1194 subscriber_fname = '$subscriber_fname',
1195 subscriber_relationship = '$subscriber_relationship',
1196 subscriber_ss = '$subscriber_ss',
1197 subscriber_DOB = '$subscriber_DOB',
1198 subscriber_street = '$subscriber_street',
1199 subscriber_postal_code = '$subscriber_postal_code',
1200 subscriber_city = '$subscriber_city',
1201 subscriber_state = '$subscriber_state',
1202 subscriber_country = '$subscriber_country',
1203 subscriber_phone = '$subscriber_phone',
1204 subscriber_employer = '$subscriber_employer',
1205 subscriber_employer_city = '$subscriber_employer_city',
1206 subscriber_employer_street = '$subscriber_employer_street',
1207 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1208 subscriber_employer_state = '$subscriber_employer_state',
1209 subscriber_employer_country = '$subscriber_employer_country',
1211 subscriber_sex = '$subscriber_sex',
1213 date = '$effective_date',
1214 accept_assignment = '$accept_assignment',
1215 policy_type = '$policy_type'
1220 // This is used internally only.
1221 function updateInsuranceData($id, $new)
1223 $fields = sqlListFields("insurance_data");
1226 while(list($key, $value) = each ($new)) {
1227 if (in_array($key, $fields)) {
1228 $use[$key] = $value;
1232 $sql = "UPDATE insurance_data SET ";
1233 while(list($key, $value) = each($use))
1234 $sql .= "`$key` = '$value', ";
1235 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1240 function newHistoryData($pid, $new=false) {
1241 $arraySqlBind = array();
1242 $sql = "insert into history_data set pid = ?, date = NOW()";
1243 array_push($arraySqlBind,$pid);
1245 while(list($key, $value) = each($new)) {
1246 array_push($arraySqlBind,$value);
1247 $sql .= ", `$key` = ?";
1250 return sqlInsert($sql, $arraySqlBind );
1253 function updateHistoryData($pid,$new)
1255 $real = getHistoryData($pid);
1256 while(list($key, $value) = each ($new))
1257 $real[$key] = $value;
1259 // need to unset date, so can reset it below
1260 unset($real['date']);
1262 $arraySqlBind = array();
1263 $sql = "insert into history_data set `date` = NOW(), ";
1264 while(list($key, $value) = each($real)) {
1265 array_push($arraySqlBind,$value);
1266 $sql .= "`$key` = ?, ";
1268 $sql = substr($sql, 0, -2);
1270 return sqlInsert($sql, $arraySqlBind );
1274 // in months if < 2 years old
1275 // in years if > 2 years old
1276 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1277 // (optional) nowYMD is a date in YYYYMMDD format
1278 function getPatientAge($dobYMD, $nowYMD=null)
1280 // strip any dashes from the DOB
1281 $dobYMD = preg_replace("/-/", "", $dobYMD);
1282 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1284 // set the 'now' date values
1285 if ($nowYMD == null) {
1286 $nowDay = date("d");
1287 $nowMonth = date("m");
1288 $nowYear = date("Y");
1291 $nowDay = substr($nowYMD,6,2);
1292 $nowMonth = substr($nowYMD,4,2);
1293 $nowYear = substr($nowYMD,0,4);
1296 $dayDiff = $nowDay - $dobDay;
1297 $monthDiff = $nowMonth - $dobMonth;
1298 $yearDiff = $nowYear - $dobYear;
1300 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1302 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1303 if($dayDiff<0) { $ageInMonths-=1; }
1305 if ( $ageInMonths > 24 ) {
1307 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1308 else if ($monthDiff < 0) { $age -= 1; }
1311 $age = "$ageInMonths " . xl('month');
1318 * Wrapper to make sure the clinical rules dates formats corresponds to the
1319 * format expected by getPatientAgeYMD
1321 * @param string $dob date of birth
1322 * @param string $target date to calculate age on
1323 * @return array containing
1324 * age - decimal age in years
1325 * age_in_months - decimal age in months
1326 * ageinYMD - formatted string #y #m #d */
1327 function parseAgeInfo($dob,$target)
1329 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1330 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1331 // Prepare target (Y-M-D H:M:S)
1332 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1334 return getPatientAgeYMD($dateDOB,$dateTarget);
1342 * @return array containing
1343 * age - decimal age in years
1344 * age_in_months - decimal age in months
1345 * ageinYMD - formatted string #y #m #d
1347 function getPatientAgeYMD($dob, $date=null) {
1349 if ($date == null) {
1350 $daynow = date("d");
1351 $monthnow = date("m");
1352 $yearnow = date("Y");
1353 $datenow=$yearnow.$monthnow.$daynow;
1356 $datenow=preg_replace("/-/", "", $date);
1357 $yearnow=substr($datenow,0,4);
1358 $monthnow=substr($datenow,4,2);
1359 $daynow=substr($datenow,6,2);
1360 $datenow=$yearnow.$monthnow.$daynow;
1363 $dob=preg_replace("/-/", "", $dob);
1364 $dobyear=substr($dob,0,4);
1365 $dobmonth=substr($dob,4,2);
1366 $dobday=substr($dob,6,2);
1367 $dob=$dobyear.$dobmonth.$dobday;
1369 //to compensate for 30, 31, 28, 29 days/month
1370 $mo=$monthnow; //to avoid confusion with later calculation
1372 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1373 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1374 } // look at April, June, September, November for calculation. These months only have 30 days.
1375 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1376 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1377 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1378 else {$nd=28;} //otherwise, it is not a leap year.
1380 else {$nd=31;} // other months have 31 days
1382 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1383 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1385 $age_year = $yearnow - $dobyear - 1;
1386 if ($daynow < $dobday) {
1387 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1388 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1391 $months_since_birthday=12 - $dobmonth + $monthnow;
1392 $days_since_dobday=$daynow - $dobday;
1395 else // if patient has had birthday this calandar year
1397 $age_year = $yearnow - $dobyear;
1398 if ($daynow < $dobday) {
1399 $months_since_birthday=$monthnow - $dobmonth -1;
1400 $days_since_dobday=$nd - $dobday + $daynow;
1403 $months_since_birthday=$monthnow - $dobmonth;
1404 $days_since_dobday=$daynow - $dobday;
1408 $day_as_month_decimal = $days_since_dobday / 30;
1409 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1410 $month_as_year_decimal = $months_since_birthday_float / 12;
1411 $age_float = $age_year + $month_as_year_decimal;
1413 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1414 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1415 $age = round($age_float,2);
1417 // round the years to 2 floating points
1418 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1419 return compact('age','age_in_months','ageinYMD');
1422 // Returns Age in days
1423 // in months if < 2 years old
1424 // in years if > 2 years old
1425 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1426 // (optional) nowYMD is a date in YYYYMMDD format
1427 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1430 // strip any dashes from the DOB
1431 $dobYMD = preg_replace("/-/", "", $dobYMD);
1432 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1434 // set the 'now' date values
1435 if ($nowYMD == null) {
1436 $nowDay = date("d");
1437 $nowMonth = date("m");
1438 $nowYear = date("Y");
1441 $nowDay = substr($nowYMD,6,2);
1442 $nowMonth = substr($nowYMD,4,2);
1443 $nowYear = substr($nowYMD,0,4);
1447 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1448 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1449 $timediff = $nowtime - $dobtime;
1450 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1455 * Returns a string to be used to display a patient's age
1457 * @param type $dobYMD
1458 * @param type $asOfYMD
1459 * @return string suitable for displaying patient's age based on preferences
1461 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1463 if($GLOBALS['age_display_format']=='1')
1465 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1466 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1468 return $ageYMD['ageinYMD'];
1472 return getPatientAge($dobYMD, $asOfYMD);
1477 return getPatientAge($dobYMD, $asOfYMD);
1481 function dateToDB ($date)
1483 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1488 // ----------------------------------------------------------------------------
1490 * DROPDOWN FOR COUNTRIES
1492 * build a dropdown with all countries from geo_country_reference
1494 * @param int $selected - id for selected record
1495 * @param string $name - the name/id for select form
1496 * @return void - just echo the html encoded string
1498 function dropdown_countries($selected = 0, $name = 'country_code') {
1499 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1501 $string = "<select name='$name' id='$name'>";
1502 while ( $row = sqlFetchArray($r) ) {
1503 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1504 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1507 $string .= '</select>';
1512 // ----------------------------------------------------------------------------
1514 * DROPDOWN FOR YES/NO
1516 * build a dropdown with two options (yes - 1, no - 0)
1518 * @param int $selected - id for selected record
1519 * @param string $name - the name/id for select form
1520 * @return void - just echo the html encoded string
1522 function dropdown_yesno($selected = 0, $name = 'yesno') {
1523 $string = "<select name='$name' id='$name'>";
1525 $selected = (int)$selected;
1526 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1527 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1529 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1530 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1531 $string .= '</select>';
1536 // ----------------------------------------------------------------------------
1538 * DROPDOWN FOR MALE/FEMALE options
1540 * build a dropdown with three options (unselected/male/female)
1542 * @param int $selected - id for selected record
1543 * @param string $name - the name/id for select form
1544 * @return void - just echo the html encoded string
1546 function dropdown_sex($selected = 0, $name = 'sex') {
1547 $string = "<select name='$name' id='$name'>";
1549 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1550 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1551 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1553 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1554 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1555 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1556 $string .= '</select>';
1561 // ----------------------------------------------------------------------------
1563 * DROPDOWN FOR MARITAL STATUS
1565 * build a dropdown with marital status
1567 * @param int $selected - id for selected record
1568 * @param string $name - the name/id for select form
1569 * @return void - just echo the html encoded string
1571 function dropdown_marital($selected = 0, $name = 'status') {
1572 $string = "<select name='$name' id='$name'>";
1574 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1576 foreach ( $statii as $st ) {
1577 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1578 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1581 $string .= '</select>';
1586 // ----------------------------------------------------------------------------
1588 * DROPDOWN FOR PROVIDERS
1590 * build a dropdown with all providers
1592 * @param int $selected - id for selected record
1593 * @param string $name - the name/id for select form
1594 * @return void - just echo the html encoded string
1596 function dropdown_providers($selected = 0, $name = 'status') {
1597 $provideri = getProviderInfo();
1599 $string = "<select name='$name' id='$name'>";
1600 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1601 foreach ( $provideri as $s ) {
1602 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1603 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1606 $string .= '</select>';
1611 // ----------------------------------------------------------------------------
1613 * DROPDOWN FOR INSURANCE COMPANIES
1615 * build a dropdown with all insurers
1617 * @param int $selected - id for selected record
1618 * @param string $name - the name/id for select form
1619 * @return void - just echo the html encoded string
1621 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1622 $insurancei = getInsuranceProviders();
1624 $string = "<select name='$name' id='$name'>";
1625 $string .= '<option value="0">Onbekend</option>';
1626 foreach ( $insurancei as $iid => $iname ) {
1627 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1628 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1631 $string .= '</select>';
1637 // ----------------------------------------------------------------------------
1641 * return the name or the country code, function of arguments
1643 * @param int $country_code
1644 * @param string $country_name
1645 * @return string | int - name or code
1647 function country_code($country_code = 0, $country_name = '') {
1649 if ( $country_code ) {
1650 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1652 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1655 $db = $GLOBALS['adodb']['db'];
1656 $result = $db->Execute($sql);
1657 if ($result && !$result->EOF) {
1658 $strint = $result->fields['res'];
1664 function DBToDate ($date)
1666 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1671 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1672 * for the given patient on the given date.
1674 * @param int The PID of the patient.
1675 * @param string Date in yyyy-mm-dd format.
1676 * @return array Array of 0-3 insurance_data rows.
1678 function getEffectiveInsurances($patient_id, $encdate) {
1680 foreach (array('primary','secondary','tertiary') as $instype) {
1681 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1682 "WHERE pid = ? AND type = ? " .
1683 "AND date <= ? ORDER BY date DESC LIMIT 1",
1684 array($patient_id, $instype, $encdate));
1685 if (empty($tmp['provider'])) break;
1692 * Get the patient's balance due. Normally this excludes amounts that are out
1693 * to insurance. If you want to include what insurance owes, set the second
1694 * parameter to true.
1696 * @param int The PID of the patient.
1697 * @param boolean Indicates if amounts owed by insurance are to be included.
1698 * @return number The balance.
1700 function get_patient_balance($pid, $with_insurance=false) {
1702 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1703 "last_level_closed, stmt_count " .
1704 "FROM form_encounter WHERE pid = ?", array($pid));
1705 while ($ferow = sqlFetchArray($feres)) {
1706 $encounter = $ferow['encounter'];
1707 $dos = substr($ferow['date'], 0, 10);
1708 $insarr = getEffectiveInsurances($pid, $dos);
1709 $inscount = count($insarr);
1710 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1711 // It's out to insurance so only the co-pay might be due.
1712 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1713 "pid = ? AND encounter = ? AND " .
1714 "code_type = 'copay' AND activity = 1",
1715 array($pid, $encounter));
1716 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1717 "FROM ar_activity WHERE " .
1718 "pid = ? AND encounter = ? AND payer_type = 0",
1719 array($pid, $encounter));
1720 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1721 if ($ptbal > 0) $balance += $ptbal;
1724 // Including insurance or not out to insurance, everything is due.
1725 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1726 "pid = ? AND encounter = ? AND " .
1727 "activity = 1", array($pid, $encounter));
1728 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1729 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1730 "pid = ? AND encounter = ?", array($pid, $encounter));
1731 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1732 "pid = ? AND encounter = ?", array($pid, $encounter));
1733 $balance += $brow['amount'] + $srow['amount']
1734 - $drow['payments'] - $drow['adjustments'];
1737 return sprintf('%01.2f', $balance);
1740 // Function to check if patient is deceased.
1742 // $pid - patient id
1743 // $date - date checking if deceased (will default to current date if blank)
1745 // If deceased, then will return the number of
1746 // days that patient has been deceased.
1747 // If not deceased, then will return false.
1748 function is_patient_deceased($pid,$date='') {
1750 // Set date to current if not set
1751 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1753 // Query for deceased status (gets days deceased if patient is deceased)
1754 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1755 "FROM `patient_data` " .
1756 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1758 if (empty($results)) {
1759 // Patient is alive, so return false
1763 // Patient is dead, so return the number of days patient has been deceased.
1764 // Don't let it be zero days or else will confuse calls to this function.
1765 if ($results['days_deceased'] === 0) {
1766 $results['days_deceased'] = 1;
1768 return $results['days_deceased'];