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);
562 if(empty($n['last'])) $n['last'] = '%';
564 // Trim whitespace off the names before returning
565 foreach($n as $key => $val) {
566 $n[$key] = trim($val);
568 return $n; // associative array containing names
571 function getPatientId($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
574 $sqlBindArray = array();
575 $where = "pubpid LIKE ? ";
576 array_push($sqlBindArray, $pid."%");
577 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
578 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
579 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
580 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
581 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
582 array_push($sqlBindArray, $_SESSION{"authUser"});
586 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
587 if ($limit != "all") $sql .= " limit $start, $limit";
588 $rez = sqlStatement($sql, $sqlBindArray);
589 for($iter=0; $row=sqlFetchArray($rez); $iter++)
590 $returnval[$iter]=$row;
592 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
596 function getByPatientDemographics($searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
598 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
600 $sqlBindArray = array();
602 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
606 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
607 array_push($sqlBindArray, "%".$searchTerm."%");
610 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
611 if ($limit != "all") $sql .= " limit $start, $limit";
612 $rez = sqlStatement($sql, $sqlBindArray);
613 for($iter=0; $row=sqlFetchArray($rez); $iter++)
614 $returnval[$iter]=$row;
615 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
619 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
620 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
621 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
623 $layoutCols = explode( '~', $searchFields );
624 $sqlBindArray = array();
627 foreach ($layoutCols as $val) {
628 if (empty($val)) continue;
633 $where .= " ".add_escape_custom($val)." = ? ";
634 array_push($sqlBindArray, $searchTerm);
637 $where .= " ".add_escape_custom($val)." like ? ";
638 array_push($sqlBindArray, $searchTerm."%");
643 // If no search terms, ensure valid syntax.
644 if ($i == 0) $where = "1 = 1";
646 // If a non-empty service code was given, then restrict to patients who
647 // have been provided that service. Since the code is used in a LIKE
648 // clause, % and _ wildcards are supported.
649 if ($search_service_code) {
650 $where = "( $where ) AND " .
651 "( SELECT COUNT(*) FROM billing AS b WHERE " .
652 "b.pid = patient_data.pid AND " .
653 "b.activity = 1 AND " .
654 "b.code_type != 'COPAY' AND " .
657 array_push($sqlBindArray, $search_service_code);
660 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
661 if ($limit != "all") $sql .= " limit $start, $limit";
662 $rez = sqlStatement($sql, $sqlBindArray);
663 for($iter=0; $row=sqlFetchArray($rez); $iter++)
664 $returnval[$iter]=$row;
665 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
669 // return a collection of Patient PIDs
670 // new arg style by JRM March 2008
671 // orig function getPatientPID($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
672 function getPatientPID($args)
675 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
676 $orderby = "lname ASC, fname ASC";
680 // alter default values if defined in the passed in args
681 if (isset($args['pid'])) { $pid = $args['pid']; }
682 if (isset($args['given'])) { $given = $args['given']; }
683 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
684 if (isset($args['limit'])) { $limit = $args['limit']; }
685 if (isset($args['start'])) { $start = $args['start']; }
688 if ($pid == -1) $pid = "%";
689 elseif (empty($pid)) $pid = "NULL";
691 if (strstr($pid,"%")) $command = "like";
693 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
694 if ($limit != "all") $sql .= " limit $start, $limit";
696 $rez = sqlStatement($sql);
697 for($iter=0; $row=sqlFetchArray($rez); $iter++)
698 $returnval[$iter]=$row;
703 /* return a patient's name in the format LAST, FIRST */
704 function getPatientName($pid) {
705 if (empty($pid)) return "";
706 $patientData = getPatientPID(array("pid"=>$pid));
707 if (empty($patientData[0]['lname'])) return "";
708 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
712 /* find patient data by DOB */
713 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
715 $DOB = fixDate($DOB, $DOB);
716 $sqlBindArray = array();
717 $where = "DOB like ? ";
718 array_push($sqlBindArray, $DOB."%");
719 if (!empty($GLOBALS['pt_restrict_field'])) {
720 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
721 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
722 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
723 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
724 array_push($sqlBindArray, $_SESSION{"authUser"});
728 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
730 if ($limit != "all") $sql .= " LIMIT $start, $limit";
732 $rez = sqlStatement($sql, $sqlBindArray);
733 for($iter=0; $row=sqlFetchArray($rez); $iter++)
734 $returnval[$iter]=$row;
736 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
740 /* find patient data by SSN */
741 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
743 $sqlBindArray = array();
744 $where = "ss LIKE ?";
745 array_push($sqlBindArray, $ss."%");
746 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
747 if ($limit != "all") $sql .= " LIMIT $start, $limit";
749 $rez = sqlStatement($sql, $sqlBindArray);
750 for($iter=0; $row=sqlFetchArray($rez); $iter++)
751 $returnval[$iter]=$row;
753 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
757 //(CHEMED) Search by phone number
758 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
760 $phone = preg_replace( "/[[:punct:]]/","", $phone );
761 $sqlBindArray = array();
762 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
763 array_push($sqlBindArray, $phone);
764 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
765 if ($limit != "all") $sql .= " LIMIT $start, $limit";
767 $rez = sqlStatement($sql, $sqlBindArray);
768 for($iter=0; $row=sqlFetchArray($rez); $iter++)
769 $returnval[$iter]=$row;
771 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
775 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
777 $sql="select $given from patient_data order by $orderby";
780 $sql .= " limit $start, $limit";
782 $rez = sqlStatement($sql);
783 for($iter=0; $row=sqlFetchArray($rez); $iter++)
784 $returnval[$iter]=$row;
789 //----------------------input functions
790 function newPatientData( $db_id="",
808 $contact_relationship = "",
815 $migrantseasonal = "",
817 $monthly_income = "",
819 $financial_review = "",
833 $drivers_license = "",
839 $DOB = fixDate($DOB);
840 $regdate = fixDate($regdate);
843 $referral_source = '';
845 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
846 // Check for brain damage:
847 if ($db_id != $rez['id']) {
848 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
849 $rez['id'] . "' to '$db_id' for pid '$pid'";
852 $fitness = $rez['fitness'];
853 $referral_source = $rez['referral_source'];
856 // Get the default price level.
857 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
858 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
859 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
861 $query = ("replace into patient_data set
870 postal_code='$postal_code',
873 country_code='$country_code',
874 drivers_license='$drivers_license',
876 occupation='$occupation',
877 phone_home='$phone_home',
878 phone_biz='$phone_biz',
879 phone_contact='$phone_contact',
881 contact_relationship='$contact_relationship',
882 referrer='$referrer',
883 referrerID='$referrerID',
885 language='$language',
886 ethnoracial='$ethnoracial',
887 interpretter='$interpretter',
888 migrantseasonal='$migrantseasonal',
889 family_size='$family_size',
890 monthly_income='$monthly_income',
891 homeless='$homeless',
892 financial_review='$financial_review',
895 providerID = '$providerID',
896 genericname1 = '$genericname1',
897 genericval1 = '$genericval1',
898 genericname2 = '$genericname2',
899 genericval2 = '$genericval2',
900 billing_note= '$billing_note';
901 phone_cell = '$phone_cell',
902 pharmacy_id = '$pharmacy_id',
903 hipaa_mail = '$hipaa_mail',
904 hipaa_voice = '$hipaa_voice',
905 hipaa_notice = '$hipaa_notice',
906 hipaa_message = '$hipaa_message',
909 referral_source='$referral_source',
911 pricelevel='$pricelevel',
914 $id = sqlInsert($query);
917 // find the last inserted id for new patient case
918 $db_id = getSqlLastID();
921 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
923 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
924 $phone_biz,$phone_cell,$email,$pid);
929 // Supported input date formats are:
931 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
933 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
935 function fixDate($date, $default="0000-00-00") {
936 $fixed_date = $default;
938 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
939 $dmy = preg_split("'[/.-]'", $date);
941 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
943 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
944 if ($dmy[2] < 1000) $dmy[2] += 1900;
945 if ($dmy[2] < 1910) $dmy[2] += 100;
947 // phone_country_code indicates format of ambiguous input dates.
948 if ($GLOBALS['phone_country_code'] == 1)
949 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
951 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
958 function pdValueOrNull($key, $value) {
959 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
960 substr($key, 0, 8) == 'userdate') &&
961 (empty($value) || $value == '0000-00-00'))
970 // Create or update patient data from an array.
972 function updatePatientData($pid, $new, $create=false)
974 /*******************************************************************
975 $real = getPatientData($pid);
976 $new['DOB'] = fixDate($new['DOB']);
977 while(list($key, $value) = each ($new))
978 $real[$key] = $value;
979 $real['date'] = "'+NOW()+'";
981 $sql = "insert into patient_data set ";
982 while(list($key, $value) = each($real))
983 $sql .= $key." = '$value', ";
984 $sql = substr($sql, 0, -2);
985 return sqlInsert($sql);
986 *******************************************************************/
988 // The above was broken, though seems intent to insert a new patient_data
989 // row for each update. A good idea, but nothing is doing that yet so
990 // the code below does not yet attempt it.
992 $new['DOB'] = fixDate($new['DOB']);
995 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
996 foreach ($new as $key => $value) {
997 if ($key == 'id') continue;
998 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1000 $db_id = sqlInsert($sql);
1003 $db_id = $new['id'];
1004 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1005 // Check for brain damage:
1006 if ($pid != $rez['pid']) {
1007 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1008 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1011 $sql = "UPDATE patient_data SET date = NOW()";
1012 foreach ($new as $key => $value) {
1013 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1015 $sql .= " WHERE id = '$db_id'";
1019 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
1020 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
1021 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
1022 $rez['phone_cell'],$rez['email'],$rez['pid']);
1027 function newEmployerData( $pid,
1036 return sqlInsert("insert into employer_data set
1039 postal_code='$postal_code',
1048 // Create or update employer data from an array.
1050 function updateEmployerData($pid, $new, $create=false)
1052 $colnames = array('name','street','city','state','postal_code','country');
1055 $set .= "pid = '$pid', date = NOW()";
1056 foreach ($colnames as $key) {
1057 $value = isset($new[$key]) ? $new[$key] : '';
1058 $set .= ", `$key` = '$value'";
1060 return sqlInsert("INSERT INTO employer_data SET $set");
1064 $old = getEmployerData($pid);
1066 foreach ($colnames as $key) {
1067 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1068 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1069 $value = $new[$key];
1072 $set .= "`$key` = '$value', ";
1075 $set .= "pid = '$pid', date = NOW()";
1076 return sqlInsert("INSERT INTO employer_data SET $set");
1082 // This updates or adds the given insurance data info, while retaining any
1083 // previously added insurance_data rows that should be preserved.
1084 // This does not directly support the maintenance of non-current insurance.
1086 function newInsuranceData(
1090 $policy_number = "",
1093 $subscriber_lname = "",
1094 $subscriber_mname = "",
1095 $subscriber_fname = "",
1096 $subscriber_relationship = "",
1097 $subscriber_ss = "",
1098 $subscriber_DOB = "",
1099 $subscriber_street = "",
1100 $subscriber_postal_code = "",
1101 $subscriber_city = "",
1102 $subscriber_state = "",
1103 $subscriber_country = "",
1104 $subscriber_phone = "",
1105 $subscriber_employer = "",
1106 $subscriber_employer_street = "",
1107 $subscriber_employer_city = "",
1108 $subscriber_employer_postal_code = "",
1109 $subscriber_employer_state = "",
1110 $subscriber_employer_country = "",
1112 $subscriber_sex = "",
1113 $effective_date = "0000-00-00",
1114 $accept_assignment = "TRUE",
1117 if (strlen($type) <= 0) return FALSE;
1119 // If a bad date was passed, err on the side of caution.
1120 $effective_date = fixDate($effective_date, date('Y-m-d'));
1122 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1123 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1124 $idrow = sqlFetchArray($idres);
1126 // Replace the most recent entry in any of the following cases:
1127 // * Its effective date is >= this effective date.
1128 // * It is the first entry and it has no (insurance) provider.
1129 // * There is no encounter that is earlier than the new effective date but
1130 // on or after the old effective date.
1131 // Otherwise insert a new entry.
1135 if (strcmp($idrow['date'], $effective_date) > 0) {
1139 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1143 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1144 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1145 "date >= '" . $idrow['date'] . " 00:00:00'");
1146 if ($ferow['count'] == 0) $replace = true;
1153 // TBD: This is a bit dangerous in that a typo in entering the effective
1154 // date can wipe out previous insurance history. So we want some data
1155 // entry validation somewhere.
1156 sqlStatement("DELETE FROM insurance_data WHERE " .
1157 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1158 "id != " . $idrow['id']);
1161 $data['type'] = $type;
1162 $data['provider'] = $provider;
1163 $data['policy_number'] = $policy_number;
1164 $data['group_number'] = $group_number;
1165 $data['plan_name'] = $plan_name;
1166 $data['subscriber_lname'] = $subscriber_lname;
1167 $data['subscriber_mname'] = $subscriber_mname;
1168 $data['subscriber_fname'] = $subscriber_fname;
1169 $data['subscriber_relationship'] = $subscriber_relationship;
1170 $data['subscriber_ss'] = $subscriber_ss;
1171 $data['subscriber_DOB'] = $subscriber_DOB;
1172 $data['subscriber_street'] = $subscriber_street;
1173 $data['subscriber_postal_code'] = $subscriber_postal_code;
1174 $data['subscriber_city'] = $subscriber_city;
1175 $data['subscriber_state'] = $subscriber_state;
1176 $data['subscriber_country'] = $subscriber_country;
1177 $data['subscriber_phone'] = $subscriber_phone;
1178 $data['subscriber_employer'] = $subscriber_employer;
1179 $data['subscriber_employer_city'] = $subscriber_employer_city;
1180 $data['subscriber_employer_street'] = $subscriber_employer_street;
1181 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1182 $data['subscriber_employer_state'] = $subscriber_employer_state;
1183 $data['subscriber_employer_country'] = $subscriber_employer_country;
1184 $data['copay'] = $copay;
1185 $data['subscriber_sex'] = $subscriber_sex;
1186 $data['pid'] = $pid;
1187 $data['date'] = $effective_date;
1188 $data['accept_assignment'] = $accept_assignment;
1189 $data['policy_type'] = $policy_type;
1190 updateInsuranceData($idrow['id'], $data);
1191 return $idrow['id'];
1194 return sqlInsert("INSERT INTO insurance_data SET
1196 provider = '$provider',
1197 policy_number = '$policy_number',
1198 group_number = '$group_number',
1199 plan_name = '$plan_name',
1200 subscriber_lname = '$subscriber_lname',
1201 subscriber_mname = '$subscriber_mname',
1202 subscriber_fname = '$subscriber_fname',
1203 subscriber_relationship = '$subscriber_relationship',
1204 subscriber_ss = '$subscriber_ss',
1205 subscriber_DOB = '$subscriber_DOB',
1206 subscriber_street = '$subscriber_street',
1207 subscriber_postal_code = '$subscriber_postal_code',
1208 subscriber_city = '$subscriber_city',
1209 subscriber_state = '$subscriber_state',
1210 subscriber_country = '$subscriber_country',
1211 subscriber_phone = '$subscriber_phone',
1212 subscriber_employer = '$subscriber_employer',
1213 subscriber_employer_city = '$subscriber_employer_city',
1214 subscriber_employer_street = '$subscriber_employer_street',
1215 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1216 subscriber_employer_state = '$subscriber_employer_state',
1217 subscriber_employer_country = '$subscriber_employer_country',
1219 subscriber_sex = '$subscriber_sex',
1221 date = '$effective_date',
1222 accept_assignment = '$accept_assignment',
1223 policy_type = '$policy_type'
1228 // This is used internally only.
1229 function updateInsuranceData($id, $new)
1231 $fields = sqlListFields("insurance_data");
1234 while(list($key, $value) = each ($new)) {
1235 if (in_array($key, $fields)) {
1236 $use[$key] = $value;
1240 $sql = "UPDATE insurance_data SET ";
1241 while(list($key, $value) = each($use))
1242 $sql .= "`$key` = '$value', ";
1243 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1248 function newHistoryData($pid, $new=false) {
1249 $arraySqlBind = array();
1250 $sql = "insert into history_data set pid = ?, date = NOW()";
1251 array_push($arraySqlBind,$pid);
1253 while(list($key, $value) = each($new)) {
1254 array_push($arraySqlBind,$value);
1255 $sql .= ", `$key` = ?";
1258 return sqlInsert($sql, $arraySqlBind );
1261 function updateHistoryData($pid,$new)
1263 $real = getHistoryData($pid);
1264 while(list($key, $value) = each ($new))
1265 $real[$key] = $value;
1267 // need to unset date, so can reset it below
1268 unset($real['date']);
1270 $arraySqlBind = array();
1271 $sql = "insert into history_data set `date` = NOW(), ";
1272 while(list($key, $value) = each($real)) {
1273 array_push($arraySqlBind,$value);
1274 $sql .= "`$key` = ?, ";
1276 $sql = substr($sql, 0, -2);
1278 return sqlInsert($sql, $arraySqlBind );
1281 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1282 $phone_biz,$phone_cell,$email,$pid="")
1284 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1285 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1287 $db = $GLOBALS['adodb']['db'];
1288 $customer_info = array();
1290 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1291 $result = $db->Execute($sql);
1292 if ($result && !$result->EOF) {
1293 $customer_info['foreign_update'] = true;
1294 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1295 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1298 ///xml rpc code to connect to accounting package and add user to it
1299 $customer_info['firstname'] = $fname;
1300 $customer_info['lastname'] = $lname;
1301 $customer_info['address'] = $street;
1302 $customer_info['suburb'] = $city;
1303 $customer_info['state'] = $state;
1304 $customer_info['postcode'] = $postal_code;
1306 //ezybiz wants state as a code rather than abbreviation
1307 $customer_info['geo_zone_id'] = "";
1308 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1309 $db = $GLOBALS['adodb']['db'];
1310 $result = $db->Execute($sql);
1311 if ($result && !$result->EOF) {
1312 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1315 //ezybiz wants country as a code rather than abbreviation
1316 $customer_info['geo_country_id'] = "";
1317 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1318 $db = $GLOBALS['adodb']['db'];
1319 $result = $db->Execute($sql);
1320 if ($result && !$result->EOF) {
1321 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1324 $customer_info['phone1'] = $phone_home;
1325 $customer_info['phone1comment'] = "Home Phone";
1326 $customer_info['phone2'] = $phone_biz;
1327 $customer_info['phone2comment'] = "Business Phone";
1328 $customer_info['phone3'] = $phone_cell;
1329 $customer_info['phone3comment'] = "Cell Phone";
1330 $customer_info['email'] = $email;
1331 $customer_info['customernumber'] = $pid;
1333 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1334 $ws = new WSWrapper($function);
1336 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1337 if (is_numeric($ws->value)) {
1338 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1339 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1344 // in months if < 2 years old
1345 // in years if > 2 years old
1346 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1347 // (optional) nowYMD is a date in YYYYMMDD format
1348 function getPatientAge($dobYMD, $nowYMD=null)
1350 // strip any dashes from the DOB
1351 $dobYMD = preg_replace("/-/", "", $dobYMD);
1352 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1354 // set the 'now' date values
1355 if ($nowYMD == null) {
1356 $nowDay = date("d");
1357 $nowMonth = date("m");
1358 $nowYear = date("Y");
1361 $nowDay = substr($nowYMD,6,2);
1362 $nowMonth = substr($nowYMD,4,2);
1363 $nowYear = substr($nowYMD,0,4);
1366 $dayDiff = $nowDay - $dobDay;
1367 $monthDiff = $nowMonth - $dobMonth;
1368 $yearDiff = $nowYear - $dobYear;
1370 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1372 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1373 if($dayDiff<0) { $ageInMonths-=1; }
1375 if ( $ageInMonths > 24 ) {
1377 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1378 else if ($monthDiff < 0) { $age -= 1; }
1381 $age = "$ageInMonths month";
1388 * Wrapper to make sure the clinical rules dates formats corresponds to the
1389 * format expected by getPatientAgeYMD
1391 * @param string $dob date of birth
1392 * @param string $target date to calculate age on
1393 * @return array containing
1394 * age - decimal age in years
1395 * age_in_months - decimal age in months
1396 * ageinYMD - formatted string #y #m #d */
1397 function parseAgeInfo($dob,$target)
1399 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1400 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1401 // Prepare target (Y-M-D H:M:S)
1402 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1404 return getPatientAgeYMD($dateDOB,$dateTarget);
1412 * @return array containing
1413 * age - decimal age in years
1414 * age_in_months - decimal age in months
1415 * ageinYMD - formatted string #y #m #d
1417 function getPatientAgeYMD($dob, $date=null) {
1419 if ($date == null) {
1420 $daynow = date("d");
1421 $monthnow = date("m");
1422 $yearnow = date("Y");
1423 $datenow=$yearnow.$monthnow.$daynow;
1426 $datenow=preg_replace("/-/", "", $date);
1427 $yearnow=substr($datenow,0,4);
1428 $monthnow=substr($datenow,4,2);
1429 $daynow=substr($datenow,6,2);
1430 $datenow=$yearnow.$monthnow.$daynow;
1433 $dob=preg_replace("/-/", "", $dob);
1434 $dobyear=substr($dob,0,4);
1435 $dobmonth=substr($dob,4,2);
1436 $dobday=substr($dob,6,2);
1437 $dob=$dobyear.$dobmonth.$dobday;
1439 //to compensate for 30, 31, 28, 29 days/month
1440 $mo=$monthnow; //to avoid confusion with later calculation
1442 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1443 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1444 } // look at April, June, September, November for calculation. These months only have 30 days.
1445 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1446 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1447 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1448 else {$nd=28;} //otherwise, it is not a leap year.
1450 else {$nd=31;} // other months have 31 days
1452 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1453 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1455 $age_year = $yearnow - $dobyear - 1;
1456 if ($daynow < $dobday) {
1457 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1458 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1461 $months_since_birthday=12 - $dobmonth + $monthnow;
1462 $days_since_dobday=$daynow - $dobday;
1465 else // if patient has had birthday this calandar year
1467 $age_year = $yearnow - $dobyear;
1468 if ($daynow < $dobday) {
1469 $months_since_birthday=$monthnow - $dobmonth -1;
1470 $days_since_dobday=$nd - $dobday + $daynow;
1473 $months_since_birthday=$monthnow - $dobmonth;
1474 $days_since_dobday=$daynow - $dobday;
1478 $day_as_month_decimal = $days_since_dobday / 30;
1479 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1480 $month_as_year_decimal = $months_since_birthday_float / 12;
1481 $age_float = $age_year + $month_as_year_decimal;
1483 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1484 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1485 $age = round($age_float,2);
1487 // round the years to 2 floating points
1488 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1489 return compact('age','age_in_months','ageinYMD');
1492 // Returns Age in days
1493 // in months if < 2 years old
1494 // in years if > 2 years old
1495 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1496 // (optional) nowYMD is a date in YYYYMMDD format
1497 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1500 // strip any dashes from the DOB
1501 $dobYMD = preg_replace("/-/", "", $dobYMD);
1502 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1504 // set the 'now' date values
1505 if ($nowYMD == null) {
1506 $nowDay = date("d");
1507 $nowMonth = date("m");
1508 $nowYear = date("Y");
1511 $nowDay = substr($nowYMD,6,2);
1512 $nowMonth = substr($nowYMD,4,2);
1513 $nowYear = substr($nowYMD,0,4);
1517 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1518 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1519 $timediff = $nowtime - $dobtime;
1520 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1525 * Returns a string to be used to display a patient's age
1527 * @param type $dobYMD
1528 * @param type $asOfYMD
1529 * @return string suitable for displaying patient's age based on preferences
1531 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1533 if($GLOBALS['age_display_format']=='1')
1535 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1536 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1538 return $ageYMD['ageinYMD'];
1542 return getPatientAge($dobYMD, $asOfYMD);
1547 return getPatientAge($dobYMD, $asOfYMD);
1551 function dateToDB ($date)
1553 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1558 // ----------------------------------------------------------------------------
1560 * DROPDOWN FOR COUNTRIES
1562 * build a dropdown with all countries from geo_country_reference
1564 * @param int $selected - id for selected record
1565 * @param string $name - the name/id for select form
1566 * @return void - just echo the html encoded string
1568 function dropdown_countries($selected = 0, $name = 'country_code') {
1569 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1571 $string = "<select name='$name' id='$name'>";
1572 while ( $row = sqlFetchArray($r) ) {
1573 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1574 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1577 $string .= '</select>';
1582 // ----------------------------------------------------------------------------
1584 * DROPDOWN FOR YES/NO
1586 * build a dropdown with two options (yes - 1, no - 0)
1588 * @param int $selected - id for selected record
1589 * @param string $name - the name/id for select form
1590 * @return void - just echo the html encoded string
1592 function dropdown_yesno($selected = 0, $name = 'yesno') {
1593 $string = "<select name='$name' id='$name'>";
1595 $selected = (int)$selected;
1596 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1597 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1599 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1600 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1601 $string .= '</select>';
1606 // ----------------------------------------------------------------------------
1608 * DROPDOWN FOR MALE/FEMALE options
1610 * build a dropdown with three options (unselected/male/female)
1612 * @param int $selected - id for selected record
1613 * @param string $name - the name/id for select form
1614 * @return void - just echo the html encoded string
1616 function dropdown_sex($selected = 0, $name = 'sex') {
1617 $string = "<select name='$name' id='$name'>";
1619 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1620 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1621 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1623 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1624 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1625 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1626 $string .= '</select>';
1631 // ----------------------------------------------------------------------------
1633 * DROPDOWN FOR MARITAL STATUS
1635 * build a dropdown with marital status
1637 * @param int $selected - id for selected record
1638 * @param string $name - the name/id for select form
1639 * @return void - just echo the html encoded string
1641 function dropdown_marital($selected = 0, $name = 'status') {
1642 $string = "<select name='$name' id='$name'>";
1644 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1646 foreach ( $statii as $st ) {
1647 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1648 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1651 $string .= '</select>';
1656 // ----------------------------------------------------------------------------
1658 * DROPDOWN FOR PROVIDERS
1660 * build a dropdown with all providers
1662 * @param int $selected - id for selected record
1663 * @param string $name - the name/id for select form
1664 * @return void - just echo the html encoded string
1666 function dropdown_providers($selected = 0, $name = 'status') {
1667 $provideri = getProviderInfo();
1669 $string = "<select name='$name' id='$name'>";
1670 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1671 foreach ( $provideri as $s ) {
1672 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1673 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1676 $string .= '</select>';
1681 // ----------------------------------------------------------------------------
1683 * DROPDOWN FOR INSURANCE COMPANIES
1685 * build a dropdown with all insurers
1687 * @param int $selected - id for selected record
1688 * @param string $name - the name/id for select form
1689 * @return void - just echo the html encoded string
1691 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1692 $insurancei = getInsuranceProviders();
1694 $string = "<select name='$name' id='$name'>";
1695 $string .= '<option value="0">Onbekend</option>';
1696 foreach ( $insurancei as $iid => $iname ) {
1697 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1698 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1701 $string .= '</select>';
1707 // ----------------------------------------------------------------------------
1711 * return the name or the country code, function of arguments
1713 * @param int $country_code
1714 * @param string $country_name
1715 * @return string | int - name or code
1717 function country_code($country_code = 0, $country_name = '') {
1719 if ( $country_code ) {
1720 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1722 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1725 $db = $GLOBALS['adodb']['db'];
1726 $result = $db->Execute($sql);
1727 if ($result && !$result->EOF) {
1728 $strint = $result->fields['res'];
1734 function DBToDate ($date)
1736 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1741 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1742 * for the given patient on the given date.
1744 * @param int The PID of the patient.
1745 * @param string Date in yyyy-mm-dd format.
1746 * @return array Array of 0-3 insurance_data rows.
1748 function getEffectiveInsurances($patient_id, $encdate) {
1750 foreach (array('primary','secondary','tertiary') as $instype) {
1751 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1752 "WHERE pid = ? AND type = ? " .
1753 "AND date <= ? ORDER BY date DESC LIMIT 1",
1754 array($patient_id, $instype, $encdate));
1755 if (empty($tmp['provider'])) break;
1762 * Get the patient's balance due. Normally this excludes amounts that are out
1763 * to insurance. If you want to include what insurance owes, set the second
1764 * parameter to true.
1766 * @param int The PID of the patient.
1767 * @param boolean Indicates if amounts owed by insurance are to be included.
1768 * @return number The balance.
1770 function get_patient_balance($pid, $with_insurance=false) {
1771 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1773 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1774 "last_level_closed, stmt_count " .
1775 "FROM form_encounter WHERE pid = ?", array($pid));
1776 while ($ferow = sqlFetchArray($feres)) {
1777 $encounter = $ferow['encounter'];
1778 $dos = substr($ferow['date'], 0, 10);
1779 $insarr = getEffectiveInsurances($pid, $dos);
1780 $inscount = count($insarr);
1781 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1782 // It's out to insurance so only the co-pay might be due.
1783 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1784 "pid = ? AND encounter = ? AND " .
1785 "code_type = 'copay' AND activity = 1",
1786 array($pid, $encounter));
1787 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1788 "FROM ar_activity WHERE " .
1789 "pid = ? AND encounter = ? AND payer_type = 0",
1790 array($pid, $encounter));
1791 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1792 if ($ptbal > 0) $balance += $ptbal;
1795 // Including insurance or not out to insurance, everything is due.
1796 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1797 "pid = ? AND encounter = ? AND " .
1798 "activity = 1", array($pid, $encounter));
1799 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1800 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1801 "pid = ? AND encounter = ?", array($pid, $encounter));
1802 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1803 "pid = ? AND encounter = ?", array($pid, $encounter));
1804 $balance += $brow['amount'] + $srow['amount']
1805 - $drow['payments'] - $drow['adjustments'];
1808 return sprintf('%01.2f', $balance);
1810 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1811 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1812 $conn = $GLOBALS['adodb']['db'];
1813 $customer_info['id'] = 0;
1814 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1815 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1816 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1817 "im.foreign_table = 'customer'";
1818 $result = $conn->Execute($sql);
1819 if($result && !$result->EOF) {
1820 $customer_info['id'] = $result->fields['foreign_id'];
1822 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1823 $ws = new WSWrapper($function);
1824 if(is_numeric($ws->value)) {
1825 return sprintf('%01.2f', $ws->value);
1831 // Function to check if patient is deceased.
1833 // $pid - patient id
1834 // $date - date checking if deceased (will default to current date if blank)
1836 // If deceased, then will return the number of
1837 // days that patient has been deceased.
1838 // If not deceased, then will return false.
1839 function is_patient_deceased($pid,$date='') {
1841 // Set date to current if not set
1842 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1844 // Query for deceased status (gets days deceased if patient is deceased)
1845 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1846 "FROM `patient_data` " .
1847 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1849 if (empty($results)) {
1850 // Patient is alive, so return false
1854 // Patient is dead, so return the number of days patient has been deceased.
1855 // Don't let it be zero days or else will confuse calls to this function.
1856 if ($results['days_deceased'] === 0) {
1857 $results['days_deceased'] = 1;
1859 return $results['days_deceased'];