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 require_once("{$GLOBALS['srcdir']}/sql.inc");
12 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
14 // These are for sports team use:
15 $PLAYER_FITNESSES = array(
18 xl('Restricted Training'),
22 xl('International Duty')
24 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
26 // Hard-coding this array because its values and meanings are fixed by the 837p
27 // standard and we don't want people messing with them.
28 $policy_types = array(
30 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
31 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
32 '14' => xl('No-fault Insurance including Auto is Primary'),
33 '15' => xl('Worker`s Compensation'),
34 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
35 '41' => xl('Black Lung'),
36 '42' => xl('Veteran`s Administration'),
37 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
38 '47' => xl('Other Liability Insurance is Primary'),
42 * Get a patient's demographic data.
44 * @param int $pid The PID of the patient
45 * @param string $given an optional subsection of the patient's demographic
47 * @return array The requested subsection of a patient's demographic data.
48 * If no subsection was given, returns everything, with the
49 * date of birth as the last field.
51 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
52 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
53 return sqlQuery($sql, array($pid) );
56 function getLanguages() {
57 $returnval = array('','english');
58 $sql = "select distinct lower(language) as language from patient_data";
59 $rez = sqlStatement($sql);
60 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
61 if (($row["language"] != "english") && ($row["language"] != "")) {
62 array_push($returnval, $row["language"]);
68 function getInsuranceProvider($ins_id) {
70 $sql = "select name from insurance_companies where id=?";
71 $row = sqlQuery($sql,array($ins_id));
76 function getInsuranceProviders() {
80 $sql = "select name, id from insurance_companies order by name, id";
81 $rez = sqlStatement($sql);
82 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
83 $returnval[$row['id']] = $row['name'];
87 // Please leave this here. I have a user who wants to see zip codes and PO
88 // box numbers listed along with the insurance company names, as many companies
89 // have different billing addresses for different plans. -- Rod Roark
92 $sql = "select insurance_companies.name, insurance_companies.id, " .
93 "addresses.zip, addresses.line1 " .
94 "from insurance_companies, addresses " .
95 "where addresses.foreign_id = insurance_companies.id " .
96 "order by insurance_companies.name, addresses.zip";
98 $rez = sqlStatement($sql);
100 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
101 preg_match("/\d+/", $row['line1'], $matches);
102 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
103 "," . $matches[0] . ")";
110 function getInsuranceProvidersExtra() {
111 $returnval = array();
112 // add a global and if for where to allow inactive inscompanies
114 $sql = "select insurance_companies.name, insurance_companies.id, " .
115 "addresses.zip, addresses.line1, addresses.state " .
116 "from insurance_companies, addresses " .
117 "where addresses.foreign_id = insurance_companies.id " .
118 "order by insurance_companies.name, addresses.zip";
120 $rez = sqlStatement($sql);
122 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
123 switch ($GLOBALS['insurance_information']) {
124 case $GLOBALS['insurance_information'] = '0':
125 $returnval[$row['id']] = $row['name'];
127 case $GLOBALS['insurance_information'] = '1':
128 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
130 case $GLOBALS['insurance_information'] = '2':
131 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";
133 case $GLOBALS['insurance_information'] = '3':
134 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
136 case $GLOBALS['insurance_information'] = '4':
137 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
138 "," . $row['zip'] . ")";
140 case $GLOBALS['insurance_information'] = '5':
141 preg_match("/\d+/", $row['line1'], $matches);
142 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
143 "," . $matches[0] . ")";
151 function getProviders() {
152 $returnval = array("");
153 $sql = "select fname, lname from users where authorized = 1 and " .
154 "active = 1 and username != ''";
155 $rez = sqlStatement($sql);
156 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
157 if (($row["fname"] != "") && ($row["lname"] != "")) {
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 " .
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 the the base array so that $resultval[0]['key'] is also
314 //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 return $pi[0]['fname'] . " " . $pi[0]['lname'];
354 function getProviderId($providerName) {
355 $query = "select id from users where username = ?";
356 $rez = sqlStatement($query, array($providerName) );
357 for($iter=0; $row=sqlFetchArray($rez); $iter++)
358 $returnval[$iter]=$row;
362 function getEthnoRacials() {
363 $returnval = array("");
364 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
365 $rez = sqlStatement($sql);
366 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
367 if (($row["ethnoracial"] != "")) {
368 array_push($returnval, $row["ethnoracial"]);
374 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
377 if ($dateStart && $dateEnd) {
378 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
380 else if ($dateStart && !$dateEnd) {
381 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
383 else if (!$dateStart && $dateEnd) {
384 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
387 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
390 if($given == 'tobacco'){
391 $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));
397 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
398 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
400 $sql = "select $given from insurance_data as insd " .
401 "left join insurance_companies as ic on ic.id = insd.provider " .
402 "where pid = ? and type = ? order by date DESC limit 1";
403 return sqlQuery($sql, array($pid, $type) );
406 function getInsuranceDataByDate($pid, $date, $type,
407 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
408 { // this must take the date in the following manner: YYYY-MM-DD
409 // this function recalls the insurance value that was most recently enterred from the
410 // given date. it will call up most recent records up to and on the date given,
411 // but not records enterred after the given date
412 $sql = "select $given from insurance_data as insd " .
413 "left join insurance_companies as ic on ic.id = provider " .
414 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
415 "type=? order by date DESC limit 1";
416 return sqlQuery($sql, array($pid,$date,$type) );
419 function getEmployerData($pid, $given = "*")
421 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
422 return sqlQuery($sql, array($pid) );
425 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
426 // When the limit is exceeded, find out what the unlimited count would be.
427 $GLOBALS['PATIENT_INC_COUNT'] = $count;
428 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
429 if ($limit != "all") {
430 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
431 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
436 * Allow the last name to be followed by a comma and some part of a first name(can
437 * also place middle name after the first name with a space separating them)
438 * Allows comma alone followed by some part of a first name(can also place middle name
439 * after the first name with a space separating them).
440 * Allows comma alone preceded by some part of a last name.
441 * If no comma or space, then will search both last name and first name.
442 * If the first letter of either name is capital, searches for name starting
443 * with given substring (the expected behavior). If it is lower case, it
444 * searches for the substring anywhere in the name. This applies to either
445 * last name, first name, and middle name.
446 * Also allows first name followed by middle and/or last name when separated by spaces.
447 * @param string $term
448 * @param string $given
449 * @param string $orderby
450 * @param string $limit
451 * @param string $start
454 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")
456 $names = getPatientNameSplit($term);
458 foreach ($names as $key => $val) {
460 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
461 $names[$key] = '%' . $val . '%';
463 $names[$key] = $val . '%';
468 // Debugging section below
469 //if(array_key_exists('first',$names)) {
470 // error_log("first name search term :".$names['first']);
472 //if(array_key_exists('middle',$names)) {
473 // error_log("middle name search term :".$names['middle']);
475 //if(array_key_exists('last',$names)) {
476 // error_log("last name search term :".$names['last']);
478 // Debugging section above
480 $sqlBindArray = array();
481 if(array_key_exists('last',$names) && $names['last'] == '') {
482 // Do not search last name
483 $where = "fname LIKE ? ";
484 array_push($sqlBindArray, $names['first']);
485 if ($names['middle'] != '') {
486 $where .= "AND mname LIKE ? ";
487 array_push($sqlBindArray, $names['middle']);
489 } elseif(array_key_exists('first',$names) && $names['first'] == '') {
490 // Do not search first name or middle name
491 $where = "lname LIKE ? ";
492 array_push($sqlBindArray, $names['last']);
493 } elseif($names['first'] == '' && $names['last'] != '') {
494 // Search both first name and last name with same term
495 $names['first'] = $names['last'];
496 $where = "lname LIKE ? OR fname LIKE ? ";
497 array_push($sqlBindArray, $names['last'], $names['first']);
498 } elseif ($names['middle'] != '') {
499 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
500 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
502 $where = "lname LIKE ? AND fname LIKE ? ";
503 array_push($sqlBindArray, $names['last'], $names['first']);
506 if (!empty($GLOBALS['pt_restrict_field'])) {
507 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
508 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
509 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
510 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
511 array_push($sqlBindArray, $_SESSION{"authUser"});
515 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
516 if ($limit != "all") $sql .= " LIMIT $start, $limit";
518 $rez = sqlStatement($sql, $sqlBindArray);
521 for($iter=0; $row=sqlFetchArray($rez); $iter++)
522 $returnval[$iter] = $row;
524 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
528 * Accept a string used by a search function expected to find a patient name,
529 * then split up the string if a comma or space exists. Return an array having
530 * from 1 to 3 elements, named first, middle, and last.
531 * See above getPatientLnames() function for details on how the splitting occurs.
532 * @param string $term
535 function getPatientNameSplit($term) {
537 if (strpos($term, ',') !== false) {
538 $names = explode(',', $term);
539 $n['last'] = $names[0];
540 if (strpos(trim($names[1]), ' ') !== false) {
541 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
543 $n['first'] = $names[1];
545 } elseif (strpos($term, ' ') !== false) {
546 $names = explode(' ', $term);
547 if (count($names) == 1) {
548 $n['last'] = $names[0];
549 } elseif (count($names) == 3) {
550 $n['first'] = $names[0];
551 $n['middle'] = $names[1];
552 $n['last'] = $names[2];
554 // This will handle first and last name or first followed by
555 // multiple names only using just the last of the names in the list.
556 $n['first'] = $names[0];
557 $n['last'] = end($names);
561 if(empty($n['last'])) $n['last'] = '%';
563 // Trim whitespace off the names before returning
564 foreach($n as $key => $val) {
565 $n[$key] = trim($val);
567 return $n; // associative array containing names
570 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")
573 $sqlBindArray = array();
574 $where = "pubpid LIKE ? ";
575 array_push($sqlBindArray, $pid."%");
576 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
577 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
578 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
579 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
580 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
581 array_push($sqlBindArray, $_SESSION{"authUser"});
585 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
586 if ($limit != "all") $sql .= " limit $start, $limit";
587 $rez = sqlStatement($sql, $sqlBindArray);
588 for($iter=0; $row=sqlFetchArray($rez); $iter++)
589 $returnval[$iter]=$row;
591 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
595 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")
597 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
599 $sqlBindArray = array();
601 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
605 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
606 array_push($sqlBindArray, "%".$searchTerm."%");
609 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
610 if ($limit != "all") $sql .= " limit $start, $limit";
611 $rez = sqlStatement($sql, $sqlBindArray);
612 for($iter=0; $row=sqlFetchArray($rez); $iter++)
613 $returnval[$iter]=$row;
614 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
618 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
619 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
620 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
622 $layoutCols = explode( '~', $searchFields );
623 $sqlBindArray = array();
626 foreach ($layoutCols as $val) {
627 if (empty($val)) continue;
632 $where .= " ".add_escape_custom($val)." = ? ";
633 array_push($sqlBindArray, $searchTerm);
636 $where .= " ".add_escape_custom($val)." like ? ";
637 array_push($sqlBindArray, $searchTerm."%");
642 // If no search terms, ensure valid syntax.
643 if ($i == 0) $where = "1 = 1";
645 // If a non-empty service code was given, then restrict to patients who
646 // have been provided that service. Since the code is used in a LIKE
647 // clause, % and _ wildcards are supported.
648 if ($search_service_code) {
649 $where = "( $where ) AND " .
650 "( SELECT COUNT(*) FROM billing AS b WHERE " .
651 "b.pid = patient_data.pid AND " .
652 "b.activity = 1 AND " .
653 "b.code_type != 'COPAY' AND " .
656 array_push($sqlBindArray, $search_service_code);
659 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
660 if ($limit != "all") $sql .= " limit $start, $limit";
661 $rez = sqlStatement($sql, $sqlBindArray);
662 for($iter=0; $row=sqlFetchArray($rez); $iter++)
663 $returnval[$iter]=$row;
664 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
668 // return a collection of Patient PIDs
669 // new arg style by JRM March 2008
670 // 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")
671 function getPatientPID($args)
674 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
675 $orderby = "lname ASC, fname ASC";
679 // alter default values if defined in the passed in args
680 if (isset($args['pid'])) { $pid = $args['pid']; }
681 if (isset($args['given'])) { $given = $args['given']; }
682 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
683 if (isset($args['limit'])) { $limit = $args['limit']; }
684 if (isset($args['start'])) { $start = $args['start']; }
687 if ($pid == -1) $pid = "%";
688 elseif (empty($pid)) $pid = "NULL";
690 if (strstr($pid,"%")) $command = "like";
692 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
693 if ($limit != "all") $sql .= " limit $start, $limit";
695 $rez = sqlStatement($sql);
696 for($iter=0; $row=sqlFetchArray($rez); $iter++)
697 $returnval[$iter]=$row;
702 /* return a patient's name in the format LAST, FIRST */
703 function getPatientName($pid) {
704 if (empty($pid)) return "";
705 $patientData = getPatientPID(array("pid"=>$pid));
706 if (empty($patientData[0]['lname'])) return "";
707 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
711 /* find patient data by DOB */
712 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
714 $DOB = fixDate($DOB, $DOB);
715 $sqlBindArray = array();
716 $where = "DOB like ? ";
717 array_push($sqlBindArray, $DOB."%");
718 if (!empty($GLOBALS['pt_restrict_field'])) {
719 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
720 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
721 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
722 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
723 array_push($sqlBindArray, $_SESSION{"authUser"});
727 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
729 if ($limit != "all") $sql .= " LIMIT $start, $limit";
731 $rez = sqlStatement($sql, $sqlBindArray);
732 for($iter=0; $row=sqlFetchArray($rez); $iter++)
733 $returnval[$iter]=$row;
735 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
739 /* find patient data by SSN */
740 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
742 $sqlBindArray = array();
743 $where = "ss LIKE ?";
744 array_push($sqlBindArray, $ss."%");
745 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
746 if ($limit != "all") $sql .= " LIMIT $start, $limit";
748 $rez = sqlStatement($sql, $sqlBindArray);
749 for($iter=0; $row=sqlFetchArray($rez); $iter++)
750 $returnval[$iter]=$row;
752 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
756 //(CHEMED) Search by phone number
757 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
759 $phone = preg_replace( "/[[:punct:]]/","", $phone );
760 $sqlBindArray = array();
761 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
762 array_push($sqlBindArray, $phone);
763 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
764 if ($limit != "all") $sql .= " LIMIT $start, $limit";
766 $rez = sqlStatement($sql, $sqlBindArray);
767 for($iter=0; $row=sqlFetchArray($rez); $iter++)
768 $returnval[$iter]=$row;
770 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
774 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
776 $sql="select $given from patient_data order by $orderby";
779 $sql .= " limit $start, $limit";
781 $rez = sqlStatement($sql);
782 for($iter=0; $row=sqlFetchArray($rez); $iter++)
783 $returnval[$iter]=$row;
788 //----------------------input functions
789 function newPatientData( $db_id="",
807 $contact_relationship = "",
814 $migrantseasonal = "",
816 $monthly_income = "",
818 $financial_review = "",
832 $drivers_license = "",
838 $DOB = fixDate($DOB);
839 $regdate = fixDate($regdate);
842 $referral_source = '';
844 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
845 // Check for brain damage:
846 if ($db_id != $rez['id']) {
847 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
848 $rez['id'] . "' to '$db_id' for pid '$pid'";
851 $fitness = $rez['fitness'];
852 $referral_source = $rez['referral_source'];
855 // Get the default price level.
856 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
857 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
858 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
860 $query = ("replace into patient_data set
869 postal_code='$postal_code',
872 country_code='$country_code',
873 drivers_license='$drivers_license',
875 occupation='$occupation',
876 phone_home='$phone_home',
877 phone_biz='$phone_biz',
878 phone_contact='$phone_contact',
880 contact_relationship='$contact_relationship',
881 referrer='$referrer',
882 referrerID='$referrerID',
884 language='$language',
885 ethnoracial='$ethnoracial',
886 interpretter='$interpretter',
887 migrantseasonal='$migrantseasonal',
888 family_size='$family_size',
889 monthly_income='$monthly_income',
890 homeless='$homeless',
891 financial_review='$financial_review',
894 providerID = '$providerID',
895 genericname1 = '$genericname1',
896 genericval1 = '$genericval1',
897 genericname2 = '$genericname2',
898 genericval2 = '$genericval2',
899 billing_note= '$billing_note';
900 phone_cell = '$phone_cell',
901 pharmacy_id = '$pharmacy_id',
902 hipaa_mail = '$hipaa_mail',
903 hipaa_voice = '$hipaa_voice',
904 hipaa_notice = '$hipaa_notice',
905 hipaa_message = '$hipaa_message',
908 referral_source='$referral_source',
910 pricelevel='$pricelevel',
913 $id = sqlInsert($query);
916 // find the last inserted id for new patient case
917 $db_id = getSqlLastID();
920 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
925 // Supported input date formats are:
927 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
929 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
931 function fixDate($date, $default="0000-00-00") {
932 $fixed_date = $default;
934 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
935 $dmy = preg_split("'[/.-]'", $date);
937 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
939 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
940 if ($dmy[2] < 1000) $dmy[2] += 1900;
941 if ($dmy[2] < 1910) $dmy[2] += 100;
943 // phone_country_code indicates format of ambiguous input dates.
944 if ($GLOBALS['phone_country_code'] == 1)
945 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
947 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
954 function pdValueOrNull($key, $value) {
955 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
956 substr($key, 0, 8) == 'userdate') &&
957 (empty($value) || $value == '0000-00-00'))
966 // Create or update patient data from an array.
968 function updatePatientData($pid, $new, $create=false)
970 /*******************************************************************
971 $real = getPatientData($pid);
972 $new['DOB'] = fixDate($new['DOB']);
973 while(list($key, $value) = each ($new))
974 $real[$key] = $value;
975 $real['date'] = "'+NOW()+'";
977 $sql = "insert into patient_data set ";
978 while(list($key, $value) = each($real))
979 $sql .= $key." = '$value', ";
980 $sql = substr($sql, 0, -2);
981 return sqlInsert($sql);
982 *******************************************************************/
984 // The above was broken, though seems intent to insert a new patient_data
985 // row for each update. A good idea, but nothing is doing that yet so
986 // the code below does not yet attempt it.
988 $new['DOB'] = fixDate($new['DOB']);
991 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
992 foreach ($new as $key => $value) {
993 if ($key == 'id') continue;
994 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
996 $db_id = sqlInsert($sql);
1000 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1001 // Check for brain damage:
1002 if ($pid != $rez['pid']) {
1003 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1004 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1007 $sql = "UPDATE patient_data SET date = NOW()";
1008 foreach ($new as $key => $value) {
1009 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1011 $sql .= " WHERE id = '$db_id'";
1018 function newEmployerData( $pid,
1027 return sqlInsert("insert into employer_data set
1030 postal_code='$postal_code',
1039 // Create or update employer data from an array.
1041 function updateEmployerData($pid, $new, $create=false)
1043 $colnames = array('name','street','city','state','postal_code','country');
1046 $set .= "pid = '$pid', date = NOW()";
1047 foreach ($colnames as $key) {
1048 $value = isset($new[$key]) ? $new[$key] : '';
1049 $set .= ", `$key` = '$value'";
1051 return sqlInsert("INSERT INTO employer_data SET $set");
1055 $old = getEmployerData($pid);
1057 foreach ($colnames as $key) {
1058 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1059 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1060 $value = $new[$key];
1063 $set .= "`$key` = '$value', ";
1066 $set .= "pid = '$pid', date = NOW()";
1067 return sqlInsert("INSERT INTO employer_data SET $set");
1073 // This updates or adds the given insurance data info, while retaining any
1074 // previously added insurance_data rows that should be preserved.
1075 // This does not directly support the maintenance of non-current insurance.
1077 function newInsuranceData(
1081 $policy_number = "",
1084 $subscriber_lname = "",
1085 $subscriber_mname = "",
1086 $subscriber_fname = "",
1087 $subscriber_relationship = "",
1088 $subscriber_ss = "",
1089 $subscriber_DOB = "",
1090 $subscriber_street = "",
1091 $subscriber_postal_code = "",
1092 $subscriber_city = "",
1093 $subscriber_state = "",
1094 $subscriber_country = "",
1095 $subscriber_phone = "",
1096 $subscriber_employer = "",
1097 $subscriber_employer_street = "",
1098 $subscriber_employer_city = "",
1099 $subscriber_employer_postal_code = "",
1100 $subscriber_employer_state = "",
1101 $subscriber_employer_country = "",
1103 $subscriber_sex = "",
1104 $effective_date = "0000-00-00",
1105 $accept_assignment = "TRUE",
1108 if (strlen($type) <= 0) return FALSE;
1110 // If a bad date was passed, err on the side of caution.
1111 $effective_date = fixDate($effective_date, date('Y-m-d'));
1113 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1114 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1115 $idrow = sqlFetchArray($idres);
1117 // Replace the most recent entry in any of the following cases:
1118 // * Its effective date is >= this effective date.
1119 // * It is the first entry and it has no (insurance) provider.
1120 // * There is no encounter that is earlier than the new effective date but
1121 // on or after the old effective date.
1122 // Otherwise insert a new entry.
1126 if (strcmp($idrow['date'], $effective_date) > 0) {
1130 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1134 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1135 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1136 "date >= '" . $idrow['date'] . " 00:00:00'");
1137 if ($ferow['count'] == 0) $replace = true;
1144 // TBD: This is a bit dangerous in that a typo in entering the effective
1145 // date can wipe out previous insurance history. So we want some data
1146 // entry validation somewhere.
1147 sqlStatement("DELETE FROM insurance_data WHERE " .
1148 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1149 "id != " . $idrow['id']);
1152 $data['type'] = $type;
1153 $data['provider'] = $provider;
1154 $data['policy_number'] = $policy_number;
1155 $data['group_number'] = $group_number;
1156 $data['plan_name'] = $plan_name;
1157 $data['subscriber_lname'] = $subscriber_lname;
1158 $data['subscriber_mname'] = $subscriber_mname;
1159 $data['subscriber_fname'] = $subscriber_fname;
1160 $data['subscriber_relationship'] = $subscriber_relationship;
1161 $data['subscriber_ss'] = $subscriber_ss;
1162 $data['subscriber_DOB'] = $subscriber_DOB;
1163 $data['subscriber_street'] = $subscriber_street;
1164 $data['subscriber_postal_code'] = $subscriber_postal_code;
1165 $data['subscriber_city'] = $subscriber_city;
1166 $data['subscriber_state'] = $subscriber_state;
1167 $data['subscriber_country'] = $subscriber_country;
1168 $data['subscriber_phone'] = $subscriber_phone;
1169 $data['subscriber_employer'] = $subscriber_employer;
1170 $data['subscriber_employer_city'] = $subscriber_employer_city;
1171 $data['subscriber_employer_street'] = $subscriber_employer_street;
1172 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1173 $data['subscriber_employer_state'] = $subscriber_employer_state;
1174 $data['subscriber_employer_country'] = $subscriber_employer_country;
1175 $data['copay'] = $copay;
1176 $data['subscriber_sex'] = $subscriber_sex;
1177 $data['pid'] = $pid;
1178 $data['date'] = $effective_date;
1179 $data['accept_assignment'] = $accept_assignment;
1180 $data['policy_type'] = $policy_type;
1181 updateInsuranceData($idrow['id'], $data);
1182 return $idrow['id'];
1185 return sqlInsert("INSERT INTO insurance_data SET
1187 provider = '$provider',
1188 policy_number = '$policy_number',
1189 group_number = '$group_number',
1190 plan_name = '$plan_name',
1191 subscriber_lname = '$subscriber_lname',
1192 subscriber_mname = '$subscriber_mname',
1193 subscriber_fname = '$subscriber_fname',
1194 subscriber_relationship = '$subscriber_relationship',
1195 subscriber_ss = '$subscriber_ss',
1196 subscriber_DOB = '$subscriber_DOB',
1197 subscriber_street = '$subscriber_street',
1198 subscriber_postal_code = '$subscriber_postal_code',
1199 subscriber_city = '$subscriber_city',
1200 subscriber_state = '$subscriber_state',
1201 subscriber_country = '$subscriber_country',
1202 subscriber_phone = '$subscriber_phone',
1203 subscriber_employer = '$subscriber_employer',
1204 subscriber_employer_city = '$subscriber_employer_city',
1205 subscriber_employer_street = '$subscriber_employer_street',
1206 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1207 subscriber_employer_state = '$subscriber_employer_state',
1208 subscriber_employer_country = '$subscriber_employer_country',
1210 subscriber_sex = '$subscriber_sex',
1212 date = '$effective_date',
1213 accept_assignment = '$accept_assignment',
1214 policy_type = '$policy_type'
1219 // This is used internally only.
1220 function updateInsuranceData($id, $new)
1222 $fields = sqlListFields("insurance_data");
1225 while(list($key, $value) = each ($new)) {
1226 if (in_array($key, $fields)) {
1227 $use[$key] = $value;
1231 $sql = "UPDATE insurance_data SET ";
1232 while(list($key, $value) = each($use))
1233 $sql .= "`$key` = '$value', ";
1234 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1239 function newHistoryData($pid, $new=false) {
1240 $arraySqlBind = array();
1241 $sql = "insert into history_data set pid = ?, date = NOW()";
1242 array_push($arraySqlBind,$pid);
1244 while(list($key, $value) = each($new)) {
1245 array_push($arraySqlBind,$value);
1246 $sql .= ", `$key` = ?";
1249 return sqlInsert($sql, $arraySqlBind );
1252 function updateHistoryData($pid,$new)
1254 $real = getHistoryData($pid);
1255 while(list($key, $value) = each ($new))
1256 $real[$key] = $value;
1258 // need to unset date, so can reset it below
1259 unset($real['date']);
1261 $arraySqlBind = array();
1262 $sql = "insert into history_data set `date` = NOW(), ";
1263 while(list($key, $value) = each($real)) {
1264 array_push($arraySqlBind,$value);
1265 $sql .= "`$key` = ?, ";
1267 $sql = substr($sql, 0, -2);
1269 return sqlInsert($sql, $arraySqlBind );
1273 // in months if < 2 years old
1274 // in years if > 2 years old
1275 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1276 // (optional) nowYMD is a date in YYYYMMDD format
1277 function getPatientAge($dobYMD, $nowYMD=null)
1279 // strip any dashes from the DOB
1280 $dobYMD = preg_replace("/-/", "", $dobYMD);
1281 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1283 // set the 'now' date values
1284 if ($nowYMD == null) {
1285 $nowDay = date("d");
1286 $nowMonth = date("m");
1287 $nowYear = date("Y");
1290 $nowDay = substr($nowYMD,6,2);
1291 $nowMonth = substr($nowYMD,4,2);
1292 $nowYear = substr($nowYMD,0,4);
1295 $dayDiff = $nowDay - $dobDay;
1296 $monthDiff = $nowMonth - $dobMonth;
1297 $yearDiff = $nowYear - $dobYear;
1299 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1301 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1302 if($dayDiff<0) { $ageInMonths-=1; }
1304 if ( $ageInMonths > 24 ) {
1306 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1307 else if ($monthDiff < 0) { $age -= 1; }
1310 $age = "$ageInMonths " . xl('month');
1317 * Wrapper to make sure the clinical rules dates formats corresponds to the
1318 * format expected by getPatientAgeYMD
1320 * @param string $dob date of birth
1321 * @param string $target date to calculate age on
1322 * @return array containing
1323 * age - decimal age in years
1324 * age_in_months - decimal age in months
1325 * ageinYMD - formatted string #y #m #d */
1326 function parseAgeInfo($dob,$target)
1328 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1329 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1330 // Prepare target (Y-M-D H:M:S)
1331 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1333 return getPatientAgeYMD($dateDOB,$dateTarget);
1341 * @return array containing
1342 * age - decimal age in years
1343 * age_in_months - decimal age in months
1344 * ageinYMD - formatted string #y #m #d
1346 function getPatientAgeYMD($dob, $date=null) {
1348 if ($date == null) {
1349 $daynow = date("d");
1350 $monthnow = date("m");
1351 $yearnow = date("Y");
1352 $datenow=$yearnow.$monthnow.$daynow;
1355 $datenow=preg_replace("/-/", "", $date);
1356 $yearnow=substr($datenow,0,4);
1357 $monthnow=substr($datenow,4,2);
1358 $daynow=substr($datenow,6,2);
1359 $datenow=$yearnow.$monthnow.$daynow;
1362 $dob=preg_replace("/-/", "", $dob);
1363 $dobyear=substr($dob,0,4);
1364 $dobmonth=substr($dob,4,2);
1365 $dobday=substr($dob,6,2);
1366 $dob=$dobyear.$dobmonth.$dobday;
1368 //to compensate for 30, 31, 28, 29 days/month
1369 $mo=$monthnow; //to avoid confusion with later calculation
1371 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1372 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1373 } // look at April, June, September, November for calculation. These months only have 30 days.
1374 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1375 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1376 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1377 else {$nd=28;} //otherwise, it is not a leap year.
1379 else {$nd=31;} // other months have 31 days
1381 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1382 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1384 $age_year = $yearnow - $dobyear - 1;
1385 if ($daynow < $dobday) {
1386 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1387 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1390 $months_since_birthday=12 - $dobmonth + $monthnow;
1391 $days_since_dobday=$daynow - $dobday;
1394 else // if patient has had birthday this calandar year
1396 $age_year = $yearnow - $dobyear;
1397 if ($daynow < $dobday) {
1398 $months_since_birthday=$monthnow - $dobmonth -1;
1399 $days_since_dobday=$nd - $dobday + $daynow;
1402 $months_since_birthday=$monthnow - $dobmonth;
1403 $days_since_dobday=$daynow - $dobday;
1407 $day_as_month_decimal = $days_since_dobday / 30;
1408 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1409 $month_as_year_decimal = $months_since_birthday_float / 12;
1410 $age_float = $age_year + $month_as_year_decimal;
1412 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1413 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1414 $age = round($age_float,2);
1416 // round the years to 2 floating points
1417 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1418 return compact('age','age_in_months','ageinYMD');
1421 // Returns Age in days
1422 // in months if < 2 years old
1423 // in years if > 2 years old
1424 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1425 // (optional) nowYMD is a date in YYYYMMDD format
1426 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1429 // strip any dashes from the DOB
1430 $dobYMD = preg_replace("/-/", "", $dobYMD);
1431 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1433 // set the 'now' date values
1434 if ($nowYMD == null) {
1435 $nowDay = date("d");
1436 $nowMonth = date("m");
1437 $nowYear = date("Y");
1440 $nowDay = substr($nowYMD,6,2);
1441 $nowMonth = substr($nowYMD,4,2);
1442 $nowYear = substr($nowYMD,0,4);
1446 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1447 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1448 $timediff = $nowtime - $dobtime;
1449 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1454 * Returns a string to be used to display a patient's age
1456 * @param type $dobYMD
1457 * @param type $asOfYMD
1458 * @return string suitable for displaying patient's age based on preferences
1460 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1462 if($GLOBALS['age_display_format']=='1')
1464 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1465 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1467 return $ageYMD['ageinYMD'];
1471 return getPatientAge($dobYMD, $asOfYMD);
1476 return getPatientAge($dobYMD, $asOfYMD);
1480 function dateToDB ($date)
1482 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1487 // ----------------------------------------------------------------------------
1489 * DROPDOWN FOR COUNTRIES
1491 * build a dropdown with all countries from geo_country_reference
1493 * @param int $selected - id for selected record
1494 * @param string $name - the name/id for select form
1495 * @return void - just echo the html encoded string
1497 function dropdown_countries($selected = 0, $name = 'country_code') {
1498 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1500 $string = "<select name='$name' id='$name'>";
1501 while ( $row = sqlFetchArray($r) ) {
1502 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1503 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1506 $string .= '</select>';
1511 // ----------------------------------------------------------------------------
1513 * DROPDOWN FOR YES/NO
1515 * build a dropdown with two options (yes - 1, no - 0)
1517 * @param int $selected - id for selected record
1518 * @param string $name - the name/id for select form
1519 * @return void - just echo the html encoded string
1521 function dropdown_yesno($selected = 0, $name = 'yesno') {
1522 $string = "<select name='$name' id='$name'>";
1524 $selected = (int)$selected;
1525 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1526 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1528 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1529 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1530 $string .= '</select>';
1535 // ----------------------------------------------------------------------------
1537 * DROPDOWN FOR MALE/FEMALE options
1539 * build a dropdown with three options (unselected/male/female)
1541 * @param int $selected - id for selected record
1542 * @param string $name - the name/id for select form
1543 * @return void - just echo the html encoded string
1545 function dropdown_sex($selected = 0, $name = 'sex') {
1546 $string = "<select name='$name' id='$name'>";
1548 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1549 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1550 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1552 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1553 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1554 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1555 $string .= '</select>';
1560 // ----------------------------------------------------------------------------
1562 * DROPDOWN FOR MARITAL STATUS
1564 * build a dropdown with marital status
1566 * @param int $selected - id for selected record
1567 * @param string $name - the name/id for select form
1568 * @return void - just echo the html encoded string
1570 function dropdown_marital($selected = 0, $name = 'status') {
1571 $string = "<select name='$name' id='$name'>";
1573 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1575 foreach ( $statii as $st ) {
1576 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1577 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1580 $string .= '</select>';
1585 // ----------------------------------------------------------------------------
1587 * DROPDOWN FOR PROVIDERS
1589 * build a dropdown with all providers
1591 * @param int $selected - id for selected record
1592 * @param string $name - the name/id for select form
1593 * @return void - just echo the html encoded string
1595 function dropdown_providers($selected = 0, $name = 'status') {
1596 $provideri = getProviderInfo();
1598 $string = "<select name='$name' id='$name'>";
1599 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1600 foreach ( $provideri as $s ) {
1601 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1602 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1605 $string .= '</select>';
1610 // ----------------------------------------------------------------------------
1612 * DROPDOWN FOR INSURANCE COMPANIES
1614 * build a dropdown with all insurers
1616 * @param int $selected - id for selected record
1617 * @param string $name - the name/id for select form
1618 * @return void - just echo the html encoded string
1620 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1621 $insurancei = getInsuranceProviders();
1623 $string = "<select name='$name' id='$name'>";
1624 $string .= '<option value="0">Onbekend</option>';
1625 foreach ( $insurancei as $iid => $iname ) {
1626 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1627 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1630 $string .= '</select>';
1636 // ----------------------------------------------------------------------------
1640 * return the name or the country code, function of arguments
1642 * @param int $country_code
1643 * @param string $country_name
1644 * @return string | int - name or code
1646 function country_code($country_code = 0, $country_name = '') {
1648 if ( $country_code ) {
1649 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1651 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1654 $db = $GLOBALS['adodb']['db'];
1655 $result = $db->Execute($sql);
1656 if ($result && !$result->EOF) {
1657 $strint = $result->fields['res'];
1663 function DBToDate ($date)
1665 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1670 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1671 * for the given patient on the given date.
1673 * @param int The PID of the patient.
1674 * @param string Date in yyyy-mm-dd format.
1675 * @return array Array of 0-3 insurance_data rows.
1677 function getEffectiveInsurances($patient_id, $encdate) {
1679 foreach (array('primary','secondary','tertiary') as $instype) {
1680 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1681 "WHERE pid = ? AND type = ? " .
1682 "AND date <= ? ORDER BY date DESC LIMIT 1",
1683 array($patient_id, $instype, $encdate));
1684 if (empty($tmp['provider'])) break;
1691 * Get the patient's balance due. Normally this excludes amounts that are out
1692 * to insurance. If you want to include what insurance owes, set the second
1693 * parameter to true.
1695 * @param int The PID of the patient.
1696 * @param boolean Indicates if amounts owed by insurance are to be included.
1697 * @return number The balance.
1699 function get_patient_balance($pid, $with_insurance=false) {
1701 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1702 "last_level_closed, stmt_count " .
1703 "FROM form_encounter WHERE pid = ?", array($pid));
1704 while ($ferow = sqlFetchArray($feres)) {
1705 $encounter = $ferow['encounter'];
1706 $dos = substr($ferow['date'], 0, 10);
1707 $insarr = getEffectiveInsurances($pid, $dos);
1708 $inscount = count($insarr);
1709 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1710 // It's out to insurance so only the co-pay might be due.
1711 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1712 "pid = ? AND encounter = ? AND " .
1713 "code_type = 'copay' AND activity = 1",
1714 array($pid, $encounter));
1715 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1716 "FROM ar_activity WHERE " .
1717 "pid = ? AND encounter = ? AND payer_type = 0",
1718 array($pid, $encounter));
1719 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1720 if ($ptbal > 0) $balance += $ptbal;
1723 // Including insurance or not out to insurance, everything is due.
1724 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1725 "pid = ? AND encounter = ? AND " .
1726 "activity = 1", array($pid, $encounter));
1727 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1728 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1729 "pid = ? AND encounter = ?", array($pid, $encounter));
1730 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1731 "pid = ? AND encounter = ?", array($pid, $encounter));
1732 $balance += $brow['amount'] + $srow['amount']
1733 - $drow['payments'] - $drow['adjustments'];
1736 return sprintf('%01.2f', $balance);
1739 // Function to check if patient is deceased.
1741 // $pid - patient id
1742 // $date - date checking if deceased (will default to current date if blank)
1744 // If deceased, then will return the number of
1745 // days that patient has been deceased.
1746 // If not deceased, then will return false.
1747 function is_patient_deceased($pid,$date='') {
1749 // Set date to current if not set
1750 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1752 // Query for deceased status (gets days deceased if patient is deceased)
1753 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1754 "FROM `patient_data` " .
1755 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1757 if (empty($results)) {
1758 // Patient is alive, so return false
1762 // Patient is dead, so return the number of days patient has been deceased.
1763 // Don't let it be zero days or else will confuse calls to this function.
1764 if ($results['days_deceased'] === 0) {
1765 $results['days_deceased'] = 1;
1767 return $results['days_deceased'];