Fixed some GPL script headers that contained text that was not compliant
[openemr.git] / library / patient.inc
blob5407b28935c3f2151314d2834dd8821f60b28f9a
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once("{$GLOBALS['srcdir']}/sql.inc");
8 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
9 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
11 // These are for sports team use:
12 $PLAYER_FITNESSES = array(
13   xl('Full Play'),
14   xl('Full Training'),
15   xl('Restricted Training'),
16   xl('Injured Out'),
17   xl('Rehabilitation'),
18   xl('Illness'),
19   xl('International Duty')
21 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
23 // Hard-coding this array because its values and meanings are fixed by the 837p
24 // standard and we don't want people messing with them.
25 $policy_types = array(
26   ''   => xl('N/A'),
27   '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
28   '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
29   '14' => xl('No-fault Insurance including Auto is Primary'),
30   '15' => xl('Worker`s Compensation'),
31   '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
32   '41' => xl('Black Lung'),
33   '42' => xl('Veteran`s Administration'),
34   '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
35   '47' => xl('Other Liability Insurance is Primary'),
38 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
39     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
40     return sqlQuery($sql, array($pid) );
43 function getLanguages() {
44     $returnval = array('','english');
45     $sql = "select distinct lower(language) as language from patient_data";
46     $rez = sqlStatement($sql);
47     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
48         if (($row["language"] != "english") && ($row["language"] != "")) {
49             array_push($returnval, $row["language"]);
50         }
51     }
52     return $returnval;
55 function getInsuranceProvider($ins_id) {
56     
57     $sql = "select name from insurance_companies where id=?";
58     $row = sqlQuery($sql,array($ins_id));
59     return $row['name'];
60     
63 function getInsuranceProviders() {
64     $returnval = array();
66     if (true) {
67         $sql = "select name, id from insurance_companies order by name, id";
68         $rez = sqlStatement($sql);
69         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
70             $returnval[$row['id']] = $row['name'];
71         }
72     }
74     // Please leave this here. I have a user who wants to see zip codes and PO
75     // box numbers listed along with the insurance company names, as many companies
76     // have different billing addresses for different plans.  -- Rod Roark
77     //
78     else {
79         $sql = "select insurance_companies.name, insurance_companies.id, " .
80           "addresses.zip, addresses.line1 " .
81           "from insurance_companies, addresses " .
82           "where addresses.foreign_id = insurance_companies.id " .
83           "order by insurance_companies.name, addresses.zip";
85         $rez = sqlStatement($sql);
87         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
88             preg_match("/\d+/", $row['line1'], $matches);
89             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
90               "," . $matches[0] . ")";
91         }
92     }
94     return $returnval;
97 function getProviders() {
98     $returnval = array("");
99     $sql = "select fname, lname from users where authorized = 1 and " .
100         "active = 1 and username != ''";
101     $rez = sqlStatement($sql);
102     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
103         if (($row["fname"] != "") && ($row["lname"] != "")) {
104             array_push($returnval, $row["fname"] . " " . $row["lname"]);
105         }
106     }
107     return $returnval;
110 // ----------------------------------------------------------------------------
111 // Get one facility row.  If the ID is not specified, then get either the
112 // "main" (billing) facility, or the default facility of the currently
113 // logged-in user.  This was created to support genFacilityTitle() but
114 // may find additional uses.
116 function getFacility($facid=0) {
118   //create a sql binding array
119   $sqlBindArray = array();
120   
121   if ($facid > 0) {
122     $query = "SELECT * FROM facility WHERE id = ?";
123     array_push($sqlBindArray,$facid);
124   }
125   else if ($facid == 0) {
126     $query = "SELECT * FROM facility ORDER BY " .
127       "billing_location DESC, service_location, id LIMIT 1";
128   }
129   else {
130     $query = "SELECT facility.* FROM users, facility WHERE " .
131       "users.id = ? AND " .
132       "facility.id = users.facility_id";
133     array_push($sqlBindArray,$_SESSION['authUserID']);
134   }
135   return sqlQuery($query,$sqlBindArray);
138 // Generate a report title including report name and facility name, address
139 // and phone.
141 function genFacilityTitle($repname='', $facid=0) {
142   $s = '';
143   $s .= "<table class='ftitletable'>\n";
144   $s .= " <tr>\n";
145   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
146   $s .= "  <td class='ftitlecell2'>\n";
147   $r = getFacility($facid);
148   if (!empty($r)) {
149     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
150     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
151     if ($r['city'] || $r['state'] || $r['postal_code']) {
152       $s .= "<br />";
153       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
154       if ($r['state']) {
155         if ($r['city']) $s .= ", \n";
156         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
157       }
158       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
159       $s .= "\n";
160     }
161     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
162     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
163   }
164   $s .= "  </td>\n";
165   $s .= " </tr>\n";
166   $s .= "</table>\n";
167   return $s;
171 GET FACILITIES
173 returns all facilities or just the id for the first one
174 (FACILITY FILTERING (lemonsoftware))
176 @param string - if 'first' return first facility ordered by id
177 @return array | int for 'first' case
179 function getFacilities($first = '') {
180     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
181     $ret = array();
182     while ( $row = sqlFetchArray($r) ) {
183        $ret[] = $row;
186         if ( $first == 'first') {
187             return $ret[0]['id'];
188         } else {
189             return $ret;
190         }
194 GET SERVICE FACILITIES
196 returns all service_location facilities or just the id for the first one
197 (FACILITY FILTERING (CHEMED))
199 @param string - if 'first' return first facility ordered by id
200 @return array | int for 'first' case
202 function getServiceFacilities($first = '') {
203     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
204     $ret = array();
205     while ( $row = sqlFetchArray($r) ) {
206        $ret[] = $row;
209         if ( $first == 'first') {
210             return $ret[0]['id'];
211         } else {
212             return $ret;
213         }
216 //(CHEMED) facility filter
217 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
218     $param1 = "";
219     if ($providers_only === 'any') {
220       $param1 = " AND authorized = 1 AND active = 1 ";
221     }
222     else if ($providers_only) {
223       $param1 = " AND authorized = 1 AND calendar = 1 ";
224     }
226     //--------------------------------
227     //(CHEMED) facility filter
228     $param2 = "";
229     if ($facility) {
230       if ($GLOBALS['restrict_user_facility']) {
231         $param2 = " AND (facility_id = $facility 
232           OR  $facility IN
233                 (select facility_id 
234                 from users_facility
235                 where tablename = 'users'
236                 and table_id = id)
237                 )
238           ";
239       }
240       else {
241         $param2 = " AND facility_id = $facility ";
242       }
243     }
244     //--------------------------------
246     $command = "=";
247     if ($providerID == "%") {
248         $command = "like";
249     }
250     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
251         "from users where username != '' and active = 1 and id $command '" .
252         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
253     // sort by last name -- JRM June 2008
254     $query .= " ORDER BY lname, fname ";
255     $rez = sqlStatement($query);
256     for($iter=0; $row=sqlFetchArray($rez); $iter++)
257         $returnval[$iter]=$row;
259     //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
260     //accessible from $resultval['key']
262     if($iter==1) {
263         $akeys = array_keys($returnval[0]);
264         foreach($akeys as $key) {
265             $returnval[0][$key] = $returnval[0][$key];
266         }
267     }
268     return $returnval;
271 //same as above but does not reduce if only 1 row returned
272 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
273     $param1 = "";
274     if ($providers_only) {
275         $param1 = "AND authorized=1";
276     }
277     $command = "=";
278     if ($providerID == "%") {
279         $command = "like";
280     }
281     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
282         "from users where active = 1 and username != '' and id $command '" .
283         mysql_real_escape_string($providerID) . "' " . $param1;
285     $rez = sqlStatement($query);
286     for($iter=0; $row=sqlFetchArray($rez); $iter++)
287         $returnval[$iter]=$row;
289     return $returnval;
292 function getProviderName($providerID) {
293     $pi = getProviderInfo($providerID, 'any');
294     if (strlen($pi[0]["lname"]) > 0) {
295         return $pi[0]['fname'] . " " . $pi[0]['lname'];
296     }
297     return "";
300 function getProviderId($providerName) {
301     $query = "select id from users where username = ?";
302     $rez = sqlStatement($query, array($providerName) );
303     for($iter=0; $row=sqlFetchArray($rez); $iter++)
304         $returnval[$iter]=$row;
305     return $returnval;
308 function getEthnoRacials() {
309     $returnval = array("");
310     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
311     $rez = sqlStatement($sql);
312     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
313         if (($row["ethnoracial"] != "")) {
314             array_push($returnval, $row["ethnoracial"]);
315         }
316     }
317     return $returnval;
320 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
323     if ($dateStart && $dateEnd) {
324         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
325     }
326     else if ($dateStart && !$dateEnd) {
327         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
328     }
329     else if (!$dateStart && $dateEnd) {
330         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
331     }
332     else {
333         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
334     }
336     return $res;
339 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
340 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
342   $sql = "select $given from insurance_data as insd " .
343     "left join insurance_companies as ic on ic.id = insd.provider " .
344     "where pid = ? and type = ? order by date DESC limit 1";
345   return sqlQuery($sql, array($pid, $type) );
348 function getInsuranceDataByDate($pid, $date, $type,
349   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
350 { // this must take the date in the following manner: YYYY-MM-DD
351   // this function recalls the insurance value that was most recently enterred from the
352   // given date. it will call up most recent records up to and on the date given,
353   // but not records enterred after the given date
354   $sql = "select $given from insurance_data as insd " .
355     "left join insurance_companies as ic on ic.id = provider " .
356     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
357     "type=? order by date DESC limit 1";
358   return sqlQuery($sql, array($pid,$date,$type) );
361 function getEmployerData($pid, $given = "*")
363     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
364     return sqlQuery($sql, array($pid) );
367 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
368   // When the limit is exceeded, find out what the unlimited count would be.
369   $GLOBALS['PATIENT_INC_COUNT'] = $count;
370   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
371   if ($limit != "all") {
372     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
373     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
374   }
377 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")
379     // Allow the last name to be followed by a comma and some part of a first name.
380     // New behavior for searches:
381     // Allows comma alone followed by some part of a first name
382     // If the first letter of either name is capital, searches for name starting
383     // with given substring (the expected behavior).  If it is lower case, it
384     // it searches for the substring anywhere in the name.  This applies to either
385     // last name or first name or both.  The arbitrary limit of 100 results is set
386     // in the sql query below. --Mark Leeds
387     $lname = trim($lname);
388     $fname = '';
389      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
390          $lname = trim($matches[1]);
391          $fname = trim($matches[2]);
392     }
393     $search_for_pieces1 = '';
394     $search_for_pieces2 = '';
395     if ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
396     if ((strlen($fname) < 1)|| ($fname{0} != strtoupper($fname{0}))) {$search_for_pieces2 = '%';}
398     $sqlBindArray = array();
399     $where = "lname LIKE ? AND fname LIKE ? ";
400     array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
401         if (!empty($GLOBALS['pt_restrict_field'])) {
402                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
403                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
404                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
405                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
406                         array_push($sqlBindArray, $_SESSION{"authUser"});
407                 }
408         }
410     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
411     if ($limit != "all") $sql .= " LIMIT $start, $limit";
413     $rez = sqlStatement($sql, $sqlBindArray);
415     $returnval=array();
416     for($iter=0; $row=sqlFetchArray($rez); $iter++)
417         $returnval[$iter] = $row;
419     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
420     return $returnval;
423 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")
426     $sqlBindArray = array();
427     $where = "pubpid LIKE ? ";
428     array_push($sqlBindArray, $pid."%");
429         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
430                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
431                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
432                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
433                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
434                         array_push($sqlBindArray, $_SESSION{"authUser"});
435                 }
436         }
438     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
439     if ($limit != "all") $sql .= " limit $start, $limit";
440     $rez = sqlStatement($sql, $sqlBindArray);
441     for($iter=0; $row=sqlFetchArray($rez); $iter++)
442         $returnval[$iter]=$row;
444     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
445     return $returnval;
448 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")
450   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
452   $sqlBindArray = array();
453   $where = "";
454   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
455     if ( $iter > 0 ) {
456       $where .= " or ";
457     }
458     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
459     array_push($sqlBindArray, "%".$searchTerm."%");
460   }
462   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
463   if ($limit != "all") $sql .= " limit $start, $limit";
464   $rez = sqlStatement($sql, $sqlBindArray);
465   for($iter=0; $row=sqlFetchArray($rez); $iter++)
466     $returnval[$iter]=$row;
467   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
468   return $returnval;
471 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
472   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
473   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
475         $layoutCols = split( '~', $searchFields );
476   $sqlBindArray = array();
477   $where = "";
478   $i = 0;
479   foreach ($layoutCols as $val) {
480     if (empty($val)) continue;
481                 if ( $i > 0 ) {
482                    $where .= " or ";
483                 }
484     if ($val == 'pid') {
485                 $where .= " ".add_escape_custom($val)." = ? ";
486                 array_push($sqlBindArray, $searchTerm);
487     }
488     else {
489                 $where .= " ".add_escape_custom($val)." like ? ";
490                 array_push($sqlBindArray, $searchTerm."%");
491     }
492                 $i++;
493         }
495   // If no search terms, ensure valid syntax.
496   if ($i == 0) $where = "1 = 1";
498   // If a non-empty service code was given, then restrict to patients who
499   // have been provided that service.  Since the code is used in a LIKE
500   // clause, % and _ wildcards are supported.
501   if ($search_service_code) {
502     $where = "( $where ) AND " .
503       "( SELECT COUNT(*) FROM billing AS b WHERE " .
504       "b.pid = patient_data.pid AND " .
505       "b.activity = 1 AND " .
506       "b.code_type != 'COPAY' AND " .
507       "b.code LIKE ? " .
508       ") > 0";
509     array_push($sqlBindArray, $search_service_code);
510   }
512   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
513   if ($limit != "all") $sql .= " limit $start, $limit";
514   $rez = sqlStatement($sql, $sqlBindArray);
515   for($iter=0; $row=sqlFetchArray($rez); $iter++)
516       $returnval[$iter]=$row;
517   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
518   return $returnval;
521 // return a collection of Patient PIDs
522 // new arg style by JRM March 2008
523 // 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")
524 function getPatientPID($args)
526     $pid = "%";
527     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
528     $orderby = "lname ASC, fname ASC";
529     $limit="all";
530     $start="0";
532     // alter default values if defined in the passed in args
533     if (isset($args['pid'])) { $pid = $args['pid']; }
534     if (isset($args['given'])) { $given = $args['given']; }
535     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
536     if (isset($args['limit'])) { $limit = $args['limit']; }
537     if (isset($args['start'])) { $start = $args['start']; }
539     $command = "=";
540     if ($pid == -1) $pid = "%";
541     elseif (empty($pid)) $pid = "NULL";
543     if (strstr($pid,"%")) $command = "like";
545     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
546     if ($limit != "all") $sql .= " limit $start, $limit";
548     $rez = sqlStatement($sql);
549     for($iter=0; $row=sqlFetchArray($rez); $iter++)
550         $returnval[$iter]=$row;
552     return $returnval;
555 /* return a patient's name in the format LAST, FIRST */
556 function getPatientName($pid) {
557     if (empty($pid)) return "";
558     $patientData = getPatientPID(array("pid"=>$pid));
559     if (empty($patientData[0]['lname'])) return "";
560     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
561     return $patientName;
564 /* find patient data by DOB */
565 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
567     $DOB = fixDate($DOB, $DOB);
568     $sqlBindArray = array();
569     $where = "DOB like ? ";
570     array_push($sqlBindArray, $DOB."%");
571         if (!empty($GLOBALS['pt_restrict_field'])) {
572                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
573                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
574                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
575                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
576                         array_push($sqlBindArray, $_SESSION{"authUser"});
577                 }
578         }
580     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
582     if ($limit != "all") $sql .= " LIMIT $start, $limit";
584     $rez = sqlStatement($sql, $sqlBindArray);
585     for($iter=0; $row=sqlFetchArray($rez); $iter++)
586         $returnval[$iter]=$row;
588     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
589     return $returnval;
592 /* find patient data by SSN */
593 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
595     $sqlBindArray = array();
596     $where = "ss LIKE ?";
597     array_push($sqlBindArray, $ss."%");
598     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
599     if ($limit != "all") $sql .= " LIMIT $start, $limit";
601     $rez = sqlStatement($sql, $sqlBindArray);
602     for($iter=0; $row=sqlFetchArray($rez); $iter++)
603         $returnval[$iter]=$row;
605     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
606     return $returnval;
609 //(CHEMED) Search by phone number
610 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
612     $phone = ereg_replace( "[[:punct:]]","", $phone );
613     $sqlBindArray = array();
614     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
615     array_push($sqlBindArray, $phone);
616     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
617     if ($limit != "all") $sql .= " LIMIT $start, $limit";
619     $rez = sqlStatement($sql, $sqlBindArray);
620     for($iter=0; $row=sqlFetchArray($rez); $iter++)
621         $returnval[$iter]=$row;
623     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
624     return $returnval;
627 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
629     $sql="select $given from patient_data order by $orderby";
631     if ($limit != "all")
632         $sql .= " limit $start, $limit";
634     $rez = sqlStatement($sql);
635     for($iter=0; $row=sqlFetchArray($rez); $iter++)
636         $returnval[$iter]=$row;
638     return $returnval;
641 //----------------------input functions
642 function newPatientData(    $db_id="",
643                 $title = "",
644                 $fname = "",
645                 $lname = "",
646                 $mname = "",
647                 $sex = "",
648                 $DOB = "",
649                 $street = "",
650                 $postal_code = "",
651                 $city = "",
652                 $state = "",
653                 $country_code = "",
654                 $ss = "",
655                 $occupation = "",
656                 $phone_home = "",
657                 $phone_biz = "",
658                 $phone_contact = "",
659                 $status = "",
660                 $contact_relationship = "",
661                 $referrer = "",
662                 $referrerID = "",
663                 $email = "",
664                 $language = "",
665                 $ethnoracial = "",
666                 $interpretter = "",
667                 $migrantseasonal = "",
668                 $family_size = "",
669                 $monthly_income = "",
670                 $homeless = "",
671                 $financial_review = "",
672                 $pubpid = "",
673                 $pid = "MAX(pid)+1",
674                 $providerID = "",
675                 $genericname1 = "",
676                 $genericval1 = "",
677                 $genericname2 = "",
678                 $genericval2 = "",
679                 $phone_cell = "",
680                 $hipaa_mail = "",
681                 $hipaa_voice = "",
682                 $squad = 0,
683                 $pharmacy_id = 0,
684                 $drivers_license = "",
685                 $hipaa_notice = "",
686                 $hipaa_message = "",
687                 $regdate = ""
688             )
690     $DOB = fixDate($DOB);
691     $regdate = fixDate($regdate);
693     $fitness = 0;
694     $referral_source = '';
695     if ($pid) {
696         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
697         // Check for brain damage:
698         if ($db_id != $rez['id']) {
699             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
700               $rez['id'] . "' to '$db_id' for pid '$pid'";
701             die($errmsg);
702         }
703         $fitness = $rez['fitness'];
704         $referral_source = $rez['referral_source'];
705     }
707     // Get the default price level.
708     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
709       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
710     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
712     $query = ("replace into patient_data set
713         id='$db_id',
714         title='$title',
715         fname='$fname',
716         lname='$lname',
717         mname='$mname',
718         sex='$sex',
719         DOB='$DOB',
720         street='$street',
721         postal_code='$postal_code',
722         city='$city',
723         state='$state',
724         country_code='$country_code',
725         drivers_license='$drivers_license',
726         ss='$ss',
727         occupation='$occupation',
728         phone_home='$phone_home',
729         phone_biz='$phone_biz',
730         phone_contact='$phone_contact',
731         status='$status',
732         contact_relationship='$contact_relationship',
733         referrer='$referrer',
734         referrerID='$referrerID',
735         email='$email',
736         language='$language',
737         ethnoracial='$ethnoracial',
738         interpretter='$interpretter',
739         migrantseasonal='$migrantseasonal',
740         family_size='$family_size',
741         monthly_income='$monthly_income',
742         homeless='$homeless',
743         financial_review='$financial_review',
744         pubpid='$pubpid',
745         pid = $pid,
746         providerID = '$providerID',
747         genericname1 = '$genericname1',
748         genericval1 = '$genericval1',
749         genericname2 = '$genericname2',
750         genericval2 = '$genericval2',
751         phone_cell = '$phone_cell',
752         pharmacy_id = '$pharmacy_id',
753         hipaa_mail = '$hipaa_mail',
754         hipaa_voice = '$hipaa_voice',
755         hipaa_notice = '$hipaa_notice',
756         hipaa_message = '$hipaa_message',
757         squad = '$squad',
758         fitness='$fitness',
759         referral_source='$referral_source',
760         regdate='$regdate',
761         pricelevel='$pricelevel',
762         date=NOW()");
764     $id = sqlInsert($query);
766     if ( !$db_id ) {
767       // find the last inserted id for new patient case
768       $db_id = mysql_insert_id();
769     }
771     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
773     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
774                 $phone_biz,$phone_cell,$email,$pid);
776     return $foo['pid'];
779 // Supported input date formats are:
780 //   mm/dd/yyyy
781 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
782 //   yyyy/mm/dd
783 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
785 function fixDate($date, $default="0000-00-00") {
786     $fixed_date = $default;
787     $date = trim($date);
788     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
789         $dmy = preg_split("'[/.-]'", $date);
790         if ($dmy[0] > 99) {
791             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
792         } else {
793             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
794               if ($dmy[2] < 1000) $dmy[2] += 1900;
795               if ($dmy[2] < 1910) $dmy[2] += 100;
796             }
797             // phone_country_code indicates format of ambiguous input dates.
798             if ($GLOBALS['phone_country_code'] == 1)
799               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
800             else
801               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
802         }
803     }
805     return $fixed_date;
808 function pdValueOrNull($key, $value) {
809   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
810     substr($key, 0, 8) == 'userdate') &&
811     (empty($value) || $value == '0000-00-00'))
812   {
813     return "NULL";
814   }
815   else {
816     return "'$value'";
817   }
820 // Create or update patient data from an array.
822 function updatePatientData($pid, $new, $create=false)
824   /*******************************************************************
825     $real = getPatientData($pid);
826     $new['DOB'] = fixDate($new['DOB']);
827     while(list($key, $value) = each ($new))
828         $real[$key] = $value;
829     $real['date'] = "'+NOW()+'";
830     $real['id'] = "";
831     $sql = "insert into patient_data set ";
832     while(list($key, $value) = each($real))
833         $sql .= $key." = '$value', ";
834     $sql = substr($sql, 0, -2);
835     return sqlInsert($sql);
836   *******************************************************************/
838   // The above was broken, though seems intent to insert a new patient_data
839   // row for each update.  A good idea, but nothing is doing that yet so
840   // the code below does not yet attempt it.
842   $new['DOB'] = fixDate($new['DOB']);
844   if ($create) {
845     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
846     foreach ($new as $key => $value) {
847       if ($key == 'id') continue;
848       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
849     }
850     $db_id = sqlInsert($sql);
851   }
852   else {
853     $db_id = $new['id'];
854     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
855     // Check for brain damage:
856     if ($pid != $rez['pid']) {
857       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
858         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
859       die($errmsg);
860     }
861     $sql = "UPDATE patient_data SET date = NOW()";
862     foreach ($new as $key => $value) {
863       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
864     }
865     $sql .= " WHERE id = '$db_id'";
866     sqlStatement($sql);
867   }
869   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
870   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
871     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
872     $rez['phone_cell'],$rez['email'],$rez['pid']);
874   return $db_id;
877 function newEmployerData(    $pid,
878                 $name = "",
879                 $street = "",
880                 $postal_code = "",
881                 $city = "",
882                 $state = "",
883                 $country = ""
884             )
886     return sqlInsert("insert into employer_data set
887         name='$name',
888         street='$street',
889         postal_code='$postal_code',
890         city='$city',
891         state='$state',
892         country='$country',
893         pid='$pid',
894         date=NOW()
895         ");
898 // Create or update employer data from an array.
900 function updateEmployerData($pid, $new, $create=false)
902   $colnames = array('name','street','city','state','postal_code','country');
904   if ($create) {
905     $set .= "pid = '$pid', date = NOW()";
906     foreach ($colnames as $key) {
907       $value = isset($new[$key]) ? $new[$key] : '';
908       $set .= ", `$key` = '$value'";
909     }
910     return sqlInsert("INSERT INTO employer_data SET $set");
911   }
912   else {
913     $set = '';
914     $old = getEmployerData($pid);
915     $modified = false;
916     foreach ($colnames as $key) {
917       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
918       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
919         $value = $new[$key];
920         $modified = true;
921       }
922       $set .= "`$key` = '$value', ";
923     }
924     if ($modified) {
925       $set .= "pid = '$pid', date = NOW()";
926       return sqlInsert("INSERT INTO employer_data SET $set");
927     }
928     return $old['id'];
929   }
932 // This updates or adds the given insurance data info, while retaining any
933 // previously added insurance_data rows that should be preserved.
934 // This does not directly support the maintenance of non-current insurance.
936 function newInsuranceData(
937   $pid,
938   $type = "",
939   $provider = "",
940   $policy_number = "",
941   $group_number = "",
942   $plan_name = "",
943   $subscriber_lname = "",
944   $subscriber_mname = "",
945   $subscriber_fname = "",
946   $subscriber_relationship = "",
947   $subscriber_ss = "",
948   $subscriber_DOB = "",
949   $subscriber_street = "",
950   $subscriber_postal_code = "",
951   $subscriber_city = "",
952   $subscriber_state = "",
953   $subscriber_country = "",
954   $subscriber_phone = "",
955   $subscriber_employer = "",
956   $subscriber_employer_street = "",
957   $subscriber_employer_city = "",
958   $subscriber_employer_postal_code = "",
959   $subscriber_employer_state = "",
960   $subscriber_employer_country = "",
961   $copay = "",
962   $subscriber_sex = "",
963   $effective_date = "0000-00-00",
964   $accept_assignment = "TRUE",
965   $policy_type = "")
967   if (strlen($type) <= 0) return FALSE;
969   // If a bad date was passed, err on the side of caution.
970   $effective_date = fixDate($effective_date, date('Y-m-d'));
972   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
973     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
974   $idrow = sqlFetchArray($idres);
976   // Replace the most recent entry in any of the following cases:
977   // * Its effective date is >= this effective date.
978   // * It is the first entry and it has no (insurance) provider.
979   // * There is no encounter that is earlier than the new effective date but
980   //   on or after the old effective date.
981   // Otherwise insert a new entry.
983   $replace = false;
984   if ($idrow) {
985     if (strcmp($idrow['date'], $effective_date) > 0) {
986       $replace = true;
987     }
988     else {
989       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
990         $replace = true;
991       }
992       else {
993         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
994           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
995           "date >= '" . $idrow['date'] . " 00:00:00'");
996         if ($ferow['count'] == 0) $replace = true;
997       }
998     }
999   }
1001   if ($replace) {
1003     // TBD: This is a bit dangerous in that a typo in entering the effective
1004     // date can wipe out previous insurance history.  So we want some data
1005     // entry validation somewhere.
1006     sqlStatement("DELETE FROM insurance_data WHERE " .
1007       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1008       "id != " . $idrow['id']);
1010     $data = array();
1011     $data['type'] = $type;
1012     $data['provider'] = $provider;
1013     $data['policy_number'] = $policy_number;
1014     $data['group_number'] = $group_number;
1015     $data['plan_name'] = $plan_name;
1016     $data['subscriber_lname'] = $subscriber_lname;
1017     $data['subscriber_mname'] = $subscriber_mname;
1018     $data['subscriber_fname'] = $subscriber_fname;
1019     $data['subscriber_relationship'] = $subscriber_relationship;
1020     $data['subscriber_ss'] = $subscriber_ss;
1021     $data['subscriber_DOB'] = $subscriber_DOB;
1022     $data['subscriber_street'] = $subscriber_street;
1023     $data['subscriber_postal_code'] = $subscriber_postal_code;
1024     $data['subscriber_city'] = $subscriber_city;
1025     $data['subscriber_state'] = $subscriber_state;
1026     $data['subscriber_country'] = $subscriber_country;
1027     $data['subscriber_phone'] = $subscriber_phone;
1028     $data['subscriber_employer'] = $subscriber_employer;
1029     $data['subscriber_employer_city'] = $subscriber_employer_city;
1030     $data['subscriber_employer_street'] = $subscriber_employer_street;
1031     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1032     $data['subscriber_employer_state'] = $subscriber_employer_state;
1033     $data['subscriber_employer_country'] = $subscriber_employer_country;
1034     $data['copay'] = $copay;
1035     $data['subscriber_sex'] = $subscriber_sex;
1036     $data['pid'] = $pid;
1037     $data['date'] = $effective_date;
1038     $data['accept_assignment'] = $accept_assignment;
1039     $data['policy_type'] = $policy_type;
1040     updateInsuranceData($idrow['id'], $data);
1041     return $idrow['id'];
1042   }
1043   else {
1044     return sqlInsert("INSERT INTO insurance_data SET
1045       type = '$type',
1046       provider = '$provider',
1047       policy_number = '$policy_number',
1048       group_number = '$group_number',
1049       plan_name = '$plan_name',
1050       subscriber_lname = '$subscriber_lname',
1051       subscriber_mname = '$subscriber_mname',
1052       subscriber_fname = '$subscriber_fname',
1053       subscriber_relationship = '$subscriber_relationship',
1054       subscriber_ss = '$subscriber_ss',
1055       subscriber_DOB = '$subscriber_DOB',
1056       subscriber_street = '$subscriber_street',
1057       subscriber_postal_code = '$subscriber_postal_code',
1058       subscriber_city = '$subscriber_city',
1059       subscriber_state = '$subscriber_state',
1060       subscriber_country = '$subscriber_country',
1061       subscriber_phone = '$subscriber_phone',
1062       subscriber_employer = '$subscriber_employer',
1063       subscriber_employer_city = '$subscriber_employer_city',
1064       subscriber_employer_street = '$subscriber_employer_street',
1065       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1066       subscriber_employer_state = '$subscriber_employer_state',
1067       subscriber_employer_country = '$subscriber_employer_country',
1068       copay = '$copay',
1069       subscriber_sex = '$subscriber_sex',
1070       pid = '$pid',
1071       date = '$effective_date',
1072       accept_assignment = '$accept_assignment',
1073       policy_type = '$policy_type'
1074     ");
1075   }
1078 // This is used internally only.
1079 function updateInsuranceData($id, $new)
1081   $fields = sqlListFields("insurance_data");
1082   $use = array();
1084   while(list($key, $value) = each ($new)) {
1085     if (in_array($key, $fields)) {
1086       $use[$key] = $value;
1087     }
1088   }
1090   $sql = "UPDATE insurance_data SET ";
1091   while(list($key, $value) = each($use))
1092     $sql .= "`$key` = '$value', ";
1093   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1095   sqlStatement($sql);
1098 function newHistoryData($pid, $new=false) {
1099   $arraySqlBind = array();
1100   $sql = "insert into history_data set pid = ?, date = NOW()";
1101   array_push($arraySqlBind,$pid);
1102   if ($new) {
1103     while(list($key, $value) = each($new)) {
1104       array_push($arraySqlBind,$value);
1105       $sql .= ", `$key` = ?";
1106     }
1107   }
1108   return sqlInsert($sql, $arraySqlBind );
1111 function updateHistoryData($pid,$new)
1113         $real = getHistoryData($pid);
1114         while(list($key, $value) = each ($new))
1115                 $real[$key] = $value;
1116         $real['id'] = "";
1117         // need to unset date, so can reset it below
1118         unset($real['date']);
1120         $arraySqlBind = array();
1121         $sql = "insert into history_data set `date` = NOW(), ";
1122         while(list($key, $value) = each($real)) {
1123                 array_push($arraySqlBind,$value);
1124                 $sql .= "`$key` = ?, ";
1125         }
1126         $sql = substr($sql, 0, -2);
1128         return sqlInsert($sql, $arraySqlBind );
1131 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1132                 $phone_biz,$phone_cell,$email,$pid="")
1134     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1135     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1137     $db = $GLOBALS['adodb']['db'];
1138     $customer_info = array();
1140     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1141     $result = $db->Execute($sql);
1142     if ($result && !$result->EOF) {
1143         $customer_info['foreign_update'] = true;
1144         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1145         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1146     }
1148     ///xml rpc code to connect to accounting package and add user to it
1149     $customer_info['firstname'] = $fname;
1150     $customer_info['lastname'] = $lname;
1151     $customer_info['address'] = $street;
1152     $customer_info['suburb'] = $city;
1153     $customer_info['state'] = $state;
1154     $customer_info['postcode'] = $postal_code;
1156     //ezybiz wants state as a code rather than abbreviation
1157     $customer_info['geo_zone_id'] = "";
1158     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1159     $db = $GLOBALS['adodb']['db'];
1160     $result = $db->Execute($sql);
1161     if ($result && !$result->EOF) {
1162         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1163     }
1165     //ezybiz wants country as a code rather than abbreviation
1166     $customer_info['geo_country_id'] = "";
1167     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1168     $db = $GLOBALS['adodb']['db'];
1169     $result = $db->Execute($sql);
1170     if ($result && !$result->EOF) {
1171         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1172     }
1174     $customer_info['phone1'] = $phone_home;
1175     $customer_info['phone1comment'] = "Home Phone";
1176     $customer_info['phone2'] = $phone_biz;
1177     $customer_info['phone2comment'] = "Business Phone";
1178     $customer_info['phone3'] = $phone_cell;
1179     $customer_info['phone3comment'] = "Cell Phone";
1180     $customer_info['email'] = $email;
1181     $customer_info['customernumber'] = $pid;
1183     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1184     $ws = new WSWrapper($function);
1186     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1187     if (is_numeric($ws->value)) {
1188         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1189         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1190     }
1193 // Returns Age 
1194 //   in months if < 2 years old
1195 //   in years  if > 2 years old
1196 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1197 // (optional) nowYMD is a date in YYYYMMDD format
1198 function getPatientAge($dobYMD, $nowYMD=null)
1200     // strip any dashes from the DOB
1201     $dobYMD = preg_replace("/-/", "", $dobYMD);
1202     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1203     
1204     // set the 'now' date values
1205     if ($nowYMD == null) {
1206         $nowDay = date("d");
1207         $nowMonth = date("m");
1208         $nowYear = date("Y");
1209     }
1210     else {
1211         $nowDay = substr($nowYMD,6,2);
1212         $nowMonth = substr($nowYMD,4,2);
1213         $nowYear = substr($nowYMD,0,4);
1214     }
1216     $dayDiff = $nowDay - $dobDay;
1217     $monthDiff = $nowMonth - $dobMonth;
1218     $yearDiff = $nowYear - $dobYear;
1220     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1222     if ( $ageInMonths > 24 ) {
1223         $age = $yearDiff;
1224         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1225         else if ($monthDiff < 0) { $age -= 1; }
1226     }
1227     else  {
1228         $age = "$ageInMonths month"; 
1229     }
1231     return $age;
1235 // Returns Age in days
1236 //   in months if < 2 years old
1237 //   in years  if > 2 years old
1238 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1239 // (optional) nowYMD is a date in YYYYMMDD format
1240 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1241     $age = -1;
1243     // strip any dashes from the DOB
1244     $dobYMD = preg_replace("/-/", "", $dobYMD);
1245     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1246     
1247     // set the 'now' date values
1248     if ($nowYMD == null) {
1249         $nowDay = date("d");
1250         $nowMonth = date("m");
1251         $nowYear = date("Y");
1252     }
1253     else {
1254         $nowDay = substr($nowYMD,6,2);
1255         $nowMonth = substr($nowYMD,4,2);
1256         $nowYear = substr($nowYMD,0,4);
1257     }
1259     // do the date math
1260     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1261     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1262     $timediff = $nowtime - $dobtime;
1263     $age = $timediff / 86400;
1265     return $age;
1268 function dateToDB ($date)
1270     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1271     return $date;
1275 // ----------------------------------------------------------------------------
1277  * DROPDOWN FOR COUNTRIES
1278  * 
1279  * build a dropdown with all countries from geo_country_reference
1280  * 
1281  * @param int $selected - id for selected record
1282  * @param string $name - the name/id for select form
1283  * @return void - just echo the html encoded string
1284  */
1285 function dropdown_countries($selected = 0, $name = 'country_code') {
1286     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1288     $string = "<select name='$name' id='$name'>";
1289     while ( $row = sqlFetchArray($r) ) {
1290         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1291         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1292     }
1294     $string .= '</select>';
1295     echo $string;
1299 // ----------------------------------------------------------------------------
1301  * DROPDOWN FOR YES/NO
1302  * 
1303  * build a dropdown with two options (yes - 1, no - 0)
1304  * 
1305  * @param int $selected - id for selected record
1306  * @param string $name - the name/id for select form
1307  * @return void - just echo the html encoded string 
1308  */
1309 function dropdown_yesno($selected = 0, $name = 'yesno') {
1310     $string = "<select name='$name' id='$name'>";
1312     $selected = (int)$selected;
1313     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1314     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1316     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1317     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1318     $string .= '</select>';
1320     echo $string;
1323 // ----------------------------------------------------------------------------
1325  * DROPDOWN FOR MALE/FEMALE options
1326  * 
1327  * build a dropdown with three options (unselected/male/female)
1328  * 
1329  * @param int $selected - id for selected record
1330  * @param string $name - the name/id for select form
1331  * @return void - just echo the html encoded string
1332  */
1333 function dropdown_sex($selected = 0, $name = 'sex') {
1334     $string = "<select name='$name' id='$name'>";
1336     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1337     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1338     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1340     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1341     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1342     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1343     $string .= '</select>';
1345     echo $string;
1348 // ----------------------------------------------------------------------------
1350  * DROPDOWN FOR MARITAL STATUS
1351  * 
1352  * build a dropdown with marital status
1353  * 
1354  * @param int $selected - id for selected record
1355  * @param string $name - the name/id for select form
1356  * @return void - just echo the html encoded string
1357  */
1358 function dropdown_marital($selected = 0, $name = 'status') {
1359     $string = "<select name='$name' id='$name'>";
1361     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1363     foreach ( $statii as $st ) {
1364         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1365         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1366     }
1368     $string .= '</select>';
1370     echo $string;
1373 // ----------------------------------------------------------------------------
1375  * DROPDOWN FOR PROVIDERS
1376  * 
1377  * build a dropdown with all providers
1378  * 
1379  * @param int $selected - id for selected record
1380  * @param string $name - the name/id for select form
1381  * @return void - just echo the html encoded string
1382  */
1383 function dropdown_providers($selected = 0, $name = 'status') {
1384     $provideri = getProviderInfo();
1386     $string = "<select name='$name' id='$name'>";
1387     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1388     foreach ( $provideri as $s ) {
1389         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1390         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1391     }
1393     $string .= '</select>';
1395     echo $string;
1398 // ----------------------------------------------------------------------------
1400  * DROPDOWN FOR INSURANCE COMPANIES
1401  * 
1402  * build a dropdown with all insurers
1403  * 
1404  * @param int $selected - id for selected record
1405  * @param string $name - the name/id for select form
1406  * @return void - just echo the html encoded string
1407  */
1408 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1409     $insurancei = getInsuranceProviders();
1411     $string = "<select name='$name' id='$name'>";
1412     $string .= '<option value="0">Onbekend</option>';
1413     foreach ( $insurancei as $iid => $iname ) {
1414         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1415         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1416     }
1418     $string .= '</select>';
1420     echo $string;
1424 // ----------------------------------------------------------------------------
1426  * COUNTRY CODE
1427  * 
1428  * return the name or the country code, function of arguments
1429  * 
1430  * @param int $country_code
1431  * @param string $country_name
1432  * @return string | int - name or code
1433  */
1434 function country_code($country_code = 0, $country_name = '') {
1435     $strint = '';
1436     if ( $country_code ) {
1437         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1438     } else {
1439         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1440     }
1442     $db = $GLOBALS['adodb']['db'];
1443     $result = $db->Execute($sql);
1444     if ($result && !$result->EOF) {
1445         $strint = $result->fields['res'];
1446     }
1448     return $strint;
1451 function DBToDate ($date)
1453     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1454     return $date;
1457 function get_patient_balance($pid) {
1458   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1459     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1460       "pid = ? AND activity = 1", array($pid) );
1461     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1462       "pid = ?", array($pid) );
1463     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1464       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1465       "pid = ?", array($pid) );
1466     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1467       - $drow['payments'] - $drow['adjustments']);
1468   }
1469   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1470     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1471     $conn = $GLOBALS['adodb']['db'];
1472     $customer_info['id'] = 0;
1473     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1474       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1475       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1476       "im.foreign_table = 'customer'";
1477     $result = $conn->Execute($sql);
1478     if($result && !$result->EOF) {
1479       $customer_info['id'] = $result->fields['foreign_id'];
1480     }
1481     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1482     $ws = new WSWrapper($function);
1483     if(is_numeric($ws->value)) {
1484       return sprintf('%01.2f', $ws->value);
1485     }
1486   }
1487   return '';
1490 // Function to check if patient is deceased.
1491 //  Param:
1492 //    $pid  - patient id
1493 //    $date - date checking if deceased (will default to current date if blank)
1494 //  Return:
1495 //    If deceased, then will return the number of
1496 //      days that patient has been deceased.
1497 //    If not deceased, then will return false.
1498 function is_patient_deceased($pid,$date='') {
1500   // Set date to current if not set
1501   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1503   // Query for deceased status (gets days deceased if patient is deceased)
1504   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1505                       "FROM `patient_data` " .
1506                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1508   if (empty($results)) {
1509     // Patient is alive, so return false
1510     return false;
1511   }
1512   else {
1513     // Patient is dead, so return the number of days patient has been deceased.
1514     //  Don't let it be zero days or else will confuse calls to this function.
1515     if ($results['days_deceased'] === 0) {
1516       $results['days_deceased'] = 1;
1517     }
1518     return $results['days_deceased'];
1519   }