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() {
80 $sql = "select insurance_companies.name, insurance_companies.id, " .
81 "addresses.zip, addresses.line1, addresses.state " .
82 "from insurance_companies, addresses " .
83 "where addresses.foreign_id = insurance_companies.id " .
84 "order by insurance_companies.name, addresses.zip";
86 $rez = sqlStatement($sql);
88 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
89 switch ($GLOBALS['insurance_information']) {
90 case $GLOBALS['insurance_information'] = '0':
91 $returnval[$row['id']] = $row['name'];
93 case $GLOBALS['insurance_information'] = '1':
94 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
96 case $GLOBALS['insurance_information'] = '2':
97 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";
99 case $GLOBALS['insurance_information'] = '3':
100 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
102 case $GLOBALS['insurance_information'] = '4':
103 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
104 "," . $row['zip'] . ")";
106 case $GLOBALS['insurance_information'] = '5':
107 preg_match("/\d+/", $row['line1'], $matches);
108 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
109 "," . $matches[0] . ")";
117 function getProviders() {
118 $returnval = array("");
119 $sql = "select fname, lname from users where authorized = 1 and " .
120 "active = 1 and username != ''";
121 $rez = sqlStatement($sql);
122 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
123 if (($row["fname"] != "") && ($row["lname"] != "")) {
124 array_push($returnval, $row["fname"] . " " . $row["lname"]);
130 // ----------------------------------------------------------------------------
131 // Get one facility row. If the ID is not specified, then get either the
132 // "main" (billing) facility, or the default facility of the currently
133 // logged-in user. This was created to support genFacilityTitle() but
134 // may find additional uses.
136 function getFacility($facid=0) {
138 //create a sql binding array
139 $sqlBindArray = array();
142 $query = "SELECT * FROM facility WHERE id = ?";
143 array_push($sqlBindArray,$facid);
145 else if ($facid == 0) {
146 $query = "SELECT * FROM facility ORDER BY " .
147 "billing_location DESC, service_location, id LIMIT 1";
150 $query = "SELECT facility.* FROM users, facility WHERE " .
151 "users.id = ? AND " .
152 "facility.id = users.facility_id";
153 array_push($sqlBindArray,$_SESSION['authUserID']);
155 return sqlQuery($query,$sqlBindArray);
158 // Generate a report title including report name and facility name, address
161 function genFacilityTitle($repname='', $facid=0) {
163 $s .= "<table class='ftitletable'>\n";
165 $s .= " <td class='ftitlecell1'>$repname</td>\n";
166 $s .= " <td class='ftitlecell2'>\n";
167 $r = getFacility($facid);
169 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
170 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
171 if ($r['city'] || $r['state'] || $r['postal_code']) {
173 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
175 if ($r['city']) $s .= ", \n";
176 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
178 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
181 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
182 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
193 returns all facilities or just the id for the first one
194 (FACILITY FILTERING (lemonsoftware))
196 @param string - if 'first' return first facility ordered by id
197 @return array | int for 'first' case
199 function getFacilities($first = '') {
200 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
202 while ( $row = sqlFetchArray($r) ) {
206 if ( $first == 'first') {
207 return $ret[0]['id'];
214 GET SERVICE FACILITIES
216 returns all service_location facilities or just the id for the first one
217 (FACILITY FILTERING (CHEMED))
219 @param string - if 'first' return first facility ordered by id
220 @return array | int for 'first' case
222 function getServiceFacilities($first = '') {
223 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
225 while ( $row = sqlFetchArray($r) ) {
229 if ( $first == 'first') {
230 return $ret[0]['id'];
236 //(CHEMED) facility filter
237 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
239 if ($providers_only === 'any') {
240 $param1 = " AND authorized = 1 AND active = 1 ";
242 else if ($providers_only) {
243 $param1 = " AND authorized = 1 AND calendar = 1 ";
246 //--------------------------------
247 //(CHEMED) facility filter
250 if ($GLOBALS['restrict_user_facility']) {
251 $param2 = " AND (facility_id = $facility
255 where tablename = 'users'
261 $param2 = " AND facility_id = $facility ";
264 //--------------------------------
267 if ($providerID == "%") {
270 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
271 "from users where username != '' and active = 1 and id $command '" .
272 add_escape_custom($providerID) . "' " . $param1 . $param2;
273 // sort by last name -- JRM June 2008
274 $query .= " ORDER BY lname, fname ";
275 $rez = sqlStatement($query);
276 for($iter=0; $row=sqlFetchArray($rez); $iter++)
277 $returnval[$iter]=$row;
279 //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
280 //accessible from $resultval['key']
283 $akeys = array_keys($returnval[0]);
284 foreach($akeys as $key) {
285 $returnval[0][$key] = $returnval[0][$key];
291 //same as above but does not reduce if only 1 row returned
292 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
294 if ($providers_only) {
295 $param1 = "AND authorized=1";
298 if ($providerID == "%") {
301 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
302 "from users where active = 1 and username != '' and id $command '" .
303 add_escape_custom($providerID) . "' " . $param1;
305 $rez = sqlStatement($query);
306 for($iter=0; $row=sqlFetchArray($rez); $iter++)
307 $returnval[$iter]=$row;
312 function getProviderName($providerID) {
313 $pi = getProviderInfo($providerID, 'any');
314 if (strlen($pi[0]["lname"]) > 0) {
315 return $pi[0]['fname'] . " " . $pi[0]['lname'];
320 function getProviderId($providerName) {
321 $query = "select id from users where username = ?";
322 $rez = sqlStatement($query, array($providerName) );
323 for($iter=0; $row=sqlFetchArray($rez); $iter++)
324 $returnval[$iter]=$row;
328 function getEthnoRacials() {
329 $returnval = array("");
330 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
331 $rez = sqlStatement($sql);
332 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
333 if (($row["ethnoracial"] != "")) {
334 array_push($returnval, $row["ethnoracial"]);
340 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
343 if ($dateStart && $dateEnd) {
344 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
346 else if ($dateStart && !$dateEnd) {
347 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
349 else if (!$dateStart && $dateEnd) {
350 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
353 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
359 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
360 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
362 $sql = "select $given from insurance_data as insd " .
363 "left join insurance_companies as ic on ic.id = insd.provider " .
364 "where pid = ? and type = ? order by date DESC limit 1";
365 return sqlQuery($sql, array($pid, $type) );
368 function getInsuranceDataByDate($pid, $date, $type,
369 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
370 { // this must take the date in the following manner: YYYY-MM-DD
371 // this function recalls the insurance value that was most recently enterred from the
372 // given date. it will call up most recent records up to and on the date given,
373 // but not records enterred after the given date
374 $sql = "select $given from insurance_data as insd " .
375 "left join insurance_companies as ic on ic.id = provider " .
376 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
377 "type=? order by date DESC limit 1";
378 return sqlQuery($sql, array($pid,$date,$type) );
381 function getEmployerData($pid, $given = "*")
383 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
384 return sqlQuery($sql, array($pid) );
387 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
388 // When the limit is exceeded, find out what the unlimited count would be.
389 $GLOBALS['PATIENT_INC_COUNT'] = $count;
390 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
391 if ($limit != "all") {
392 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
393 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
398 * Allow the last name to be followed by a comma and some part of a first name(can
399 * also place middle name after the first name with a space separating them)
400 * Allows comma alone followed by some part of a first name(can also place middle name
401 * after the first name with a space separating them).
402 * Allows comma alone preceded by some part of a last name.
403 * If no comma or space, then will search both last name and first name.
404 * If the first letter of either name is capital, searches for name starting
405 * with given substring (the expected behavior). If it is lower case, it
406 * searches for the substring anywhere in the name. This applies to either
407 * last name, first name, and middle name.
408 * Also allows first name followed by middle and/or last name when separated by spaces.
409 * @param string $term
410 * @param string $given
411 * @param string $orderby
412 * @param string $limit
413 * @param string $start
416 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")
418 $names = getPatientNameSplit($term);
420 foreach ($names as $key => $val) {
422 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
423 $names[$key] = '%' . $val . '%';
425 $names[$key] = $val . '%';
430 // Debugging section below
431 //if(array_key_exists('first',$names)) {
432 // error_log("first name search term :".$names['first']);
434 //if(array_key_exists('middle',$names)) {
435 // error_log("middle name search term :".$names['middle']);
437 //if(array_key_exists('last',$names)) {
438 // error_log("last name search term :".$names['last']);
440 // Debugging section above
442 $sqlBindArray = array();
443 if(array_key_exists('last',$names) && $names['last'] == '') {
444 // Do not search last name
445 $where = "fname LIKE ? ";
446 array_push($sqlBindArray, $names['first']);
447 if ($names['middle'] != '') {
448 $where .= "AND mname LIKE ? ";
449 array_push($sqlBindArray, $names['middle']);
451 } elseif(array_key_exists('first',$names) && $names['first'] == '') {
452 // Do not search first name or middle name
453 $where = "lname LIKE ? ";
454 array_push($sqlBindArray, $names['last']);
455 } elseif($names['first'] == '' && $names['last'] != '') {
456 // Search both first name and last name with same term
457 $names['first'] = $names['last'];
458 $where = "lname LIKE ? OR fname LIKE ? ";
459 array_push($sqlBindArray, $names['last'], $names['first']);
460 } elseif ($names['middle'] != '') {
461 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
462 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
464 $where = "lname LIKE ? AND fname LIKE ? ";
465 array_push($sqlBindArray, $names['last'], $names['first']);
468 if (!empty($GLOBALS['pt_restrict_field'])) {
469 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
470 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
471 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
472 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
473 array_push($sqlBindArray, $_SESSION{"authUser"});
477 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
478 if ($limit != "all") $sql .= " LIMIT $start, $limit";
480 $rez = sqlStatement($sql, $sqlBindArray);
483 for($iter=0; $row=sqlFetchArray($rez); $iter++)
484 $returnval[$iter] = $row;
486 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
490 * Accept a string used by a search function expected to find a patient name,
491 * then split up the string if a comma or space exists. Return an array having
492 * from 1 to 3 elements, named first, middle, and last.
493 * See above getPatientLnames() function for details on how the splitting occurs.
494 * @param string $term
497 function getPatientNameSplit($term) {
499 if (strpos($term, ',') !== false) {
500 $names = explode(',', $term);
501 $n['last'] = $names[0];
502 if (strpos(trim($names[1]), ' ') !== false) {
503 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
505 $n['first'] = $names[1];
507 } elseif (strpos($term, ' ') !== false) {
508 $names = explode(' ', $term);
509 if (count($names) == 1) {
510 $n['last'] = $names[0];
511 } elseif (count($names) == 3) {
512 $n['first'] = $names[0];
513 $n['middle'] = $names[1];
514 $n['last'] = $names[2];
516 // This will handle first and last name or first followed by
517 // multiple names only using just the last of the names in the list.
518 $n['first'] = $names[0];
519 $n['last'] = end($names);
524 // Trim whitespace off the names before returning
525 foreach($n as $key => $val) {
526 $n[$key] = trim($val);
528 return $n; // associative array containing names
531 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")
534 $sqlBindArray = array();
535 $where = "pubpid LIKE ? ";
536 array_push($sqlBindArray, $pid."%");
537 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
538 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
539 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
540 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
541 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
542 array_push($sqlBindArray, $_SESSION{"authUser"});
546 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
547 if ($limit != "all") $sql .= " limit $start, $limit";
548 $rez = sqlStatement($sql, $sqlBindArray);
549 for($iter=0; $row=sqlFetchArray($rez); $iter++)
550 $returnval[$iter]=$row;
552 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
556 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")
558 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
560 $sqlBindArray = array();
562 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
566 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
567 array_push($sqlBindArray, "%".$searchTerm."%");
570 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
571 if ($limit != "all") $sql .= " limit $start, $limit";
572 $rez = sqlStatement($sql, $sqlBindArray);
573 for($iter=0; $row=sqlFetchArray($rez); $iter++)
574 $returnval[$iter]=$row;
575 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
579 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
580 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
581 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
583 $layoutCols = explode( '~', $searchFields );
584 $sqlBindArray = array();
587 foreach ($layoutCols as $val) {
588 if (empty($val)) continue;
593 $where .= " ".add_escape_custom($val)." = ? ";
594 array_push($sqlBindArray, $searchTerm);
597 $where .= " ".add_escape_custom($val)." like ? ";
598 array_push($sqlBindArray, $searchTerm."%");
603 // If no search terms, ensure valid syntax.
604 if ($i == 0) $where = "1 = 1";
606 // If a non-empty service code was given, then restrict to patients who
607 // have been provided that service. Since the code is used in a LIKE
608 // clause, % and _ wildcards are supported.
609 if ($search_service_code) {
610 $where = "( $where ) AND " .
611 "( SELECT COUNT(*) FROM billing AS b WHERE " .
612 "b.pid = patient_data.pid AND " .
613 "b.activity = 1 AND " .
614 "b.code_type != 'COPAY' AND " .
617 array_push($sqlBindArray, $search_service_code);
620 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
621 if ($limit != "all") $sql .= " limit $start, $limit";
622 $rez = sqlStatement($sql, $sqlBindArray);
623 for($iter=0; $row=sqlFetchArray($rez); $iter++)
624 $returnval[$iter]=$row;
625 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
629 // return a collection of Patient PIDs
630 // new arg style by JRM March 2008
631 // 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")
632 function getPatientPID($args)
635 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
636 $orderby = "lname ASC, fname ASC";
640 // alter default values if defined in the passed in args
641 if (isset($args['pid'])) { $pid = $args['pid']; }
642 if (isset($args['given'])) { $given = $args['given']; }
643 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
644 if (isset($args['limit'])) { $limit = $args['limit']; }
645 if (isset($args['start'])) { $start = $args['start']; }
648 if ($pid == -1) $pid = "%";
649 elseif (empty($pid)) $pid = "NULL";
651 if (strstr($pid,"%")) $command = "like";
653 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
654 if ($limit != "all") $sql .= " limit $start, $limit";
656 $rez = sqlStatement($sql);
657 for($iter=0; $row=sqlFetchArray($rez); $iter++)
658 $returnval[$iter]=$row;
663 /* return a patient's name in the format LAST, FIRST */
664 function getPatientName($pid) {
665 if (empty($pid)) return "";
666 $patientData = getPatientPID(array("pid"=>$pid));
667 if (empty($patientData[0]['lname'])) return "";
668 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
672 /* find patient data by DOB */
673 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
675 $DOB = fixDate($DOB, $DOB);
676 $sqlBindArray = array();
677 $where = "DOB like ? ";
678 array_push($sqlBindArray, $DOB."%");
679 if (!empty($GLOBALS['pt_restrict_field'])) {
680 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
681 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
682 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
683 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
684 array_push($sqlBindArray, $_SESSION{"authUser"});
688 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
690 if ($limit != "all") $sql .= " LIMIT $start, $limit";
692 $rez = sqlStatement($sql, $sqlBindArray);
693 for($iter=0; $row=sqlFetchArray($rez); $iter++)
694 $returnval[$iter]=$row;
696 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
700 /* find patient data by SSN */
701 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
703 $sqlBindArray = array();
704 $where = "ss LIKE ?";
705 array_push($sqlBindArray, $ss."%");
706 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
707 if ($limit != "all") $sql .= " LIMIT $start, $limit";
709 $rez = sqlStatement($sql, $sqlBindArray);
710 for($iter=0; $row=sqlFetchArray($rez); $iter++)
711 $returnval[$iter]=$row;
713 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
717 //(CHEMED) Search by phone number
718 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
720 $phone = preg_replace( "/[[:punct:]]/","", $phone );
721 $sqlBindArray = array();
722 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
723 array_push($sqlBindArray, $phone);
724 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
725 if ($limit != "all") $sql .= " LIMIT $start, $limit";
727 $rez = sqlStatement($sql, $sqlBindArray);
728 for($iter=0; $row=sqlFetchArray($rez); $iter++)
729 $returnval[$iter]=$row;
731 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
735 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
737 $sql="select $given from patient_data order by $orderby";
740 $sql .= " limit $start, $limit";
742 $rez = sqlStatement($sql);
743 for($iter=0; $row=sqlFetchArray($rez); $iter++)
744 $returnval[$iter]=$row;
749 //----------------------input functions
750 function newPatientData( $db_id="",
768 $contact_relationship = "",
775 $migrantseasonal = "",
777 $monthly_income = "",
779 $financial_review = "",
793 $drivers_license = "",
799 $DOB = fixDate($DOB);
800 $regdate = fixDate($regdate);
803 $referral_source = '';
805 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
806 // Check for brain damage:
807 if ($db_id != $rez['id']) {
808 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
809 $rez['id'] . "' to '$db_id' for pid '$pid'";
812 $fitness = $rez['fitness'];
813 $referral_source = $rez['referral_source'];
816 // Get the default price level.
817 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
818 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
819 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
821 $query = ("replace into patient_data set
830 postal_code='$postal_code',
833 country_code='$country_code',
834 drivers_license='$drivers_license',
836 occupation='$occupation',
837 phone_home='$phone_home',
838 phone_biz='$phone_biz',
839 phone_contact='$phone_contact',
841 contact_relationship='$contact_relationship',
842 referrer='$referrer',
843 referrerID='$referrerID',
845 language='$language',
846 ethnoracial='$ethnoracial',
847 interpretter='$interpretter',
848 migrantseasonal='$migrantseasonal',
849 family_size='$family_size',
850 monthly_income='$monthly_income',
851 homeless='$homeless',
852 financial_review='$financial_review',
855 providerID = '$providerID',
856 genericname1 = '$genericname1',
857 genericval1 = '$genericval1',
858 genericname2 = '$genericname2',
859 genericval2 = '$genericval2',
860 billing_note= '$billing_note';
861 phone_cell = '$phone_cell',
862 pharmacy_id = '$pharmacy_id',
863 hipaa_mail = '$hipaa_mail',
864 hipaa_voice = '$hipaa_voice',
865 hipaa_notice = '$hipaa_notice',
866 hipaa_message = '$hipaa_message',
869 referral_source='$referral_source',
871 pricelevel='$pricelevel',
874 $id = sqlInsert($query);
877 // find the last inserted id for new patient case
878 $db_id = getSqlLastID();
881 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
883 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
884 $phone_biz,$phone_cell,$email,$pid);
889 // Supported input date formats are:
891 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
893 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
895 function fixDate($date, $default="0000-00-00") {
896 $fixed_date = $default;
898 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
899 $dmy = preg_split("'[/.-]'", $date);
901 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
903 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
904 if ($dmy[2] < 1000) $dmy[2] += 1900;
905 if ($dmy[2] < 1910) $dmy[2] += 100;
907 // phone_country_code indicates format of ambiguous input dates.
908 if ($GLOBALS['phone_country_code'] == 1)
909 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
911 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
918 function pdValueOrNull($key, $value) {
919 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
920 substr($key, 0, 8) == 'userdate') &&
921 (empty($value) || $value == '0000-00-00'))
930 // Create or update patient data from an array.
932 function updatePatientData($pid, $new, $create=false)
934 /*******************************************************************
935 $real = getPatientData($pid);
936 $new['DOB'] = fixDate($new['DOB']);
937 while(list($key, $value) = each ($new))
938 $real[$key] = $value;
939 $real['date'] = "'+NOW()+'";
941 $sql = "insert into patient_data set ";
942 while(list($key, $value) = each($real))
943 $sql .= $key." = '$value', ";
944 $sql = substr($sql, 0, -2);
945 return sqlInsert($sql);
946 *******************************************************************/
948 // The above was broken, though seems intent to insert a new patient_data
949 // row for each update. A good idea, but nothing is doing that yet so
950 // the code below does not yet attempt it.
952 $new['DOB'] = fixDate($new['DOB']);
955 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
956 foreach ($new as $key => $value) {
957 if ($key == 'id') continue;
958 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
960 $db_id = sqlInsert($sql);
964 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
965 // Check for brain damage:
966 if ($pid != $rez['pid']) {
967 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
968 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
971 $sql = "UPDATE patient_data SET date = NOW()";
972 foreach ($new as $key => $value) {
973 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
975 $sql .= " WHERE id = '$db_id'";
979 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
980 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
981 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
982 $rez['phone_cell'],$rez['email'],$rez['pid']);
987 function newEmployerData( $pid,
996 return sqlInsert("insert into employer_data set
999 postal_code='$postal_code',
1008 // Create or update employer data from an array.
1010 function updateEmployerData($pid, $new, $create=false)
1012 $colnames = array('name','street','city','state','postal_code','country');
1015 $set .= "pid = '$pid', date = NOW()";
1016 foreach ($colnames as $key) {
1017 $value = isset($new[$key]) ? $new[$key] : '';
1018 $set .= ", `$key` = '$value'";
1020 return sqlInsert("INSERT INTO employer_data SET $set");
1024 $old = getEmployerData($pid);
1026 foreach ($colnames as $key) {
1027 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1028 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1029 $value = $new[$key];
1032 $set .= "`$key` = '$value', ";
1035 $set .= "pid = '$pid', date = NOW()";
1036 return sqlInsert("INSERT INTO employer_data SET $set");
1042 // This updates or adds the given insurance data info, while retaining any
1043 // previously added insurance_data rows that should be preserved.
1044 // This does not directly support the maintenance of non-current insurance.
1046 function newInsuranceData(
1050 $policy_number = "",
1053 $subscriber_lname = "",
1054 $subscriber_mname = "",
1055 $subscriber_fname = "",
1056 $subscriber_relationship = "",
1057 $subscriber_ss = "",
1058 $subscriber_DOB = "",
1059 $subscriber_street = "",
1060 $subscriber_postal_code = "",
1061 $subscriber_city = "",
1062 $subscriber_state = "",
1063 $subscriber_country = "",
1064 $subscriber_phone = "",
1065 $subscriber_employer = "",
1066 $subscriber_employer_street = "",
1067 $subscriber_employer_city = "",
1068 $subscriber_employer_postal_code = "",
1069 $subscriber_employer_state = "",
1070 $subscriber_employer_country = "",
1072 $subscriber_sex = "",
1073 $effective_date = "0000-00-00",
1074 $accept_assignment = "TRUE",
1077 if (strlen($type) <= 0) return FALSE;
1079 // If a bad date was passed, err on the side of caution.
1080 $effective_date = fixDate($effective_date, date('Y-m-d'));
1082 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1083 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1084 $idrow = sqlFetchArray($idres);
1086 // Replace the most recent entry in any of the following cases:
1087 // * Its effective date is >= this effective date.
1088 // * It is the first entry and it has no (insurance) provider.
1089 // * There is no encounter that is earlier than the new effective date but
1090 // on or after the old effective date.
1091 // Otherwise insert a new entry.
1095 if (strcmp($idrow['date'], $effective_date) > 0) {
1099 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1103 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1104 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1105 "date >= '" . $idrow['date'] . " 00:00:00'");
1106 if ($ferow['count'] == 0) $replace = true;
1113 // TBD: This is a bit dangerous in that a typo in entering the effective
1114 // date can wipe out previous insurance history. So we want some data
1115 // entry validation somewhere.
1116 sqlStatement("DELETE FROM insurance_data WHERE " .
1117 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1118 "id != " . $idrow['id']);
1121 $data['type'] = $type;
1122 $data['provider'] = $provider;
1123 $data['policy_number'] = $policy_number;
1124 $data['group_number'] = $group_number;
1125 $data['plan_name'] = $plan_name;
1126 $data['subscriber_lname'] = $subscriber_lname;
1127 $data['subscriber_mname'] = $subscriber_mname;
1128 $data['subscriber_fname'] = $subscriber_fname;
1129 $data['subscriber_relationship'] = $subscriber_relationship;
1130 $data['subscriber_ss'] = $subscriber_ss;
1131 $data['subscriber_DOB'] = $subscriber_DOB;
1132 $data['subscriber_street'] = $subscriber_street;
1133 $data['subscriber_postal_code'] = $subscriber_postal_code;
1134 $data['subscriber_city'] = $subscriber_city;
1135 $data['subscriber_state'] = $subscriber_state;
1136 $data['subscriber_country'] = $subscriber_country;
1137 $data['subscriber_phone'] = $subscriber_phone;
1138 $data['subscriber_employer'] = $subscriber_employer;
1139 $data['subscriber_employer_city'] = $subscriber_employer_city;
1140 $data['subscriber_employer_street'] = $subscriber_employer_street;
1141 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1142 $data['subscriber_employer_state'] = $subscriber_employer_state;
1143 $data['subscriber_employer_country'] = $subscriber_employer_country;
1144 $data['copay'] = $copay;
1145 $data['subscriber_sex'] = $subscriber_sex;
1146 $data['pid'] = $pid;
1147 $data['date'] = $effective_date;
1148 $data['accept_assignment'] = $accept_assignment;
1149 $data['policy_type'] = $policy_type;
1150 updateInsuranceData($idrow['id'], $data);
1151 return $idrow['id'];
1154 return sqlInsert("INSERT INTO insurance_data SET
1156 provider = '$provider',
1157 policy_number = '$policy_number',
1158 group_number = '$group_number',
1159 plan_name = '$plan_name',
1160 subscriber_lname = '$subscriber_lname',
1161 subscriber_mname = '$subscriber_mname',
1162 subscriber_fname = '$subscriber_fname',
1163 subscriber_relationship = '$subscriber_relationship',
1164 subscriber_ss = '$subscriber_ss',
1165 subscriber_DOB = '$subscriber_DOB',
1166 subscriber_street = '$subscriber_street',
1167 subscriber_postal_code = '$subscriber_postal_code',
1168 subscriber_city = '$subscriber_city',
1169 subscriber_state = '$subscriber_state',
1170 subscriber_country = '$subscriber_country',
1171 subscriber_phone = '$subscriber_phone',
1172 subscriber_employer = '$subscriber_employer',
1173 subscriber_employer_city = '$subscriber_employer_city',
1174 subscriber_employer_street = '$subscriber_employer_street',
1175 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1176 subscriber_employer_state = '$subscriber_employer_state',
1177 subscriber_employer_country = '$subscriber_employer_country',
1179 subscriber_sex = '$subscriber_sex',
1181 date = '$effective_date',
1182 accept_assignment = '$accept_assignment',
1183 policy_type = '$policy_type'
1188 // This is used internally only.
1189 function updateInsuranceData($id, $new)
1191 $fields = sqlListFields("insurance_data");
1194 while(list($key, $value) = each ($new)) {
1195 if (in_array($key, $fields)) {
1196 $use[$key] = $value;
1200 $sql = "UPDATE insurance_data SET ";
1201 while(list($key, $value) = each($use))
1202 $sql .= "`$key` = '$value', ";
1203 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1208 function newHistoryData($pid, $new=false) {
1209 $arraySqlBind = array();
1210 $sql = "insert into history_data set pid = ?, date = NOW()";
1211 array_push($arraySqlBind,$pid);
1213 while(list($key, $value) = each($new)) {
1214 array_push($arraySqlBind,$value);
1215 $sql .= ", `$key` = ?";
1218 return sqlInsert($sql, $arraySqlBind );
1221 function updateHistoryData($pid,$new)
1223 $real = getHistoryData($pid);
1224 while(list($key, $value) = each ($new))
1225 $real[$key] = $value;
1227 // need to unset date, so can reset it below
1228 unset($real['date']);
1230 $arraySqlBind = array();
1231 $sql = "insert into history_data set `date` = NOW(), ";
1232 while(list($key, $value) = each($real)) {
1233 array_push($arraySqlBind,$value);
1234 $sql .= "`$key` = ?, ";
1236 $sql = substr($sql, 0, -2);
1238 return sqlInsert($sql, $arraySqlBind );
1241 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1242 $phone_biz,$phone_cell,$email,$pid="")
1244 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1245 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1247 $db = $GLOBALS['adodb']['db'];
1248 $customer_info = array();
1250 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1251 $result = $db->Execute($sql);
1252 if ($result && !$result->EOF) {
1253 $customer_info['foreign_update'] = true;
1254 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1255 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1258 ///xml rpc code to connect to accounting package and add user to it
1259 $customer_info['firstname'] = $fname;
1260 $customer_info['lastname'] = $lname;
1261 $customer_info['address'] = $street;
1262 $customer_info['suburb'] = $city;
1263 $customer_info['state'] = $state;
1264 $customer_info['postcode'] = $postal_code;
1266 //ezybiz wants state as a code rather than abbreviation
1267 $customer_info['geo_zone_id'] = "";
1268 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1269 $db = $GLOBALS['adodb']['db'];
1270 $result = $db->Execute($sql);
1271 if ($result && !$result->EOF) {
1272 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1275 //ezybiz wants country as a code rather than abbreviation
1276 $customer_info['geo_country_id'] = "";
1277 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1278 $db = $GLOBALS['adodb']['db'];
1279 $result = $db->Execute($sql);
1280 if ($result && !$result->EOF) {
1281 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1284 $customer_info['phone1'] = $phone_home;
1285 $customer_info['phone1comment'] = "Home Phone";
1286 $customer_info['phone2'] = $phone_biz;
1287 $customer_info['phone2comment'] = "Business Phone";
1288 $customer_info['phone3'] = $phone_cell;
1289 $customer_info['phone3comment'] = "Cell Phone";
1290 $customer_info['email'] = $email;
1291 $customer_info['customernumber'] = $pid;
1293 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1294 $ws = new WSWrapper($function);
1296 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1297 if (is_numeric($ws->value)) {
1298 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1299 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1304 // in months if < 2 years old
1305 // in years if > 2 years old
1306 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1307 // (optional) nowYMD is a date in YYYYMMDD format
1308 function getPatientAge($dobYMD, $nowYMD=null)
1310 // strip any dashes from the DOB
1311 $dobYMD = preg_replace("/-/", "", $dobYMD);
1312 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1314 // set the 'now' date values
1315 if ($nowYMD == null) {
1316 $nowDay = date("d");
1317 $nowMonth = date("m");
1318 $nowYear = date("Y");
1321 $nowDay = substr($nowYMD,6,2);
1322 $nowMonth = substr($nowYMD,4,2);
1323 $nowYear = substr($nowYMD,0,4);
1326 $dayDiff = $nowDay - $dobDay;
1327 $monthDiff = $nowMonth - $dobMonth;
1328 $yearDiff = $nowYear - $dobYear;
1330 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1332 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1333 if($dayDiff<0) { $ageInMonths-=1; }
1335 if ( $ageInMonths > 24 ) {
1337 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1338 else if ($monthDiff < 0) { $age -= 1; }
1341 $age = "$ageInMonths month";
1348 * Wrapper to make sure the clinical rules dates formats corresponds to the
1349 * format expected by getPatientAgeYMD
1351 * @param string $dob date of birth
1352 * @param string $target date to calculate age on
1353 * @return array containing
1354 * age - decimal age in years
1355 * age_in_months - decimal age in months
1356 * ageinYMD - formatted string #y #m #d */
1357 function parseAgeInfo($dob,$target)
1359 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1360 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1361 // Prepare target (Y-M-D H:M:S)
1362 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1364 return getPatientAgeYMD($dateDOB,$dateTarget);
1372 * @return array containing
1373 * age - decimal age in years
1374 * age_in_months - decimal age in months
1375 * ageinYMD - formatted string #y #m #d
1377 function getPatientAgeYMD($dob, $date=null) {
1379 if ($date == null) {
1380 $daynow = date("d");
1381 $monthnow = date("m");
1382 $yearnow = date("Y");
1383 $datenow=$yearnow.$monthnow.$daynow;
1386 $datenow=preg_replace("/-/", "", $date);
1387 $yearnow=substr($datenow,0,4);
1388 $monthnow=substr($datenow,4,2);
1389 $daynow=substr($datenow,6,2);
1390 $datenow=$yearnow.$monthnow.$daynow;
1393 $dob=preg_replace("/-/", "", $dob);
1394 $dobyear=substr($dob,0,4);
1395 $dobmonth=substr($dob,4,2);
1396 $dobday=substr($dob,6,2);
1397 $dob=$dobyear.$dobmonth.$dobday;
1399 //to compensate for 30, 31, 28, 29 days/month
1400 $mo=$monthnow; //to avoid confusion with later calculation
1402 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1403 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1404 } // look at April, June, September, November for calculation. These months only have 30 days.
1405 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1406 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1407 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1408 else {$nd=28;} //otherwise, it is not a leap year.
1410 else {$nd=31;} // other months have 31 days
1412 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1413 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1415 $age_year = $yearnow - $dobyear - 1;
1416 if ($daynow < $dobday) {
1417 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1418 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1421 $months_since_birthday=12 - $dobmonth + $monthnow;
1422 $days_since_dobday=$daynow - $dobday;
1425 else // if patient has had birthday this calandar year
1427 $age_year = $yearnow - $dobyear;
1428 if ($daynow < $dobday) {
1429 $months_since_birthday=$monthnow - $dobmonth -1;
1430 $days_since_dobday=$nd - $dobday + $daynow;
1433 $months_since_birthday=$monthnow - $dobmonth;
1434 $days_since_dobday=$daynow - $dobday;
1438 $day_as_month_decimal = $days_since_dobday / 30;
1439 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1440 $month_as_year_decimal = $months_since_birthday_float / 12;
1441 $age_float = $age_year + $month_as_year_decimal;
1443 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1444 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1445 $age = round($age_float,2);
1447 // round the years to 2 floating points
1448 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1449 return compact('age','age_in_months','ageinYMD');
1452 // Returns Age in days
1453 // in months if < 2 years old
1454 // in years if > 2 years old
1455 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1456 // (optional) nowYMD is a date in YYYYMMDD format
1457 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1460 // strip any dashes from the DOB
1461 $dobYMD = preg_replace("/-/", "", $dobYMD);
1462 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1464 // set the 'now' date values
1465 if ($nowYMD == null) {
1466 $nowDay = date("d");
1467 $nowMonth = date("m");
1468 $nowYear = date("Y");
1471 $nowDay = substr($nowYMD,6,2);
1472 $nowMonth = substr($nowYMD,4,2);
1473 $nowYear = substr($nowYMD,0,4);
1477 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1478 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1479 $timediff = $nowtime - $dobtime;
1480 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1485 * Returns a string to be used to display a patient's age
1487 * @param type $dobYMD
1488 * @param type $asOfYMD
1489 * @return string suitable for displaying patient's age based on preferences
1491 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1493 if($GLOBALS['age_display_format']=='1')
1495 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1496 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1498 return $ageYMD['ageinYMD'];
1502 return getPatientAge($dobYMD, $asOfYMD);
1507 return getPatientAge($dobYMD, $asOfYMD);
1511 function dateToDB ($date)
1513 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1518 // ----------------------------------------------------------------------------
1520 * DROPDOWN FOR COUNTRIES
1522 * build a dropdown with all countries from geo_country_reference
1524 * @param int $selected - id for selected record
1525 * @param string $name - the name/id for select form
1526 * @return void - just echo the html encoded string
1528 function dropdown_countries($selected = 0, $name = 'country_code') {
1529 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1531 $string = "<select name='$name' id='$name'>";
1532 while ( $row = sqlFetchArray($r) ) {
1533 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1534 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1537 $string .= '</select>';
1542 // ----------------------------------------------------------------------------
1544 * DROPDOWN FOR YES/NO
1546 * build a dropdown with two options (yes - 1, no - 0)
1548 * @param int $selected - id for selected record
1549 * @param string $name - the name/id for select form
1550 * @return void - just echo the html encoded string
1552 function dropdown_yesno($selected = 0, $name = 'yesno') {
1553 $string = "<select name='$name' id='$name'>";
1555 $selected = (int)$selected;
1556 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1557 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1559 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1560 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1561 $string .= '</select>';
1566 // ----------------------------------------------------------------------------
1568 * DROPDOWN FOR MALE/FEMALE options
1570 * build a dropdown with three options (unselected/male/female)
1572 * @param int $selected - id for selected record
1573 * @param string $name - the name/id for select form
1574 * @return void - just echo the html encoded string
1576 function dropdown_sex($selected = 0, $name = 'sex') {
1577 $string = "<select name='$name' id='$name'>";
1579 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1580 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1581 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1583 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1584 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1585 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1586 $string .= '</select>';
1591 // ----------------------------------------------------------------------------
1593 * DROPDOWN FOR MARITAL STATUS
1595 * build a dropdown with marital status
1597 * @param int $selected - id for selected record
1598 * @param string $name - the name/id for select form
1599 * @return void - just echo the html encoded string
1601 function dropdown_marital($selected = 0, $name = 'status') {
1602 $string = "<select name='$name' id='$name'>";
1604 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1606 foreach ( $statii as $st ) {
1607 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1608 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1611 $string .= '</select>';
1616 // ----------------------------------------------------------------------------
1618 * DROPDOWN FOR PROVIDERS
1620 * build a dropdown with all providers
1622 * @param int $selected - id for selected record
1623 * @param string $name - the name/id for select form
1624 * @return void - just echo the html encoded string
1626 function dropdown_providers($selected = 0, $name = 'status') {
1627 $provideri = getProviderInfo();
1629 $string = "<select name='$name' id='$name'>";
1630 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1631 foreach ( $provideri as $s ) {
1632 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1633 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1636 $string .= '</select>';
1641 // ----------------------------------------------------------------------------
1643 * DROPDOWN FOR INSURANCE COMPANIES
1645 * build a dropdown with all insurers
1647 * @param int $selected - id for selected record
1648 * @param string $name - the name/id for select form
1649 * @return void - just echo the html encoded string
1651 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1652 $insurancei = getInsuranceProviders();
1654 $string = "<select name='$name' id='$name'>";
1655 $string .= '<option value="0">Onbekend</option>';
1656 foreach ( $insurancei as $iid => $iname ) {
1657 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1658 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1661 $string .= '</select>';
1667 // ----------------------------------------------------------------------------
1671 * return the name or the country code, function of arguments
1673 * @param int $country_code
1674 * @param string $country_name
1675 * @return string | int - name or code
1677 function country_code($country_code = 0, $country_name = '') {
1679 if ( $country_code ) {
1680 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1682 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1685 $db = $GLOBALS['adodb']['db'];
1686 $result = $db->Execute($sql);
1687 if ($result && !$result->EOF) {
1688 $strint = $result->fields['res'];
1694 function DBToDate ($date)
1696 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1701 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1702 * for the given patient on the given date.
1704 * @param int The PID of the patient.
1705 * @param string Date in yyyy-mm-dd format.
1706 * @return array Array of 0-3 insurance_data rows.
1708 function getEffectiveInsurances($patient_id, $encdate) {
1710 foreach (array('primary','secondary','tertiary') as $instype) {
1711 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1712 "WHERE pid = ? AND type = ? " .
1713 "AND date <= ? ORDER BY date DESC LIMIT 1",
1714 array($patient_id, $instype, $encdate));
1715 if (empty($tmp['provider'])) break;
1722 * Get the patient's balance due. Normally this excludes amounts that are out
1723 * to insurance. If you want to include what insurance owes, set the second
1724 * parameter to true.
1726 * @param int The PID of the patient.
1727 * @param boolean Indicates if amounts owed by insurance are to be included.
1728 * @return number The balance.
1730 function get_patient_balance($pid, $with_insurance=false) {
1731 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1733 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1734 "last_level_closed, stmt_count " .
1735 "FROM form_encounter WHERE pid = ?", array($pid));
1736 while ($ferow = sqlFetchArray($feres)) {
1737 $encounter = $ferow['encounter'];
1738 $dos = substr($ferow['date'], 0, 10);
1739 $insarr = getEffectiveInsurances($pid, $dos);
1740 $inscount = count($insarr);
1741 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1742 // It's out to insurance so only the co-pay might be due.
1743 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1744 "pid = ? AND encounter = ? AND " .
1745 "code_type = 'copay' AND activity = 1",
1746 array($pid, $encounter));
1747 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1748 "FROM ar_activity WHERE " .
1749 "pid = ? AND encounter = ? AND payer_type = 0",
1750 array($pid, $encounter));
1751 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1752 if ($ptbal > 0) $balance += $ptbal;
1755 // Including insurance or not out to insurance, everything is due.
1756 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1757 "pid = ? AND encounter = ? AND " .
1758 "activity = 1", array($pid, $encounter));
1759 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1760 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1761 "pid = ? AND encounter = ?", array($pid, $encounter));
1762 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1763 "pid = ? AND encounter = ?", array($pid, $encounter));
1764 $balance += $brow['amount'] + $srow['amount']
1765 - $drow['payments'] - $drow['adjustments'];
1768 return sprintf('%01.2f', $balance);
1770 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1771 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1772 $conn = $GLOBALS['adodb']['db'];
1773 $customer_info['id'] = 0;
1774 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1775 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1776 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1777 "im.foreign_table = 'customer'";
1778 $result = $conn->Execute($sql);
1779 if($result && !$result->EOF) {
1780 $customer_info['id'] = $result->fields['foreign_id'];
1782 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1783 $ws = new WSWrapper($function);
1784 if(is_numeric($ws->value)) {
1785 return sprintf('%01.2f', $ws->value);
1791 // Function to check if patient is deceased.
1793 // $pid - patient id
1794 // $date - date checking if deceased (will default to current date if blank)
1796 // If deceased, then will return the number of
1797 // days that patient has been deceased.
1798 // If not deceased, then will return false.
1799 function is_patient_deceased($pid,$date='') {
1801 // Set date to current if not set
1802 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1804 // Query for deceased status (gets days deceased if patient is deceased)
1805 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1806 "FROM `patient_data` " .
1807 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1809 if (empty($results)) {
1810 // Patient is alive, so return false
1814 // Patient is dead, so return the number of days patient has been deceased.
1815 // Don't let it be zero days or else will confuse calls to this function.
1816 if ($results['days_deceased'] === 0) {
1817 $results['days_deceased'] = 1;
1819 return $results['days_deceased'];