More recurring appointment fixes
[openemr.git] / library / patient.inc
blob39519d0504817c87d84d1a4d3c87069611b33691
1 <?php
2 /**
3  * patient.inc includes functions for manipulating patient information.
4  *
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.
9  */
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(
17   xl('Full Play'),
18   xl('Full Training'),
19   xl('Restricted Training'),
20   xl('Injured Out'),
21   xl('Rehabilitation'),
22   xl('Illness'),
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(
30   ''   => xl('N/A'),
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'),
42 /**
43  * Get a patient's demographic data.
44  *
45  * @param int    $pid   The PID of the patient
46  * @param string $given an optional subsection of the patient's demographic
47  *                      data to retrieve.
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.
51  */
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"]);
64         }
65     }
66     return $returnval;
69 function getInsuranceProvider($ins_id) {
70     
71     $sql = "select name from insurance_companies where id=?";
72     $row = sqlQuery($sql,array($ins_id));
73     return $row['name'];
74     
77 function getInsuranceProviders() {
78     $returnval = array();
80     if (true) {
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'];
85         }
86     }
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
91     //
92     else {
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] . ")";
105         }
106     }
108     return $returnval;
111 function getProviders() {
112     $returnval = array("");
113     $sql = "select fname, lname from users where authorized = 1 and " .
114         "active = 1 and username != ''";
115     $rez = sqlStatement($sql);
116     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
117         if (($row["fname"] != "") && ($row["lname"] != "")) {
118             array_push($returnval, $row["fname"] . " " . $row["lname"]);
119         }
120     }
121     return $returnval;
124 // ----------------------------------------------------------------------------
125 // Get one facility row.  If the ID is not specified, then get either the
126 // "main" (billing) facility, or the default facility of the currently
127 // logged-in user.  This was created to support genFacilityTitle() but
128 // may find additional uses.
130 function getFacility($facid=0) {
132   //create a sql binding array
133   $sqlBindArray = array();
134   
135   if ($facid > 0) {
136     $query = "SELECT * FROM facility WHERE id = ?";
137     array_push($sqlBindArray,$facid);
138   }
139   else if ($facid == 0) {
140     $query = "SELECT * FROM facility ORDER BY " .
141       "billing_location DESC, service_location, id LIMIT 1";
142   }
143   else {
144     $query = "SELECT facility.* FROM users, facility WHERE " .
145       "users.id = ? AND " .
146       "facility.id = users.facility_id";
147     array_push($sqlBindArray,$_SESSION['authUserID']);
148   }
149   return sqlQuery($query,$sqlBindArray);
152 // Generate a report title including report name and facility name, address
153 // and phone.
155 function genFacilityTitle($repname='', $facid=0) {
156   $s = '';
157   $s .= "<table class='ftitletable'>\n";
158   $s .= " <tr>\n";
159   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
160   $s .= "  <td class='ftitlecell2'>\n";
161   $r = getFacility($facid);
162   if (!empty($r)) {
163     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
164     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
165     if ($r['city'] || $r['state'] || $r['postal_code']) {
166       $s .= "<br />";
167       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
168       if ($r['state']) {
169         if ($r['city']) $s .= ", \n";
170         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
171       }
172       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
173       $s .= "\n";
174     }
175     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
176     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
177   }
178   $s .= "  </td>\n";
179   $s .= " </tr>\n";
180   $s .= "</table>\n";
181   return $s;
185 GET FACILITIES
187 returns all facilities or just the id for the first one
188 (FACILITY FILTERING (lemonsoftware))
190 @param string - if 'first' return first facility ordered by id
191 @return array | int for 'first' case
193 function getFacilities($first = '') {
194     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
195     $ret = array();
196     while ( $row = sqlFetchArray($r) ) {
197        $ret[] = $row;
200         if ( $first == 'first') {
201             return $ret[0]['id'];
202         } else {
203             return $ret;
204         }
208 GET SERVICE FACILITIES
210 returns all service_location facilities or just the id for the first one
211 (FACILITY FILTERING (CHEMED))
213 @param string - if 'first' return first facility ordered by id
214 @return array | int for 'first' case
216 function getServiceFacilities($first = '') {
217     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
218     $ret = array();
219     while ( $row = sqlFetchArray($r) ) {
220        $ret[] = $row;
223         if ( $first == 'first') {
224             return $ret[0]['id'];
225         } else {
226             return $ret;
227         }
230 //(CHEMED) facility filter
231 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
232     $param1 = "";
233     if ($providers_only === 'any') {
234       $param1 = " AND authorized = 1 AND active = 1 ";
235     }
236     else if ($providers_only) {
237       $param1 = " AND authorized = 1 AND calendar = 1 ";
238     }
240     //--------------------------------
241     //(CHEMED) facility filter
242     $param2 = "";
243     if ($facility) {
244       if ($GLOBALS['restrict_user_facility']) {
245         $param2 = " AND (facility_id = $facility 
246           OR  $facility IN
247                 (select facility_id 
248                 from users_facility
249                 where tablename = 'users'
250                 and table_id = id)
251                 )
252           ";
253       }
254       else {
255         $param2 = " AND facility_id = $facility ";
256       }
257     }
258     //--------------------------------
260     $command = "=";
261     if ($providerID == "%") {
262         $command = "like";
263     }
264     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
265         "from users where username != '' and active = 1 and id $command '" .
266         add_escape_custom($providerID) . "' " . $param1 . $param2;
267     // sort by last name -- JRM June 2008
268     $query .= " ORDER BY lname, fname ";
269     $rez = sqlStatement($query);
270     for($iter=0; $row=sqlFetchArray($rez); $iter++)
271         $returnval[$iter]=$row;
273     //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
274     //accessible from $resultval['key']
276     if($iter==1) {
277         $akeys = array_keys($returnval[0]);
278         foreach($akeys as $key) {
279             $returnval[0][$key] = $returnval[0][$key];
280         }
281     }
282     return $returnval;
285 //same as above but does not reduce if only 1 row returned
286 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
287     $param1 = "";
288     if ($providers_only) {
289         $param1 = "AND authorized=1";
290     }
291     $command = "=";
292     if ($providerID == "%") {
293         $command = "like";
294     }
295     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
296         "from users where active = 1 and username != '' and id $command '" .
297         add_escape_custom($providerID) . "' " . $param1;
299     $rez = sqlStatement($query);
300     for($iter=0; $row=sqlFetchArray($rez); $iter++)
301         $returnval[$iter]=$row;
303     return $returnval;
306 function getProviderName($providerID) {
307     $pi = getProviderInfo($providerID, 'any');
308     if (strlen($pi[0]["lname"]) > 0) {
309         return $pi[0]['fname'] . " " . $pi[0]['lname'];
310     }
311     return "";
314 function getProviderId($providerName) {
315     $query = "select id from users where username = ?";
316     $rez = sqlStatement($query, array($providerName) );
317     for($iter=0; $row=sqlFetchArray($rez); $iter++)
318         $returnval[$iter]=$row;
319     return $returnval;
322 function getEthnoRacials() {
323     $returnval = array("");
324     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
325     $rez = sqlStatement($sql);
326     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
327         if (($row["ethnoracial"] != "")) {
328             array_push($returnval, $row["ethnoracial"]);
329         }
330     }
331     return $returnval;
334 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
337     if ($dateStart && $dateEnd) {
338         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
339     }
340     else if ($dateStart && !$dateEnd) {
341         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
342     }
343     else if (!$dateStart && $dateEnd) {
344         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
345     }
346     else {
347         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
348     }
350     return $res;
353 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
354 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
356   $sql = "select $given from insurance_data as insd " .
357     "left join insurance_companies as ic on ic.id = insd.provider " .
358     "where pid = ? and type = ? order by date DESC limit 1";
359   return sqlQuery($sql, array($pid, $type) );
362 function getInsuranceDataByDate($pid, $date, $type,
363   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
364 { // this must take the date in the following manner: YYYY-MM-DD
365   // this function recalls the insurance value that was most recently enterred from the
366   // given date. it will call up most recent records up to and on the date given,
367   // but not records enterred after the given date
368   $sql = "select $given from insurance_data as insd " .
369     "left join insurance_companies as ic on ic.id = provider " .
370     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
371     "type=? order by date DESC limit 1";
372   return sqlQuery($sql, array($pid,$date,$type) );
375 function getEmployerData($pid, $given = "*")
377     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
378     return sqlQuery($sql, array($pid) );
381 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
382   // When the limit is exceeded, find out what the unlimited count would be.
383   $GLOBALS['PATIENT_INC_COUNT'] = $count;
384   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
385   if ($limit != "all") {
386     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
387     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
388   }
391 function getPatientLnames($lname = "%", $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")
393     // Allow the last name to be followed by a comma and some part of a first name.
394     // Allows comma alone followed by some part of a first name.
395     // Allows comma alone preceded by some part of a last name.
396     // If no comma, then will search both last name and first name.
397     // If the first letter of either name is capital, searches for name starting
398     //   with given substring (the expected behavior). If it is lower case, it
399     //   it searches for the substring anywhere in the name. This applies to either
400     //   last name or first name or both.
401     $fname = $lname = trim($lname);
402     $where = "lname LIKE ? OR fname LIKE ? ";
403     if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
404          $lname = trim($matches[1]);
405          $fname = trim($matches[2]);
406          $where = "lname LIKE ? AND fname LIKE ? ";
407     }
409     $search_for_pieces1 = '';
410     $search_for_pieces2 = '';
411     if ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
412     if ((strlen($fname) < 1)|| ($fname{0} != strtoupper($fname{0}))) {$search_for_pieces2 = '%';}
414     $sqlBindArray = array();
415     array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
416         if (!empty($GLOBALS['pt_restrict_field'])) {
417                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
418                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
419                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
420                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
421                         array_push($sqlBindArray, $_SESSION{"authUser"});
422                 }
423         }
425     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
426     if ($limit != "all") $sql .= " LIMIT $start, $limit";
428     $rez = sqlStatement($sql, $sqlBindArray);
430     $returnval=array();
431     for($iter=0; $row=sqlFetchArray($rez); $iter++)
432         $returnval[$iter] = $row;
434     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
435     return $returnval;
438 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")
441     $sqlBindArray = array();
442     $where = "pubpid LIKE ? ";
443     array_push($sqlBindArray, $pid."%");
444         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
445                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
446                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
447                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
448                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
449                         array_push($sqlBindArray, $_SESSION{"authUser"});
450                 }
451         }
453     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
454     if ($limit != "all") $sql .= " limit $start, $limit";
455     $rez = sqlStatement($sql, $sqlBindArray);
456     for($iter=0; $row=sqlFetchArray($rez); $iter++)
457         $returnval[$iter]=$row;
459     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
460     return $returnval;
463 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")
465   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
467   $sqlBindArray = array();
468   $where = "";
469   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
470     if ( $iter > 0 ) {
471       $where .= " or ";
472     }
473     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
474     array_push($sqlBindArray, "%".$searchTerm."%");
475   }
477   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
478   if ($limit != "all") $sql .= " limit $start, $limit";
479   $rez = sqlStatement($sql, $sqlBindArray);
480   for($iter=0; $row=sqlFetchArray($rez); $iter++)
481     $returnval[$iter]=$row;
482   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
483   return $returnval;
486 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
487   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
488   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
490         $layoutCols = split( '~', $searchFields );
491   $sqlBindArray = array();
492   $where = "";
493   $i = 0;
494   foreach ($layoutCols as $val) {
495     if (empty($val)) continue;
496                 if ( $i > 0 ) {
497                    $where .= " or ";
498                 }
499     if ($val == 'pid') {
500                 $where .= " ".add_escape_custom($val)." = ? ";
501                 array_push($sqlBindArray, $searchTerm);
502     }
503     else {
504                 $where .= " ".add_escape_custom($val)." like ? ";
505                 array_push($sqlBindArray, $searchTerm."%");
506     }
507                 $i++;
508         }
510   // If no search terms, ensure valid syntax.
511   if ($i == 0) $where = "1 = 1";
513   // If a non-empty service code was given, then restrict to patients who
514   // have been provided that service.  Since the code is used in a LIKE
515   // clause, % and _ wildcards are supported.
516   if ($search_service_code) {
517     $where = "( $where ) AND " .
518       "( SELECT COUNT(*) FROM billing AS b WHERE " .
519       "b.pid = patient_data.pid AND " .
520       "b.activity = 1 AND " .
521       "b.code_type != 'COPAY' AND " .
522       "b.code LIKE ? " .
523       ") > 0";
524     array_push($sqlBindArray, $search_service_code);
525   }
527   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
528   if ($limit != "all") $sql .= " limit $start, $limit";
529   $rez = sqlStatement($sql, $sqlBindArray);
530   for($iter=0; $row=sqlFetchArray($rez); $iter++)
531       $returnval[$iter]=$row;
532   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
533   return $returnval;
536 // return a collection of Patient PIDs
537 // new arg style by JRM March 2008
538 // 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")
539 function getPatientPID($args)
541     $pid = "%";
542     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
543     $orderby = "lname ASC, fname ASC";
544     $limit="all";
545     $start="0";
547     // alter default values if defined in the passed in args
548     if (isset($args['pid'])) { $pid = $args['pid']; }
549     if (isset($args['given'])) { $given = $args['given']; }
550     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
551     if (isset($args['limit'])) { $limit = $args['limit']; }
552     if (isset($args['start'])) { $start = $args['start']; }
554     $command = "=";
555     if ($pid == -1) $pid = "%";
556     elseif (empty($pid)) $pid = "NULL";
558     if (strstr($pid,"%")) $command = "like";
560     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
561     if ($limit != "all") $sql .= " limit $start, $limit";
563     $rez = sqlStatement($sql);
564     for($iter=0; $row=sqlFetchArray($rez); $iter++)
565         $returnval[$iter]=$row;
567     return $returnval;
570 /* return a patient's name in the format LAST, FIRST */
571 function getPatientName($pid) {
572     if (empty($pid)) return "";
573     $patientData = getPatientPID(array("pid"=>$pid));
574     if (empty($patientData[0]['lname'])) return "";
575     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
576     return $patientName;
579 /* find patient data by DOB */
580 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
582     $DOB = fixDate($DOB, $DOB);
583     $sqlBindArray = array();
584     $where = "DOB like ? ";
585     array_push($sqlBindArray, $DOB."%");
586         if (!empty($GLOBALS['pt_restrict_field'])) {
587                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
588                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
589                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
590                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
591                         array_push($sqlBindArray, $_SESSION{"authUser"});
592                 }
593         }
595     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
597     if ($limit != "all") $sql .= " LIMIT $start, $limit";
599     $rez = sqlStatement($sql, $sqlBindArray);
600     for($iter=0; $row=sqlFetchArray($rez); $iter++)
601         $returnval[$iter]=$row;
603     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
604     return $returnval;
607 /* find patient data by SSN */
608 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
610     $sqlBindArray = array();
611     $where = "ss LIKE ?";
612     array_push($sqlBindArray, $ss."%");
613     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
614     if ($limit != "all") $sql .= " LIMIT $start, $limit";
616     $rez = sqlStatement($sql, $sqlBindArray);
617     for($iter=0; $row=sqlFetchArray($rez); $iter++)
618         $returnval[$iter]=$row;
620     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
621     return $returnval;
624 //(CHEMED) Search by phone number
625 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
627     $phone = ereg_replace( "[[:punct:]]","", $phone );
628     $sqlBindArray = array();
629     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
630     array_push($sqlBindArray, $phone);
631     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
632     if ($limit != "all") $sql .= " LIMIT $start, $limit";
634     $rez = sqlStatement($sql, $sqlBindArray);
635     for($iter=0; $row=sqlFetchArray($rez); $iter++)
636         $returnval[$iter]=$row;
638     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
639     return $returnval;
642 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
644     $sql="select $given from patient_data order by $orderby";
646     if ($limit != "all")
647         $sql .= " limit $start, $limit";
649     $rez = sqlStatement($sql);
650     for($iter=0; $row=sqlFetchArray($rez); $iter++)
651         $returnval[$iter]=$row;
653     return $returnval;
656 //----------------------input functions
657 function newPatientData(    $db_id="",
658                 $title = "",
659                 $fname = "",
660                 $lname = "",
661                 $mname = "",
662                 $sex = "",
663                 $DOB = "",
664                 $street = "",
665                 $postal_code = "",
666                 $city = "",
667                 $state = "",
668                 $country_code = "",
669                 $ss = "",
670                 $occupation = "",
671                 $phone_home = "",
672                 $phone_biz = "",
673                 $phone_contact = "",
674                 $status = "",
675                 $contact_relationship = "",
676                 $referrer = "",
677                 $referrerID = "",
678                 $email = "",
679                 $language = "",
680                 $ethnoracial = "",
681                 $interpretter = "",
682                 $migrantseasonal = "",
683                 $family_size = "",
684                 $monthly_income = "",
685                 $homeless = "",
686                 $financial_review = "",
687                 $pubpid = "",
688                 $pid = "MAX(pid)+1",
689                 $providerID = "",
690                 $genericname1 = "",
691                 $genericval1 = "",
692                 $genericname2 = "",
693                 $genericval2 = "",
694                 $phone_cell = "",
695                 $hipaa_mail = "",
696                 $hipaa_voice = "",
697                 $squad = 0,
698                 $pharmacy_id = 0,
699                 $drivers_license = "",
700                 $hipaa_notice = "",
701                 $hipaa_message = "",
702                 $regdate = ""
703             )
705     $DOB = fixDate($DOB);
706     $regdate = fixDate($regdate);
708     $fitness = 0;
709     $referral_source = '';
710     if ($pid) {
711         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
712         // Check for brain damage:
713         if ($db_id != $rez['id']) {
714             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
715               $rez['id'] . "' to '$db_id' for pid '$pid'";
716             die($errmsg);
717         }
718         $fitness = $rez['fitness'];
719         $referral_source = $rez['referral_source'];
720     }
722     // Get the default price level.
723     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
724       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
725     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
727     $query = ("replace into patient_data set
728         id='$db_id',
729         title='$title',
730         fname='$fname',
731         lname='$lname',
732         mname='$mname',
733         sex='$sex',
734         DOB='$DOB',
735         street='$street',
736         postal_code='$postal_code',
737         city='$city',
738         state='$state',
739         country_code='$country_code',
740         drivers_license='$drivers_license',
741         ss='$ss',
742         occupation='$occupation',
743         phone_home='$phone_home',
744         phone_biz='$phone_biz',
745         phone_contact='$phone_contact',
746         status='$status',
747         contact_relationship='$contact_relationship',
748         referrer='$referrer',
749         referrerID='$referrerID',
750         email='$email',
751         language='$language',
752         ethnoracial='$ethnoracial',
753         interpretter='$interpretter',
754         migrantseasonal='$migrantseasonal',
755         family_size='$family_size',
756         monthly_income='$monthly_income',
757         homeless='$homeless',
758         financial_review='$financial_review',
759         pubpid='$pubpid',
760         pid = $pid,
761         providerID = '$providerID',
762         genericname1 = '$genericname1',
763         genericval1 = '$genericval1',
764         genericname2 = '$genericname2',
765         genericval2 = '$genericval2',
766         phone_cell = '$phone_cell',
767         pharmacy_id = '$pharmacy_id',
768         hipaa_mail = '$hipaa_mail',
769         hipaa_voice = '$hipaa_voice',
770         hipaa_notice = '$hipaa_notice',
771         hipaa_message = '$hipaa_message',
772         squad = '$squad',
773         fitness='$fitness',
774         referral_source='$referral_source',
775         regdate='$regdate',
776         pricelevel='$pricelevel',
777         date=NOW()");
779     $id = sqlInsert($query);
781     if ( !$db_id ) {
782       // find the last inserted id for new patient case
783       $db_id = mysql_insert_id();
784     }
786     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
788     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
789                 $phone_biz,$phone_cell,$email,$pid);
791     return $foo['pid'];
794 // Supported input date formats are:
795 //   mm/dd/yyyy
796 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
797 //   yyyy/mm/dd
798 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
800 function fixDate($date, $default="0000-00-00") {
801     $fixed_date = $default;
802     $date = trim($date);
803     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
804         $dmy = preg_split("'[/.-]'", $date);
805         if ($dmy[0] > 99) {
806             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
807         } else {
808             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
809               if ($dmy[2] < 1000) $dmy[2] += 1900;
810               if ($dmy[2] < 1910) $dmy[2] += 100;
811             }
812             // phone_country_code indicates format of ambiguous input dates.
813             if ($GLOBALS['phone_country_code'] == 1)
814               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
815             else
816               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
817         }
818     }
820     return $fixed_date;
823 function pdValueOrNull($key, $value) {
824   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
825     substr($key, 0, 8) == 'userdate') &&
826     (empty($value) || $value == '0000-00-00'))
827   {
828     return "NULL";
829   }
830   else {
831     return "'$value'";
832   }
835 // Create or update patient data from an array.
837 function updatePatientData($pid, $new, $create=false)
839   /*******************************************************************
840     $real = getPatientData($pid);
841     $new['DOB'] = fixDate($new['DOB']);
842     while(list($key, $value) = each ($new))
843         $real[$key] = $value;
844     $real['date'] = "'+NOW()+'";
845     $real['id'] = "";
846     $sql = "insert into patient_data set ";
847     while(list($key, $value) = each($real))
848         $sql .= $key." = '$value', ";
849     $sql = substr($sql, 0, -2);
850     return sqlInsert($sql);
851   *******************************************************************/
853   // The above was broken, though seems intent to insert a new patient_data
854   // row for each update.  A good idea, but nothing is doing that yet so
855   // the code below does not yet attempt it.
857   $new['DOB'] = fixDate($new['DOB']);
859   if ($create) {
860     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
861     foreach ($new as $key => $value) {
862       if ($key == 'id') continue;
863       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
864     }
865     $db_id = sqlInsert($sql);
866   }
867   else {
868     $db_id = $new['id'];
869     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
870     // Check for brain damage:
871     if ($pid != $rez['pid']) {
872       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
873         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
874       die($errmsg);
875     }
876     $sql = "UPDATE patient_data SET date = NOW()";
877     foreach ($new as $key => $value) {
878       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
879     }
880     $sql .= " WHERE id = '$db_id'";
881     sqlStatement($sql);
882   }
884   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
885   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
886     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
887     $rez['phone_cell'],$rez['email'],$rez['pid']);
889   return $db_id;
892 function newEmployerData(    $pid,
893                 $name = "",
894                 $street = "",
895                 $postal_code = "",
896                 $city = "",
897                 $state = "",
898                 $country = ""
899             )
901     return sqlInsert("insert into employer_data set
902         name='$name',
903         street='$street',
904         postal_code='$postal_code',
905         city='$city',
906         state='$state',
907         country='$country',
908         pid='$pid',
909         date=NOW()
910         ");
913 // Create or update employer data from an array.
915 function updateEmployerData($pid, $new, $create=false)
917   $colnames = array('name','street','city','state','postal_code','country');
919   if ($create) {
920     $set .= "pid = '$pid', date = NOW()";
921     foreach ($colnames as $key) {
922       $value = isset($new[$key]) ? $new[$key] : '';
923       $set .= ", `$key` = '$value'";
924     }
925     return sqlInsert("INSERT INTO employer_data SET $set");
926   }
927   else {
928     $set = '';
929     $old = getEmployerData($pid);
930     $modified = false;
931     foreach ($colnames as $key) {
932       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
933       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
934         $value = $new[$key];
935         $modified = true;
936       }
937       $set .= "`$key` = '$value', ";
938     }
939     if ($modified) {
940       $set .= "pid = '$pid', date = NOW()";
941       return sqlInsert("INSERT INTO employer_data SET $set");
942     }
943     return $old['id'];
944   }
947 // This updates or adds the given insurance data info, while retaining any
948 // previously added insurance_data rows that should be preserved.
949 // This does not directly support the maintenance of non-current insurance.
951 function newInsuranceData(
952   $pid,
953   $type = "",
954   $provider = "",
955   $policy_number = "",
956   $group_number = "",
957   $plan_name = "",
958   $subscriber_lname = "",
959   $subscriber_mname = "",
960   $subscriber_fname = "",
961   $subscriber_relationship = "",
962   $subscriber_ss = "",
963   $subscriber_DOB = "",
964   $subscriber_street = "",
965   $subscriber_postal_code = "",
966   $subscriber_city = "",
967   $subscriber_state = "",
968   $subscriber_country = "",
969   $subscriber_phone = "",
970   $subscriber_employer = "",
971   $subscriber_employer_street = "",
972   $subscriber_employer_city = "",
973   $subscriber_employer_postal_code = "",
974   $subscriber_employer_state = "",
975   $subscriber_employer_country = "",
976   $copay = "",
977   $subscriber_sex = "",
978   $effective_date = "0000-00-00",
979   $accept_assignment = "TRUE",
980   $policy_type = "")
982   if (strlen($type) <= 0) return FALSE;
984   // If a bad date was passed, err on the side of caution.
985   $effective_date = fixDate($effective_date, date('Y-m-d'));
987   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
988     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
989   $idrow = sqlFetchArray($idres);
991   // Replace the most recent entry in any of the following cases:
992   // * Its effective date is >= this effective date.
993   // * It is the first entry and it has no (insurance) provider.
994   // * There is no encounter that is earlier than the new effective date but
995   //   on or after the old effective date.
996   // Otherwise insert a new entry.
998   $replace = false;
999   if ($idrow) {
1000     if (strcmp($idrow['date'], $effective_date) > 0) {
1001       $replace = true;
1002     }
1003     else {
1004       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1005         $replace = true;
1006       }
1007       else {
1008         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1009           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1010           "date >= '" . $idrow['date'] . " 00:00:00'");
1011         if ($ferow['count'] == 0) $replace = true;
1012       }
1013     }
1014   }
1016   if ($replace) {
1018     // TBD: This is a bit dangerous in that a typo in entering the effective
1019     // date can wipe out previous insurance history.  So we want some data
1020     // entry validation somewhere.
1021     sqlStatement("DELETE FROM insurance_data WHERE " .
1022       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1023       "id != " . $idrow['id']);
1025     $data = array();
1026     $data['type'] = $type;
1027     $data['provider'] = $provider;
1028     $data['policy_number'] = $policy_number;
1029     $data['group_number'] = $group_number;
1030     $data['plan_name'] = $plan_name;
1031     $data['subscriber_lname'] = $subscriber_lname;
1032     $data['subscriber_mname'] = $subscriber_mname;
1033     $data['subscriber_fname'] = $subscriber_fname;
1034     $data['subscriber_relationship'] = $subscriber_relationship;
1035     $data['subscriber_ss'] = $subscriber_ss;
1036     $data['subscriber_DOB'] = $subscriber_DOB;
1037     $data['subscriber_street'] = $subscriber_street;
1038     $data['subscriber_postal_code'] = $subscriber_postal_code;
1039     $data['subscriber_city'] = $subscriber_city;
1040     $data['subscriber_state'] = $subscriber_state;
1041     $data['subscriber_country'] = $subscriber_country;
1042     $data['subscriber_phone'] = $subscriber_phone;
1043     $data['subscriber_employer'] = $subscriber_employer;
1044     $data['subscriber_employer_city'] = $subscriber_employer_city;
1045     $data['subscriber_employer_street'] = $subscriber_employer_street;
1046     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1047     $data['subscriber_employer_state'] = $subscriber_employer_state;
1048     $data['subscriber_employer_country'] = $subscriber_employer_country;
1049     $data['copay'] = $copay;
1050     $data['subscriber_sex'] = $subscriber_sex;
1051     $data['pid'] = $pid;
1052     $data['date'] = $effective_date;
1053     $data['accept_assignment'] = $accept_assignment;
1054     $data['policy_type'] = $policy_type;
1055     updateInsuranceData($idrow['id'], $data);
1056     return $idrow['id'];
1057   }
1058   else {
1059     return sqlInsert("INSERT INTO insurance_data SET
1060       type = '$type',
1061       provider = '$provider',
1062       policy_number = '$policy_number',
1063       group_number = '$group_number',
1064       plan_name = '$plan_name',
1065       subscriber_lname = '$subscriber_lname',
1066       subscriber_mname = '$subscriber_mname',
1067       subscriber_fname = '$subscriber_fname',
1068       subscriber_relationship = '$subscriber_relationship',
1069       subscriber_ss = '$subscriber_ss',
1070       subscriber_DOB = '$subscriber_DOB',
1071       subscriber_street = '$subscriber_street',
1072       subscriber_postal_code = '$subscriber_postal_code',
1073       subscriber_city = '$subscriber_city',
1074       subscriber_state = '$subscriber_state',
1075       subscriber_country = '$subscriber_country',
1076       subscriber_phone = '$subscriber_phone',
1077       subscriber_employer = '$subscriber_employer',
1078       subscriber_employer_city = '$subscriber_employer_city',
1079       subscriber_employer_street = '$subscriber_employer_street',
1080       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1081       subscriber_employer_state = '$subscriber_employer_state',
1082       subscriber_employer_country = '$subscriber_employer_country',
1083       copay = '$copay',
1084       subscriber_sex = '$subscriber_sex',
1085       pid = '$pid',
1086       date = '$effective_date',
1087       accept_assignment = '$accept_assignment',
1088       policy_type = '$policy_type'
1089     ");
1090   }
1093 // This is used internally only.
1094 function updateInsuranceData($id, $new)
1096   $fields = sqlListFields("insurance_data");
1097   $use = array();
1099   while(list($key, $value) = each ($new)) {
1100     if (in_array($key, $fields)) {
1101       $use[$key] = $value;
1102     }
1103   }
1105   $sql = "UPDATE insurance_data SET ";
1106   while(list($key, $value) = each($use))
1107     $sql .= "`$key` = '$value', ";
1108   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1110   sqlStatement($sql);
1113 function newHistoryData($pid, $new=false) {
1114   $arraySqlBind = array();
1115   $sql = "insert into history_data set pid = ?, date = NOW()";
1116   array_push($arraySqlBind,$pid);
1117   if ($new) {
1118     while(list($key, $value) = each($new)) {
1119       array_push($arraySqlBind,$value);
1120       $sql .= ", `$key` = ?";
1121     }
1122   }
1123   return sqlInsert($sql, $arraySqlBind );
1126 function updateHistoryData($pid,$new)
1128         $real = getHistoryData($pid);
1129         while(list($key, $value) = each ($new))
1130                 $real[$key] = $value;
1131         $real['id'] = "";
1132         // need to unset date, so can reset it below
1133         unset($real['date']);
1135         $arraySqlBind = array();
1136         $sql = "insert into history_data set `date` = NOW(), ";
1137         while(list($key, $value) = each($real)) {
1138                 array_push($arraySqlBind,$value);
1139                 $sql .= "`$key` = ?, ";
1140         }
1141         $sql = substr($sql, 0, -2);
1143         return sqlInsert($sql, $arraySqlBind );
1146 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1147                 $phone_biz,$phone_cell,$email,$pid="")
1149     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1150     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1152     $db = $GLOBALS['adodb']['db'];
1153     $customer_info = array();
1155     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1156     $result = $db->Execute($sql);
1157     if ($result && !$result->EOF) {
1158         $customer_info['foreign_update'] = true;
1159         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1160         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1161     }
1163     ///xml rpc code to connect to accounting package and add user to it
1164     $customer_info['firstname'] = $fname;
1165     $customer_info['lastname'] = $lname;
1166     $customer_info['address'] = $street;
1167     $customer_info['suburb'] = $city;
1168     $customer_info['state'] = $state;
1169     $customer_info['postcode'] = $postal_code;
1171     //ezybiz wants state as a code rather than abbreviation
1172     $customer_info['geo_zone_id'] = "";
1173     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1174     $db = $GLOBALS['adodb']['db'];
1175     $result = $db->Execute($sql);
1176     if ($result && !$result->EOF) {
1177         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1178     }
1180     //ezybiz wants country as a code rather than abbreviation
1181     $customer_info['geo_country_id'] = "";
1182     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1183     $db = $GLOBALS['adodb']['db'];
1184     $result = $db->Execute($sql);
1185     if ($result && !$result->EOF) {
1186         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1187     }
1189     $customer_info['phone1'] = $phone_home;
1190     $customer_info['phone1comment'] = "Home Phone";
1191     $customer_info['phone2'] = $phone_biz;
1192     $customer_info['phone2comment'] = "Business Phone";
1193     $customer_info['phone3'] = $phone_cell;
1194     $customer_info['phone3comment'] = "Cell Phone";
1195     $customer_info['email'] = $email;
1196     $customer_info['customernumber'] = $pid;
1198     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1199     $ws = new WSWrapper($function);
1201     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1202     if (is_numeric($ws->value)) {
1203         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1204         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1205     }
1208 // Returns Age 
1209 //   in months if < 2 years old
1210 //   in years  if > 2 years old
1211 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1212 // (optional) nowYMD is a date in YYYYMMDD format
1213 function getPatientAge($dobYMD, $nowYMD=null)
1215     // strip any dashes from the DOB
1216     $dobYMD = preg_replace("/-/", "", $dobYMD);
1217     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1218     
1219     // set the 'now' date values
1220     if ($nowYMD == null) {
1221         $nowDay = date("d");
1222         $nowMonth = date("m");
1223         $nowYear = date("Y");
1224     }
1225     else {
1226         $nowDay = substr($nowYMD,6,2);
1227         $nowMonth = substr($nowYMD,4,2);
1228         $nowYear = substr($nowYMD,0,4);
1229     }
1231     $dayDiff = $nowDay - $dobDay;
1232     $monthDiff = $nowMonth - $dobMonth;
1233     $yearDiff = $nowYear - $dobYear;
1235     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1237     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1238     if($dayDiff<0) { $ageInMonths-=1; } 
1239     
1240     if ( $ageInMonths > 24 ) {
1241         $age = $yearDiff;
1242         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1243         else if ($monthDiff < 0) { $age -= 1; }
1244     }
1245     else  {
1246         $age = "$ageInMonths month"; 
1247     }
1249     return $age;
1253  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1254  * format expected by getPatientAgeYMD
1256  * @param  string  $dob     date of birth
1257  * @param  string  $target  date to calculate age on
1258  * @return array containing
1259  *      age - decimal age in years
1260  *      age_in_months - decimal age in months
1261  *      ageinYMD - formatted string #y #m #d */
1262 function parseAgeInfo($dob,$target)
1264     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1265     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1266     // Prepare target (Y-M-D H:M:S)
1267     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1269     return getPatientAgeYMD($dateDOB,$dateTarget);
1274  * 
1275  * @param type $dob
1276  * @param type $date
1277  * @return array containing
1278  *      age - decimal age in years
1279  *      age_in_months - decimal age in months
1280  *      ageinYMD - formatted string #y #m #d
1281  */
1282 function getPatientAgeYMD($dob, $date=null) {
1283         
1284     if ($date == null) {
1285         $daynow = date("d");
1286         $monthnow = date("m");
1287         $yearnow = date("Y");
1288         $datenow=$yearnow.$monthnow.$daynow;
1289     }
1290     else {
1291         $datenow=preg_replace("/-/", "", $date);
1292         $yearnow=substr($datenow,0,4);
1293         $monthnow=substr($datenow,4,2);
1294         $daynow=substr($datenow,6,2);
1295         $datenow=$yearnow.$monthnow.$daynow;
1296     }
1298     $dob=preg_replace("/-/", "", $dob);
1299     $dobyear=substr($dob,0,4);
1300     $dobmonth=substr($dob,4,2);
1301     $dobday=substr($dob,6,2);
1302     $dob=$dobyear.$dobmonth.$dobday;
1304     //to compensate for 30, 31, 28, 29 days/month
1305     $mo=$monthnow; //to avoid confusion with later calculation
1307     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1308         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1309     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1310     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1311         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1312         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1313         else {$nd=28;} //otherwise, it is not a leap year.
1314     }
1315     else {$nd=31;} // other months have 31 days
1317     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1318     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1319     {
1320         $age_year = $yearnow - $dobyear - 1;
1321         if ($daynow < $dobday) {
1322             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1323             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1324         }
1325         else {
1326             $months_since_birthday=12 - $dobmonth + $monthnow;
1327             $days_since_dobday=$daynow - $dobday;
1328         }
1329     }
1330     else // if patient has had birthday this calandar year
1331     {
1332         $age_year = $yearnow - $dobyear;
1333         if ($daynow < $dobday) {
1334             $months_since_birthday=$monthnow - $dobmonth -1;
1335             $days_since_dobday=$nd - $dobday + $daynow;
1336         }
1337         else {
1338             $months_since_birthday=$monthnow - $dobmonth;
1339             $days_since_dobday=$daynow - $dobday;
1340         }       
1341     }
1342     
1343     $day_as_month_decimal = $days_since_dobday / 30;
1344     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1345     $month_as_year_decimal = $months_since_birthday_float / 12;
1346     $age_float = $age_year + $month_as_year_decimal;
1348     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1349     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1350     $age = round($age_float,2);
1352     // round the years to 2 floating points
1353     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1354     return compact('age','age_in_months','ageinYMD');
1357 // Returns Age in days
1358 //   in months if < 2 years old
1359 //   in years  if > 2 years old
1360 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1361 // (optional) nowYMD is a date in YYYYMMDD format
1362 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1363     $age = -1;
1365     // strip any dashes from the DOB
1366     $dobYMD = preg_replace("/-/", "", $dobYMD);
1367     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1368     
1369     // set the 'now' date values
1370     if ($nowYMD == null) {
1371         $nowDay = date("d");
1372         $nowMonth = date("m");
1373         $nowYear = date("Y");
1374     }
1375     else {
1376         $nowDay = substr($nowYMD,6,2);
1377         $nowMonth = substr($nowYMD,4,2);
1378         $nowYear = substr($nowYMD,0,4);
1379     }
1381     // do the date math
1382     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1383     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1384     $timediff = $nowtime - $dobtime;
1385     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1387     return $age;
1390  * Returns a string to be used to display a patient's age
1391  * 
1392  * @param type $dobYMD
1393  * @param type $asOfYMD
1394  * @return string suitable for displaying patient's age based on preferences
1395  */
1396 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1398     if($GLOBALS['age_display_format']=='1')
1399     {
1400         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1401         if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1402         {
1403             return $ageYMD['ageinYMD'];
1404         }
1405         else
1406         {
1407             return getPatientAge($dobYMD, $asOfYMD);                    
1408         }
1409     }
1410     else
1411     {
1412         return getPatientAge($dobYMD, $asOfYMD);
1413     }
1414     
1416 function dateToDB ($date)
1418     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1419     return $date;
1423 // ----------------------------------------------------------------------------
1425  * DROPDOWN FOR COUNTRIES
1426  * 
1427  * build a dropdown with all countries from geo_country_reference
1428  * 
1429  * @param int $selected - id for selected record
1430  * @param string $name - the name/id for select form
1431  * @return void - just echo the html encoded string
1432  */
1433 function dropdown_countries($selected = 0, $name = 'country_code') {
1434     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1436     $string = "<select name='$name' id='$name'>";
1437     while ( $row = sqlFetchArray($r) ) {
1438         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1439         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1440     }
1442     $string .= '</select>';
1443     echo $string;
1447 // ----------------------------------------------------------------------------
1449  * DROPDOWN FOR YES/NO
1450  * 
1451  * build a dropdown with two options (yes - 1, no - 0)
1452  * 
1453  * @param int $selected - id for selected record
1454  * @param string $name - the name/id for select form
1455  * @return void - just echo the html encoded string 
1456  */
1457 function dropdown_yesno($selected = 0, $name = 'yesno') {
1458     $string = "<select name='$name' id='$name'>";
1460     $selected = (int)$selected;
1461     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1462     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1464     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1465     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1466     $string .= '</select>';
1468     echo $string;
1471 // ----------------------------------------------------------------------------
1473  * DROPDOWN FOR MALE/FEMALE options
1474  * 
1475  * build a dropdown with three options (unselected/male/female)
1476  * 
1477  * @param int $selected - id for selected record
1478  * @param string $name - the name/id for select form
1479  * @return void - just echo the html encoded string
1480  */
1481 function dropdown_sex($selected = 0, $name = 'sex') {
1482     $string = "<select name='$name' id='$name'>";
1484     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1485     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1486     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1488     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1489     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1490     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1491     $string .= '</select>';
1493     echo $string;
1496 // ----------------------------------------------------------------------------
1498  * DROPDOWN FOR MARITAL STATUS
1499  * 
1500  * build a dropdown with marital status
1501  * 
1502  * @param int $selected - id for selected record
1503  * @param string $name - the name/id for select form
1504  * @return void - just echo the html encoded string
1505  */
1506 function dropdown_marital($selected = 0, $name = 'status') {
1507     $string = "<select name='$name' id='$name'>";
1509     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1511     foreach ( $statii as $st ) {
1512         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1513         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1514     }
1516     $string .= '</select>';
1518     echo $string;
1521 // ----------------------------------------------------------------------------
1523  * DROPDOWN FOR PROVIDERS
1524  * 
1525  * build a dropdown with all providers
1526  * 
1527  * @param int $selected - id for selected record
1528  * @param string $name - the name/id for select form
1529  * @return void - just echo the html encoded string
1530  */
1531 function dropdown_providers($selected = 0, $name = 'status') {
1532     $provideri = getProviderInfo();
1534     $string = "<select name='$name' id='$name'>";
1535     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1536     foreach ( $provideri as $s ) {
1537         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1538         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1539     }
1541     $string .= '</select>';
1543     echo $string;
1546 // ----------------------------------------------------------------------------
1548  * DROPDOWN FOR INSURANCE COMPANIES
1549  * 
1550  * build a dropdown with all insurers
1551  * 
1552  * @param int $selected - id for selected record
1553  * @param string $name - the name/id for select form
1554  * @return void - just echo the html encoded string
1555  */
1556 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1557     $insurancei = getInsuranceProviders();
1559     $string = "<select name='$name' id='$name'>";
1560     $string .= '<option value="0">Onbekend</option>';
1561     foreach ( $insurancei as $iid => $iname ) {
1562         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1563         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1564     }
1566     $string .= '</select>';
1568     echo $string;
1572 // ----------------------------------------------------------------------------
1574  * COUNTRY CODE
1575  * 
1576  * return the name or the country code, function of arguments
1577  * 
1578  * @param int $country_code
1579  * @param string $country_name
1580  * @return string | int - name or code
1581  */
1582 function country_code($country_code = 0, $country_name = '') {
1583     $strint = '';
1584     if ( $country_code ) {
1585         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1586     } else {
1587         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1588     }
1590     $db = $GLOBALS['adodb']['db'];
1591     $result = $db->Execute($sql);
1592     if ($result && !$result->EOF) {
1593         $strint = $result->fields['res'];
1594     }
1596     return $strint;
1599 function DBToDate ($date)
1601     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1602     return $date;
1606  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1607  * for the given patient on the given date.
1609  * @param int     The PID of the patient.
1610  * @param string  Date in yyyy-mm-dd format.
1611  * @return array  Array of 0-3 insurance_data rows.
1612  */
1613 function getEffectiveInsurances($patient_id, $encdate) {
1614   $insarr = array();
1615   foreach (array('primary','secondary','tertiary') as $instype) {
1616     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1617       "WHERE pid = ? AND type = ? " .
1618       "AND date <= ? ORDER BY date DESC LIMIT 1",
1619       array($patient_id, $instype, $encdate));
1620     if (empty($tmp['provider'])) break;
1621     $insarr[] = $tmp;
1622   }
1623   return $insarr;
1627  * Get the patient's balance due. Normally this excludes amounts that are out
1628  * to insurance.  If you want to include what insurance owes, set the second
1629  * parameter to true.
1631  * @param int     The PID of the patient.
1632  * @param boolean Indicates if amounts owed by insurance are to be included.
1633  * @return number The balance.
1634  */
1635 function get_patient_balance($pid, $with_insurance=false) {
1636   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1637     $balance = 0;
1638     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1639       "last_level_closed, stmt_count " .
1640       "FROM form_encounter WHERE pid = ?", array($pid));
1641     while ($ferow = sqlFetchArray($feres)) {
1642       $encounter = $ferow['encounter'];
1643       $dos = substr($ferow['date'], 0, 10);
1644       $insarr = getEffectiveInsurances($pid, $dos);
1645       $inscount = count($insarr);
1646       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1647         // It's out to insurance so only the co-pay might be due.
1648         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1649           "pid = ? AND encounter = ? AND " .
1650           "code_type = 'copay' AND activity = 1",
1651           array($pid, $encounter));
1652         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1653           "FROM ar_activity WHERE " .
1654           "pid = ? AND encounter = ? AND payer_type = 0",
1655           array($pid, $encounter));
1656         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1657         if ($ptbal > 0) $balance += $ptbal;
1658       }
1659       else {
1660         // Including insurance or not out to insurance, everything is due.
1661         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1662           "pid = ? AND encounter = ? AND " .
1663           "activity = 1", array($pid, $encounter));
1664         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1665           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1666           "pid = ? AND encounter = ?", array($pid, $encounter));
1667         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1668           "pid = ? AND encounter = ?", array($pid, $encounter));
1669         $balance += $brow['amount'] + $srow['amount']
1670           - $drow['payments'] - $drow['adjustments'];
1671       }
1672     }
1673     return sprintf('%01.2f', $balance);
1674   }
1675   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1676     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1677     $conn = $GLOBALS['adodb']['db'];
1678     $customer_info['id'] = 0;
1679     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1680       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1681       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1682       "im.foreign_table = 'customer'";
1683     $result = $conn->Execute($sql);
1684     if($result && !$result->EOF) {
1685       $customer_info['id'] = $result->fields['foreign_id'];
1686     }
1687     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1688     $ws = new WSWrapper($function);
1689     if(is_numeric($ws->value)) {
1690       return sprintf('%01.2f', $ws->value);
1691     }
1692   }
1693   return '';
1696 // Function to check if patient is deceased.
1697 //  Param:
1698 //    $pid  - patient id
1699 //    $date - date checking if deceased (will default to current date if blank)
1700 //  Return:
1701 //    If deceased, then will return the number of
1702 //      days that patient has been deceased.
1703 //    If not deceased, then will return false.
1704 function is_patient_deceased($pid,$date='') {
1706   // Set date to current if not set
1707   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1709   // Query for deceased status (gets days deceased if patient is deceased)
1710   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1711                       "FROM `patient_data` " .
1712                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1714   if (empty($results)) {
1715     // Patient is alive, so return false
1716     return false;
1717   }
1718   else {
1719     // Patient is dead, so return the number of days patient has been deceased.
1720     //  Don't let it be zero days or else will confuse calls to this function.
1721     if ($results['days_deceased'] === 0) {
1722       $results['days_deceased'] = 1;
1723     }
1724     return $results['days_deceased'];
1725   }