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(dirname(__FILE__) . "/classes/WSWrapper.class.php");
13 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
15 // These are for sports team use:
16 $PLAYER_FITNESSES = array(
19 xl('Restricted Training'),
23 xl('International Duty')
25 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
27 // Hard-coding this array because its values and meanings are fixed by the 837p
28 // standard and we don't want people messing with them.
29 $policy_types = array(
31 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
32 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
33 '14' => xl('No-fault Insurance including Auto is Primary'),
34 '15' => xl('Worker`s Compensation'),
35 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
36 '41' => xl('Black Lung'),
37 '42' => xl('Veteran`s Administration'),
38 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
39 '47' => xl('Other Liability Insurance is Primary'),
43 * Get a patient's demographic data.
45 * @param int $pid The PID of the patient
46 * @param string $given an optional subsection of the patient's demographic
48 * @return array The requested subsection of a patient's demographic data.
49 * If no subsection was given, returns everything, with the
50 * date of birth as the last field.
52 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
53 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
54 return sqlQuery($sql, array($pid) );
57 function getLanguages() {
58 $returnval = array('','english');
59 $sql = "select distinct lower(language) as language from patient_data";
60 $rez = sqlStatement($sql);
61 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
62 if (($row["language"] != "english") && ($row["language"] != "")) {
63 array_push($returnval, $row["language"]);
69 function getInsuranceProvider($ins_id) {
71 $sql = "select name from insurance_companies where id=?";
72 $row = sqlQuery($sql,array($ins_id));
77 function getInsuranceProviders() {
81 $sql = "select name, id from insurance_companies order by name, id";
82 $rez = sqlStatement($sql);
83 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
84 $returnval[$row['id']] = $row['name'];
88 // Please leave this here. I have a user who wants to see zip codes and PO
89 // box numbers listed along with the insurance company names, as many companies
90 // have different billing addresses for different plans. -- Rod Roark
93 $sql = "select insurance_companies.name, insurance_companies.id, " .
94 "addresses.zip, addresses.line1 " .
95 "from insurance_companies, addresses " .
96 "where addresses.foreign_id = insurance_companies.id " .
97 "order by insurance_companies.name, addresses.zip";
99 $rez = sqlStatement($sql);
101 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
102 preg_match("/\d+/", $row['line1'], $matches);
103 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
104 "," . $matches[0] . ")";
111 function getInsuranceProvidersExtra() {
112 $returnval = array();
113 // add a global and if for where to allow inactive inscompanies
115 $sql = "select insurance_companies.name, insurance_companies.id, " .
116 "addresses.zip, addresses.line1, addresses.state " .
117 "from insurance_companies, addresses " .
118 "where addresses.foreign_id = insurance_companies.id " .
119 "order by insurance_companies.name, addresses.zip";
121 $rez = sqlStatement($sql);
123 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
124 switch ($GLOBALS['insurance_information']) {
125 case $GLOBALS['insurance_information'] = '0':
126 $returnval[$row['id']] = $row['name'];
128 case $GLOBALS['insurance_information'] = '1':
129 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
131 case $GLOBALS['insurance_information'] = '2':
132 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";
134 case $GLOBALS['insurance_information'] = '3':
135 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
137 case $GLOBALS['insurance_information'] = '4':
138 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
139 "," . $row['zip'] . ")";
141 case $GLOBALS['insurance_information'] = '5':
142 preg_match("/\d+/", $row['line1'], $matches);
143 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
144 "," . $matches[0] . ")";
152 function getProviders() {
153 $returnval = array("");
154 $sql = "select fname, lname from users where authorized = 1 and " .
155 "active = 1 and username != ''";
156 $rez = sqlStatement($sql);
157 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
158 if (($row["fname"] != "") && ($row["lname"] != "")) {
159 array_push($returnval, $row["fname"] . " " . $row["lname"]);
165 // ----------------------------------------------------------------------------
166 // Get one facility row. If the ID is not specified, then get either the
167 // "main" (billing) facility, or the default facility of the currently
168 // logged-in user. This was created to support genFacilityTitle() but
169 // may find additional uses.
171 function getFacility($facid=0) {
173 //create a sql binding array
174 $sqlBindArray = array();
177 $query = "SELECT * FROM facility WHERE id = ?";
178 array_push($sqlBindArray,$facid);
180 else if ($facid == 0) {
181 $query = "SELECT * FROM facility ORDER BY " .
182 "billing_location DESC, service_location, id LIMIT 1";
185 $query = "SELECT facility.* FROM users, facility WHERE " .
186 "users.id = ? AND " .
187 "facility.id = users.facility_id";
188 array_push($sqlBindArray,$_SESSION['authUserID']);
190 return sqlQuery($query,$sqlBindArray);
193 // Generate a report title including report name and facility name, address
196 function genFacilityTitle($repname='', $facid=0) {
198 $s .= "<table class='ftitletable'>\n";
200 $s .= " <td class='ftitlecell1'>$repname</td>\n";
201 $s .= " <td class='ftitlecell2'>\n";
202 $r = getFacility($facid);
204 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
205 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
206 if ($r['city'] || $r['state'] || $r['postal_code']) {
208 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
210 if ($r['city']) $s .= ", \n";
211 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
213 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
216 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
217 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
228 returns all facilities or just the id for the first one
229 (FACILITY FILTERING (lemonsoftware))
231 @param string - if 'first' return first facility ordered by id
232 @return array | int for 'first' case
234 function getFacilities($first = '') {
235 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
237 while ( $row = sqlFetchArray($r) ) {
241 if ( $first == 'first') {
242 return $ret[0]['id'];
249 GET SERVICE FACILITIES
251 returns all service_location facilities or just the id for the first one
252 (FACILITY FILTERING (CHEMED))
254 @param string - if 'first' return first facility ordered by id
255 @return array | int for 'first' case
257 function getServiceFacilities($first = '') {
258 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
260 while ( $row = sqlFetchArray($r) ) {
264 if ( $first == 'first') {
265 return $ret[0]['id'];
271 //(CHEMED) facility filter
272 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
274 if ($providers_only === 'any') {
275 $param1 = " AND authorized = 1 AND active = 1 ";
277 else if ($providers_only) {
278 $param1 = " AND authorized = 1 AND calendar = 1 ";
281 //--------------------------------
282 //(CHEMED) facility filter
285 if ($GLOBALS['restrict_user_facility']) {
286 $param2 = " AND (facility_id = $facility
290 where tablename = 'users'
296 $param2 = " AND facility_id = $facility ";
299 //--------------------------------
302 if ($providerID == "%") {
305 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
306 "from users where username != '' and active = 1 and id $command '" .
307 add_escape_custom($providerID) . "' " . $param1 . $param2;
308 // sort by last name -- JRM June 2008
309 $query .= " ORDER BY lname, fname ";
310 $rez = sqlStatement($query);
311 for($iter=0; $row=sqlFetchArray($rez); $iter++)
312 $returnval[$iter]=$row;
314 //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
315 //accessible from $resultval['key']
318 $akeys = array_keys($returnval[0]);
319 foreach($akeys as $key) {
320 $returnval[0][$key] = $returnval[0][$key];
326 //same as above but does not reduce if only 1 row returned
327 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
329 if ($providers_only) {
330 $param1 = "AND authorized=1";
333 if ($providerID == "%") {
336 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
337 "from users where active = 1 and username != '' and id $command '" .
338 add_escape_custom($providerID) . "' " . $param1;
340 $rez = sqlStatement($query);
341 for($iter=0; $row=sqlFetchArray($rez); $iter++)
342 $returnval[$iter]=$row;
347 function getProviderName($providerID) {
348 $pi = getProviderInfo($providerID, 'any');
349 if (strlen($pi[0]["lname"]) > 0) {
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);
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");
922 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
923 $phone_biz,$phone_cell,$email,$pid);
928 // Supported input date formats are:
930 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
932 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
934 function fixDate($date, $default="0000-00-00") {
935 $fixed_date = $default;
937 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
938 $dmy = preg_split("'[/.-]'", $date);
940 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
942 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
943 if ($dmy[2] < 1000) $dmy[2] += 1900;
944 if ($dmy[2] < 1910) $dmy[2] += 100;
946 // phone_country_code indicates format of ambiguous input dates.
947 if ($GLOBALS['phone_country_code'] == 1)
948 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
950 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
957 function pdValueOrNull($key, $value) {
958 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
959 substr($key, 0, 8) == 'userdate') &&
960 (empty($value) || $value == '0000-00-00'))
969 // Create or update patient data from an array.
971 function updatePatientData($pid, $new, $create=false)
973 /*******************************************************************
974 $real = getPatientData($pid);
975 $new['DOB'] = fixDate($new['DOB']);
976 while(list($key, $value) = each ($new))
977 $real[$key] = $value;
978 $real['date'] = "'+NOW()+'";
980 $sql = "insert into patient_data set ";
981 while(list($key, $value) = each($real))
982 $sql .= $key." = '$value', ";
983 $sql = substr($sql, 0, -2);
984 return sqlInsert($sql);
985 *******************************************************************/
987 // The above was broken, though seems intent to insert a new patient_data
988 // row for each update. A good idea, but nothing is doing that yet so
989 // the code below does not yet attempt it.
991 $new['DOB'] = fixDate($new['DOB']);
994 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
995 foreach ($new as $key => $value) {
996 if ($key == 'id') continue;
997 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
999 $db_id = sqlInsert($sql);
1002 $db_id = $new['id'];
1003 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1004 // Check for brain damage:
1005 if ($pid != $rez['pid']) {
1006 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1007 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1010 $sql = "UPDATE patient_data SET date = NOW()";
1011 foreach ($new as $key => $value) {
1012 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1014 $sql .= " WHERE id = '$db_id'";
1018 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
1019 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
1020 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
1021 $rez['phone_cell'],$rez['email'],$rez['pid']);
1026 function newEmployerData( $pid,
1035 return sqlInsert("insert into employer_data set
1038 postal_code='$postal_code',
1047 // Create or update employer data from an array.
1049 function updateEmployerData($pid, $new, $create=false)
1051 $colnames = array('name','street','city','state','postal_code','country');
1054 $set .= "pid = '$pid', date = NOW()";
1055 foreach ($colnames as $key) {
1056 $value = isset($new[$key]) ? $new[$key] : '';
1057 $set .= ", `$key` = '$value'";
1059 return sqlInsert("INSERT INTO employer_data SET $set");
1063 $old = getEmployerData($pid);
1065 foreach ($colnames as $key) {
1066 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1067 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1068 $value = $new[$key];
1071 $set .= "`$key` = '$value', ";
1074 $set .= "pid = '$pid', date = NOW()";
1075 return sqlInsert("INSERT INTO employer_data SET $set");
1081 // This updates or adds the given insurance data info, while retaining any
1082 // previously added insurance_data rows that should be preserved.
1083 // This does not directly support the maintenance of non-current insurance.
1085 function newInsuranceData(
1089 $policy_number = "",
1092 $subscriber_lname = "",
1093 $subscriber_mname = "",
1094 $subscriber_fname = "",
1095 $subscriber_relationship = "",
1096 $subscriber_ss = "",
1097 $subscriber_DOB = "",
1098 $subscriber_street = "",
1099 $subscriber_postal_code = "",
1100 $subscriber_city = "",
1101 $subscriber_state = "",
1102 $subscriber_country = "",
1103 $subscriber_phone = "",
1104 $subscriber_employer = "",
1105 $subscriber_employer_street = "",
1106 $subscriber_employer_city = "",
1107 $subscriber_employer_postal_code = "",
1108 $subscriber_employer_state = "",
1109 $subscriber_employer_country = "",
1111 $subscriber_sex = "",
1112 $effective_date = "0000-00-00",
1113 $accept_assignment = "TRUE",
1116 if (strlen($type) <= 0) return FALSE;
1118 // If a bad date was passed, err on the side of caution.
1119 $effective_date = fixDate($effective_date, date('Y-m-d'));
1121 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1122 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1123 $idrow = sqlFetchArray($idres);
1125 // Replace the most recent entry in any of the following cases:
1126 // * Its effective date is >= this effective date.
1127 // * It is the first entry and it has no (insurance) provider.
1128 // * There is no encounter that is earlier than the new effective date but
1129 // on or after the old effective date.
1130 // Otherwise insert a new entry.
1134 if (strcmp($idrow['date'], $effective_date) > 0) {
1138 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1142 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1143 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1144 "date >= '" . $idrow['date'] . " 00:00:00'");
1145 if ($ferow['count'] == 0) $replace = true;
1152 // TBD: This is a bit dangerous in that a typo in entering the effective
1153 // date can wipe out previous insurance history. So we want some data
1154 // entry validation somewhere.
1155 sqlStatement("DELETE FROM insurance_data WHERE " .
1156 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1157 "id != " . $idrow['id']);
1160 $data['type'] = $type;
1161 $data['provider'] = $provider;
1162 $data['policy_number'] = $policy_number;
1163 $data['group_number'] = $group_number;
1164 $data['plan_name'] = $plan_name;
1165 $data['subscriber_lname'] = $subscriber_lname;
1166 $data['subscriber_mname'] = $subscriber_mname;
1167 $data['subscriber_fname'] = $subscriber_fname;
1168 $data['subscriber_relationship'] = $subscriber_relationship;
1169 $data['subscriber_ss'] = $subscriber_ss;
1170 $data['subscriber_DOB'] = $subscriber_DOB;
1171 $data['subscriber_street'] = $subscriber_street;
1172 $data['subscriber_postal_code'] = $subscriber_postal_code;
1173 $data['subscriber_city'] = $subscriber_city;
1174 $data['subscriber_state'] = $subscriber_state;
1175 $data['subscriber_country'] = $subscriber_country;
1176 $data['subscriber_phone'] = $subscriber_phone;
1177 $data['subscriber_employer'] = $subscriber_employer;
1178 $data['subscriber_employer_city'] = $subscriber_employer_city;
1179 $data['subscriber_employer_street'] = $subscriber_employer_street;
1180 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1181 $data['subscriber_employer_state'] = $subscriber_employer_state;
1182 $data['subscriber_employer_country'] = $subscriber_employer_country;
1183 $data['copay'] = $copay;
1184 $data['subscriber_sex'] = $subscriber_sex;
1185 $data['pid'] = $pid;
1186 $data['date'] = $effective_date;
1187 $data['accept_assignment'] = $accept_assignment;
1188 $data['policy_type'] = $policy_type;
1189 updateInsuranceData($idrow['id'], $data);
1190 return $idrow['id'];
1193 return sqlInsert("INSERT INTO insurance_data SET
1195 provider = '$provider',
1196 policy_number = '$policy_number',
1197 group_number = '$group_number',
1198 plan_name = '$plan_name',
1199 subscriber_lname = '$subscriber_lname',
1200 subscriber_mname = '$subscriber_mname',
1201 subscriber_fname = '$subscriber_fname',
1202 subscriber_relationship = '$subscriber_relationship',
1203 subscriber_ss = '$subscriber_ss',
1204 subscriber_DOB = '$subscriber_DOB',
1205 subscriber_street = '$subscriber_street',
1206 subscriber_postal_code = '$subscriber_postal_code',
1207 subscriber_city = '$subscriber_city',
1208 subscriber_state = '$subscriber_state',
1209 subscriber_country = '$subscriber_country',
1210 subscriber_phone = '$subscriber_phone',
1211 subscriber_employer = '$subscriber_employer',
1212 subscriber_employer_city = '$subscriber_employer_city',
1213 subscriber_employer_street = '$subscriber_employer_street',
1214 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1215 subscriber_employer_state = '$subscriber_employer_state',
1216 subscriber_employer_country = '$subscriber_employer_country',
1218 subscriber_sex = '$subscriber_sex',
1220 date = '$effective_date',
1221 accept_assignment = '$accept_assignment',
1222 policy_type = '$policy_type'
1227 // This is used internally only.
1228 function updateInsuranceData($id, $new)
1230 $fields = sqlListFields("insurance_data");
1233 while(list($key, $value) = each ($new)) {
1234 if (in_array($key, $fields)) {
1235 $use[$key] = $value;
1239 $sql = "UPDATE insurance_data SET ";
1240 while(list($key, $value) = each($use))
1241 $sql .= "`$key` = '$value', ";
1242 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1247 function newHistoryData($pid, $new=false) {
1248 $arraySqlBind = array();
1249 $sql = "insert into history_data set pid = ?, date = NOW()";
1250 array_push($arraySqlBind,$pid);
1252 while(list($key, $value) = each($new)) {
1253 array_push($arraySqlBind,$value);
1254 $sql .= ", `$key` = ?";
1257 return sqlInsert($sql, $arraySqlBind );
1260 function updateHistoryData($pid,$new)
1262 $real = getHistoryData($pid);
1263 while(list($key, $value) = each ($new))
1264 $real[$key] = $value;
1266 // need to unset date, so can reset it below
1267 unset($real['date']);
1269 $arraySqlBind = array();
1270 $sql = "insert into history_data set `date` = NOW(), ";
1271 while(list($key, $value) = each($real)) {
1272 array_push($arraySqlBind,$value);
1273 $sql .= "`$key` = ?, ";
1275 $sql = substr($sql, 0, -2);
1277 return sqlInsert($sql, $arraySqlBind );
1280 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1281 $phone_biz,$phone_cell,$email,$pid="")
1283 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1284 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1286 $db = $GLOBALS['adodb']['db'];
1287 $customer_info = array();
1289 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1290 $result = $db->Execute($sql);
1291 if ($result && !$result->EOF) {
1292 $customer_info['foreign_update'] = true;
1293 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1294 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1297 ///xml rpc code to connect to accounting package and add user to it
1298 $customer_info['firstname'] = $fname;
1299 $customer_info['lastname'] = $lname;
1300 $customer_info['address'] = $street;
1301 $customer_info['suburb'] = $city;
1302 $customer_info['state'] = $state;
1303 $customer_info['postcode'] = $postal_code;
1305 //ezybiz wants state as a code rather than abbreviation
1306 $customer_info['geo_zone_id'] = "";
1307 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1308 $db = $GLOBALS['adodb']['db'];
1309 $result = $db->Execute($sql);
1310 if ($result && !$result->EOF) {
1311 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1314 //ezybiz wants country as a code rather than abbreviation
1315 $customer_info['geo_country_id'] = "";
1316 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1317 $db = $GLOBALS['adodb']['db'];
1318 $result = $db->Execute($sql);
1319 if ($result && !$result->EOF) {
1320 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1323 $customer_info['phone1'] = $phone_home;
1324 $customer_info['phone1comment'] = "Home Phone";
1325 $customer_info['phone2'] = $phone_biz;
1326 $customer_info['phone2comment'] = "Business Phone";
1327 $customer_info['phone3'] = $phone_cell;
1328 $customer_info['phone3comment'] = "Cell Phone";
1329 $customer_info['email'] = $email;
1330 $customer_info['customernumber'] = $pid;
1332 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1333 $ws = new WSWrapper($function);
1335 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1336 if (is_numeric($ws->value)) {
1337 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1338 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1343 // in months if < 2 years old
1344 // in years if > 2 years old
1345 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1346 // (optional) nowYMD is a date in YYYYMMDD format
1347 function getPatientAge($dobYMD, $nowYMD=null)
1349 // strip any dashes from the DOB
1350 $dobYMD = preg_replace("/-/", "", $dobYMD);
1351 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1353 // set the 'now' date values
1354 if ($nowYMD == null) {
1355 $nowDay = date("d");
1356 $nowMonth = date("m");
1357 $nowYear = date("Y");
1360 $nowDay = substr($nowYMD,6,2);
1361 $nowMonth = substr($nowYMD,4,2);
1362 $nowYear = substr($nowYMD,0,4);
1365 $dayDiff = $nowDay - $dobDay;
1366 $monthDiff = $nowMonth - $dobMonth;
1367 $yearDiff = $nowYear - $dobYear;
1369 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1371 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1372 if($dayDiff<0) { $ageInMonths-=1; }
1374 if ( $ageInMonths > 24 ) {
1376 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1377 else if ($monthDiff < 0) { $age -= 1; }
1380 $age = "$ageInMonths month";
1387 * Wrapper to make sure the clinical rules dates formats corresponds to the
1388 * format expected by getPatientAgeYMD
1390 * @param string $dob date of birth
1391 * @param string $target date to calculate age on
1392 * @return array containing
1393 * age - decimal age in years
1394 * age_in_months - decimal age in months
1395 * ageinYMD - formatted string #y #m #d */
1396 function parseAgeInfo($dob,$target)
1398 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1399 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1400 // Prepare target (Y-M-D H:M:S)
1401 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1403 return getPatientAgeYMD($dateDOB,$dateTarget);
1411 * @return array containing
1412 * age - decimal age in years
1413 * age_in_months - decimal age in months
1414 * ageinYMD - formatted string #y #m #d
1416 function getPatientAgeYMD($dob, $date=null) {
1418 if ($date == null) {
1419 $daynow = date("d");
1420 $monthnow = date("m");
1421 $yearnow = date("Y");
1422 $datenow=$yearnow.$monthnow.$daynow;
1425 $datenow=preg_replace("/-/", "", $date);
1426 $yearnow=substr($datenow,0,4);
1427 $monthnow=substr($datenow,4,2);
1428 $daynow=substr($datenow,6,2);
1429 $datenow=$yearnow.$monthnow.$daynow;
1432 $dob=preg_replace("/-/", "", $dob);
1433 $dobyear=substr($dob,0,4);
1434 $dobmonth=substr($dob,4,2);
1435 $dobday=substr($dob,6,2);
1436 $dob=$dobyear.$dobmonth.$dobday;
1438 //to compensate for 30, 31, 28, 29 days/month
1439 $mo=$monthnow; //to avoid confusion with later calculation
1441 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1442 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1443 } // look at April, June, September, November for calculation. These months only have 30 days.
1444 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1445 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1446 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1447 else {$nd=28;} //otherwise, it is not a leap year.
1449 else {$nd=31;} // other months have 31 days
1451 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1452 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1454 $age_year = $yearnow - $dobyear - 1;
1455 if ($daynow < $dobday) {
1456 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1457 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1460 $months_since_birthday=12 - $dobmonth + $monthnow;
1461 $days_since_dobday=$daynow - $dobday;
1464 else // if patient has had birthday this calandar year
1466 $age_year = $yearnow - $dobyear;
1467 if ($daynow < $dobday) {
1468 $months_since_birthday=$monthnow - $dobmonth -1;
1469 $days_since_dobday=$nd - $dobday + $daynow;
1472 $months_since_birthday=$monthnow - $dobmonth;
1473 $days_since_dobday=$daynow - $dobday;
1477 $day_as_month_decimal = $days_since_dobday / 30;
1478 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1479 $month_as_year_decimal = $months_since_birthday_float / 12;
1480 $age_float = $age_year + $month_as_year_decimal;
1482 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1483 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1484 $age = round($age_float,2);
1486 // round the years to 2 floating points
1487 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1488 return compact('age','age_in_months','ageinYMD');
1491 // Returns Age in days
1492 // in months if < 2 years old
1493 // in years if > 2 years old
1494 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1495 // (optional) nowYMD is a date in YYYYMMDD format
1496 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1499 // strip any dashes from the DOB
1500 $dobYMD = preg_replace("/-/", "", $dobYMD);
1501 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1503 // set the 'now' date values
1504 if ($nowYMD == null) {
1505 $nowDay = date("d");
1506 $nowMonth = date("m");
1507 $nowYear = date("Y");
1510 $nowDay = substr($nowYMD,6,2);
1511 $nowMonth = substr($nowYMD,4,2);
1512 $nowYear = substr($nowYMD,0,4);
1516 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1517 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1518 $timediff = $nowtime - $dobtime;
1519 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1524 * Returns a string to be used to display a patient's age
1526 * @param type $dobYMD
1527 * @param type $asOfYMD
1528 * @return string suitable for displaying patient's age based on preferences
1530 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1532 if($GLOBALS['age_display_format']=='1')
1534 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1535 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1537 return $ageYMD['ageinYMD'];
1541 return getPatientAge($dobYMD, $asOfYMD);
1546 return getPatientAge($dobYMD, $asOfYMD);
1550 function dateToDB ($date)
1552 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1557 // ----------------------------------------------------------------------------
1559 * DROPDOWN FOR COUNTRIES
1561 * build a dropdown with all countries from geo_country_reference
1563 * @param int $selected - id for selected record
1564 * @param string $name - the name/id for select form
1565 * @return void - just echo the html encoded string
1567 function dropdown_countries($selected = 0, $name = 'country_code') {
1568 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1570 $string = "<select name='$name' id='$name'>";
1571 while ( $row = sqlFetchArray($r) ) {
1572 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1573 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1576 $string .= '</select>';
1581 // ----------------------------------------------------------------------------
1583 * DROPDOWN FOR YES/NO
1585 * build a dropdown with two options (yes - 1, no - 0)
1587 * @param int $selected - id for selected record
1588 * @param string $name - the name/id for select form
1589 * @return void - just echo the html encoded string
1591 function dropdown_yesno($selected = 0, $name = 'yesno') {
1592 $string = "<select name='$name' id='$name'>";
1594 $selected = (int)$selected;
1595 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1596 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1598 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1599 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1600 $string .= '</select>';
1605 // ----------------------------------------------------------------------------
1607 * DROPDOWN FOR MALE/FEMALE options
1609 * build a dropdown with three options (unselected/male/female)
1611 * @param int $selected - id for selected record
1612 * @param string $name - the name/id for select form
1613 * @return void - just echo the html encoded string
1615 function dropdown_sex($selected = 0, $name = 'sex') {
1616 $string = "<select name='$name' id='$name'>";
1618 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1619 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1620 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1622 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1623 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1624 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1625 $string .= '</select>';
1630 // ----------------------------------------------------------------------------
1632 * DROPDOWN FOR MARITAL STATUS
1634 * build a dropdown with marital status
1636 * @param int $selected - id for selected record
1637 * @param string $name - the name/id for select form
1638 * @return void - just echo the html encoded string
1640 function dropdown_marital($selected = 0, $name = 'status') {
1641 $string = "<select name='$name' id='$name'>";
1643 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1645 foreach ( $statii as $st ) {
1646 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1647 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1650 $string .= '</select>';
1655 // ----------------------------------------------------------------------------
1657 * DROPDOWN FOR PROVIDERS
1659 * build a dropdown with all providers
1661 * @param int $selected - id for selected record
1662 * @param string $name - the name/id for select form
1663 * @return void - just echo the html encoded string
1665 function dropdown_providers($selected = 0, $name = 'status') {
1666 $provideri = getProviderInfo();
1668 $string = "<select name='$name' id='$name'>";
1669 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1670 foreach ( $provideri as $s ) {
1671 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1672 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1675 $string .= '</select>';
1680 // ----------------------------------------------------------------------------
1682 * DROPDOWN FOR INSURANCE COMPANIES
1684 * build a dropdown with all insurers
1686 * @param int $selected - id for selected record
1687 * @param string $name - the name/id for select form
1688 * @return void - just echo the html encoded string
1690 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1691 $insurancei = getInsuranceProviders();
1693 $string = "<select name='$name' id='$name'>";
1694 $string .= '<option value="0">Onbekend</option>';
1695 foreach ( $insurancei as $iid => $iname ) {
1696 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1697 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1700 $string .= '</select>';
1706 // ----------------------------------------------------------------------------
1710 * return the name or the country code, function of arguments
1712 * @param int $country_code
1713 * @param string $country_name
1714 * @return string | int - name or code
1716 function country_code($country_code = 0, $country_name = '') {
1718 if ( $country_code ) {
1719 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1721 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1724 $db = $GLOBALS['adodb']['db'];
1725 $result = $db->Execute($sql);
1726 if ($result && !$result->EOF) {
1727 $strint = $result->fields['res'];
1733 function DBToDate ($date)
1735 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1740 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1741 * for the given patient on the given date.
1743 * @param int The PID of the patient.
1744 * @param string Date in yyyy-mm-dd format.
1745 * @return array Array of 0-3 insurance_data rows.
1747 function getEffectiveInsurances($patient_id, $encdate) {
1749 foreach (array('primary','secondary','tertiary') as $instype) {
1750 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1751 "WHERE pid = ? AND type = ? " .
1752 "AND date <= ? ORDER BY date DESC LIMIT 1",
1753 array($patient_id, $instype, $encdate));
1754 if (empty($tmp['provider'])) break;
1761 * Get the patient's balance due. Normally this excludes amounts that are out
1762 * to insurance. If you want to include what insurance owes, set the second
1763 * parameter to true.
1765 * @param int The PID of the patient.
1766 * @param boolean Indicates if amounts owed by insurance are to be included.
1767 * @return number The balance.
1769 function get_patient_balance($pid, $with_insurance=false) {
1770 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1772 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1773 "last_level_closed, stmt_count " .
1774 "FROM form_encounter WHERE pid = ?", array($pid));
1775 while ($ferow = sqlFetchArray($feres)) {
1776 $encounter = $ferow['encounter'];
1777 $dos = substr($ferow['date'], 0, 10);
1778 $insarr = getEffectiveInsurances($pid, $dos);
1779 $inscount = count($insarr);
1780 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1781 // It's out to insurance so only the co-pay might be due.
1782 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1783 "pid = ? AND encounter = ? AND " .
1784 "code_type = 'copay' AND activity = 1",
1785 array($pid, $encounter));
1786 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1787 "FROM ar_activity WHERE " .
1788 "pid = ? AND encounter = ? AND payer_type = 0",
1789 array($pid, $encounter));
1790 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1791 if ($ptbal > 0) $balance += $ptbal;
1794 // Including insurance or not out to insurance, everything is due.
1795 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1796 "pid = ? AND encounter = ? AND " .
1797 "activity = 1", array($pid, $encounter));
1798 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1799 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1800 "pid = ? AND encounter = ?", array($pid, $encounter));
1801 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1802 "pid = ? AND encounter = ?", array($pid, $encounter));
1803 $balance += $brow['amount'] + $srow['amount']
1804 - $drow['payments'] - $drow['adjustments'];
1807 return sprintf('%01.2f', $balance);
1809 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1810 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1811 $conn = $GLOBALS['adodb']['db'];
1812 $customer_info['id'] = 0;
1813 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1814 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1815 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1816 "im.foreign_table = 'customer'";
1817 $result = $conn->Execute($sql);
1818 if($result && !$result->EOF) {
1819 $customer_info['id'] = $result->fields['foreign_id'];
1821 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1822 $ws = new WSWrapper($function);
1823 if(is_numeric($ws->value)) {
1824 return sprintf('%01.2f', $ws->value);
1830 // Function to check if patient is deceased.
1832 // $pid - patient id
1833 // $date - date checking if deceased (will default to current date if blank)
1835 // If deceased, then will return the number of
1836 // days that patient has been deceased.
1837 // If not deceased, then will return false.
1838 function is_patient_deceased($pid,$date='') {
1840 // Set date to current if not set
1841 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1843 // Query for deceased status (gets days deceased if patient is deceased)
1844 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1845 "FROM `patient_data` " .
1846 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1848 if (empty($results)) {
1849 // Patient is alive, so return false
1853 // Patient is dead, so return the number of days patient has been deceased.
1854 // Don't let it be zero days or else will confuse calls to this function.
1855 if ($results['days_deceased'] === 0) {
1856 $results['days_deceased'] = 1;
1858 return $results['days_deceased'];