31e75b84c0099e6b7e468f4d55a7c524f70274e4
[openemr.git] / library / patient.inc
blob31e75b84c0099e6b7e468f4d55a7c524f70274e4
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 /**
39  * Get a patient's demographic data.
40  *
41  * @param int    $pid   The PID of the patient
42  * @param string $given an optional subsection of the patient's demographic
43  *                      data to retrieve.
44  * @return array The requested subsection of a patient's demographic data.
45  *               If no subsection was given, returns everything, with the
46  *               date of birth as the last field.
47  */
48 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
49     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
50     return sqlQuery($sql, array($pid) );
53 function getLanguages() {
54     $returnval = array('','english');
55     $sql = "select distinct lower(language) as language from patient_data";
56     $rez = sqlStatement($sql);
57     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
58         if (($row["language"] != "english") && ($row["language"] != "")) {
59             array_push($returnval, $row["language"]);
60         }
61     }
62     return $returnval;
65 function getInsuranceProvider($ins_id) {
66     
67     $sql = "select name from insurance_companies where id=?";
68     $row = sqlQuery($sql,array($ins_id));
69     return $row['name'];
70     
73 function getInsuranceProviders() {
74     $returnval = array();
76     if (true) {
77         $sql = "select name, id from insurance_companies order by name, id";
78         $rez = sqlStatement($sql);
79         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
80             $returnval[$row['id']] = $row['name'];
81         }
82     }
84     // Please leave this here. I have a user who wants to see zip codes and PO
85     // box numbers listed along with the insurance company names, as many companies
86     // have different billing addresses for different plans.  -- Rod Roark
87     //
88     else {
89         $sql = "select insurance_companies.name, insurance_companies.id, " .
90           "addresses.zip, addresses.line1 " .
91           "from insurance_companies, addresses " .
92           "where addresses.foreign_id = insurance_companies.id " .
93           "order by insurance_companies.name, addresses.zip";
95         $rez = sqlStatement($sql);
97         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
98             preg_match("/\d+/", $row['line1'], $matches);
99             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
100               "," . $matches[0] . ")";
101         }
102     }
104     return $returnval;
107 function getProviders() {
108     $returnval = array("");
109     $sql = "select fname, lname from users where authorized = 1 and " .
110         "active = 1 and username != ''";
111     $rez = sqlStatement($sql);
112     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
113         if (($row["fname"] != "") && ($row["lname"] != "")) {
114             array_push($returnval, $row["fname"] . " " . $row["lname"]);
115         }
116     }
117     return $returnval;
120 // ----------------------------------------------------------------------------
121 // Get one facility row.  If the ID is not specified, then get either the
122 // "main" (billing) facility, or the default facility of the currently
123 // logged-in user.  This was created to support genFacilityTitle() but
124 // may find additional uses.
126 function getFacility($facid=0) {
128   //create a sql binding array
129   $sqlBindArray = array();
130   
131   if ($facid > 0) {
132     $query = "SELECT * FROM facility WHERE id = ?";
133     array_push($sqlBindArray,$facid);
134   }
135   else if ($facid == 0) {
136     $query = "SELECT * FROM facility ORDER BY " .
137       "billing_location DESC, service_location, id LIMIT 1";
138   }
139   else {
140     $query = "SELECT facility.* FROM users, facility WHERE " .
141       "users.id = ? AND " .
142       "facility.id = users.facility_id";
143     array_push($sqlBindArray,$_SESSION['authUserID']);
144   }
145   return sqlQuery($query,$sqlBindArray);
148 // Generate a report title including report name and facility name, address
149 // and phone.
151 function genFacilityTitle($repname='', $facid=0) {
152   $s = '';
153   $s .= "<table class='ftitletable'>\n";
154   $s .= " <tr>\n";
155   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
156   $s .= "  <td class='ftitlecell2'>\n";
157   $r = getFacility($facid);
158   if (!empty($r)) {
159     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
160     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
161     if ($r['city'] || $r['state'] || $r['postal_code']) {
162       $s .= "<br />";
163       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
164       if ($r['state']) {
165         if ($r['city']) $s .= ", \n";
166         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
167       }
168       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
169       $s .= "\n";
170     }
171     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
172     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
173   }
174   $s .= "  </td>\n";
175   $s .= " </tr>\n";
176   $s .= "</table>\n";
177   return $s;
181 GET FACILITIES
183 returns all facilities or just the id for the first one
184 (FACILITY FILTERING (lemonsoftware))
186 @param string - if 'first' return first facility ordered by id
187 @return array | int for 'first' case
189 function getFacilities($first = '') {
190     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
191     $ret = array();
192     while ( $row = sqlFetchArray($r) ) {
193        $ret[] = $row;
196         if ( $first == 'first') {
197             return $ret[0]['id'];
198         } else {
199             return $ret;
200         }
204 GET SERVICE FACILITIES
206 returns all service_location facilities or just the id for the first one
207 (FACILITY FILTERING (CHEMED))
209 @param string - if 'first' return first facility ordered by id
210 @return array | int for 'first' case
212 function getServiceFacilities($first = '') {
213     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
214     $ret = array();
215     while ( $row = sqlFetchArray($r) ) {
216        $ret[] = $row;
219         if ( $first == 'first') {
220             return $ret[0]['id'];
221         } else {
222             return $ret;
223         }
226 //(CHEMED) facility filter
227 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
228     $param1 = "";
229     if ($providers_only === 'any') {
230       $param1 = " AND authorized = 1 AND active = 1 ";
231     }
232     else if ($providers_only) {
233       $param1 = " AND authorized = 1 AND calendar = 1 ";
234     }
236     //--------------------------------
237     //(CHEMED) facility filter
238     $param2 = "";
239     if ($facility) {
240       if ($GLOBALS['restrict_user_facility']) {
241         $param2 = " AND (facility_id = $facility 
242           OR  $facility IN
243                 (select facility_id 
244                 from users_facility
245                 where tablename = 'users'
246                 and table_id = id)
247                 )
248           ";
249       }
250       else {
251         $param2 = " AND facility_id = $facility ";
252       }
253     }
254     //--------------------------------
256     $command = "=";
257     if ($providerID == "%") {
258         $command = "like";
259     }
260     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
261         "from users where username != '' and active = 1 and id $command '" .
262         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
263     // sort by last name -- JRM June 2008
264     $query .= " ORDER BY lname, fname ";
265     $rez = sqlStatement($query);
266     for($iter=0; $row=sqlFetchArray($rez); $iter++)
267         $returnval[$iter]=$row;
269     //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
270     //accessible from $resultval['key']
272     if($iter==1) {
273         $akeys = array_keys($returnval[0]);
274         foreach($akeys as $key) {
275             $returnval[0][$key] = $returnval[0][$key];
276         }
277     }
278     return $returnval;
281 //same as above but does not reduce if only 1 row returned
282 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
283     $param1 = "";
284     if ($providers_only) {
285         $param1 = "AND authorized=1";
286     }
287     $command = "=";
288     if ($providerID == "%") {
289         $command = "like";
290     }
291     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
292         "from users where active = 1 and username != '' and id $command '" .
293         mysql_real_escape_string($providerID) . "' " . $param1;
295     $rez = sqlStatement($query);
296     for($iter=0; $row=sqlFetchArray($rez); $iter++)
297         $returnval[$iter]=$row;
299     return $returnval;
302 function getProviderName($providerID) {
303     $pi = getProviderInfo($providerID, 'any');
304     if (strlen($pi[0]["lname"]) > 0) {
305         return $pi[0]['fname'] . " " . $pi[0]['lname'];
306     }
307     return "";
310 function getProviderId($providerName) {
311     $query = "select id from users where username = ?";
312     $rez = sqlStatement($query, array($providerName) );
313     for($iter=0; $row=sqlFetchArray($rez); $iter++)
314         $returnval[$iter]=$row;
315     return $returnval;
318 function getEthnoRacials() {
319     $returnval = array("");
320     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
321     $rez = sqlStatement($sql);
322     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
323         if (($row["ethnoracial"] != "")) {
324             array_push($returnval, $row["ethnoracial"]);
325         }
326     }
327     return $returnval;
330 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
333     if ($dateStart && $dateEnd) {
334         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
335     }
336     else if ($dateStart && !$dateEnd) {
337         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
338     }
339     else if (!$dateStart && $dateEnd) {
340         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
341     }
342     else {
343         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
344     }
346     return $res;
349 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
350 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
352   $sql = "select $given from insurance_data as insd " .
353     "left join insurance_companies as ic on ic.id = insd.provider " .
354     "where pid = ? and type = ? order by date DESC limit 1";
355   return sqlQuery($sql, array($pid, $type) );
358 function getInsuranceDataByDate($pid, $date, $type,
359   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
360 { // this must take the date in the following manner: YYYY-MM-DD
361   // this function recalls the insurance value that was most recently enterred from the
362   // given date. it will call up most recent records up to and on the date given,
363   // but not records enterred after the given date
364   $sql = "select $given from insurance_data as insd " .
365     "left join insurance_companies as ic on ic.id = provider " .
366     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
367     "type=? order by date DESC limit 1";
368   return sqlQuery($sql, array($pid,$date,$type) );
371 function getEmployerData($pid, $given = "*")
373     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
374     return sqlQuery($sql, array($pid) );
377 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
378   // When the limit is exceeded, find out what the unlimited count would be.
379   $GLOBALS['PATIENT_INC_COUNT'] = $count;
380   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
381   if ($limit != "all") {
382     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
383     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
384   }
387 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")
389     // Allow the last name to be followed by a comma and some part of a first name.
390     // New behavior for searches:
391     // Allows comma alone followed by some part of a first name
392     // If the first letter of either name is capital, searches for name starting
393     // with given substring (the expected behavior).  If it is lower case, it
394     // it searches for the substring anywhere in the name.  This applies to either
395     // last name or first name or both.  The arbitrary limit of 100 results is set
396     // in the sql query below. --Mark Leeds
397     $lname = trim($lname);
398     $fname = '';
399      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
400          $lname = trim($matches[1]);
401          $fname = trim($matches[2]);
402     }
403     $search_for_pieces1 = '';
404     $search_for_pieces2 = '';
405     if ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
406     if ((strlen($fname) < 1)|| ($fname{0} != strtoupper($fname{0}))) {$search_for_pieces2 = '%';}
408     $sqlBindArray = array();
409     $where = "lname LIKE ? AND fname LIKE ? ";
410     array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
411         if (!empty($GLOBALS['pt_restrict_field'])) {
412                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
413                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
414                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
415                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
416                         array_push($sqlBindArray, $_SESSION{"authUser"});
417                 }
418         }
420     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
421     if ($limit != "all") $sql .= " LIMIT $start, $limit";
423     $rez = sqlStatement($sql, $sqlBindArray);
425     $returnval=array();
426     for($iter=0; $row=sqlFetchArray($rez); $iter++)
427         $returnval[$iter] = $row;
429     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
430     return $returnval;
433 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")
436     $sqlBindArray = array();
437     $where = "pubpid LIKE ? ";
438     array_push($sqlBindArray, $pid."%");
439         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
440                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
441                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
442                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
443                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
444                         array_push($sqlBindArray, $_SESSION{"authUser"});
445                 }
446         }
448     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
449     if ($limit != "all") $sql .= " limit $start, $limit";
450     $rez = sqlStatement($sql, $sqlBindArray);
451     for($iter=0; $row=sqlFetchArray($rez); $iter++)
452         $returnval[$iter]=$row;
454     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
455     return $returnval;
458 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")
460   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
462   $sqlBindArray = array();
463   $where = "";
464   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
465     if ( $iter > 0 ) {
466       $where .= " or ";
467     }
468     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
469     array_push($sqlBindArray, "%".$searchTerm."%");
470   }
472   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
473   if ($limit != "all") $sql .= " limit $start, $limit";
474   $rez = sqlStatement($sql, $sqlBindArray);
475   for($iter=0; $row=sqlFetchArray($rez); $iter++)
476     $returnval[$iter]=$row;
477   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
478   return $returnval;
481 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
482   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
483   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
485         $layoutCols = split( '~', $searchFields );
486   $sqlBindArray = array();
487   $where = "";
488   $i = 0;
489   foreach ($layoutCols as $val) {
490     if (empty($val)) continue;
491                 if ( $i > 0 ) {
492                    $where .= " or ";
493                 }
494     if ($val == 'pid') {
495                 $where .= " ".add_escape_custom($val)." = ? ";
496                 array_push($sqlBindArray, $searchTerm);
497     }
498     else {
499                 $where .= " ".add_escape_custom($val)." like ? ";
500                 array_push($sqlBindArray, $searchTerm."%");
501     }
502                 $i++;
503         }
505   // If no search terms, ensure valid syntax.
506   if ($i == 0) $where = "1 = 1";
508   // If a non-empty service code was given, then restrict to patients who
509   // have been provided that service.  Since the code is used in a LIKE
510   // clause, % and _ wildcards are supported.
511   if ($search_service_code) {
512     $where = "( $where ) AND " .
513       "( SELECT COUNT(*) FROM billing AS b WHERE " .
514       "b.pid = patient_data.pid AND " .
515       "b.activity = 1 AND " .
516       "b.code_type != 'COPAY' AND " .
517       "b.code LIKE ? " .
518       ") > 0";
519     array_push($sqlBindArray, $search_service_code);
520   }
522   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
523   if ($limit != "all") $sql .= " limit $start, $limit";
524   $rez = sqlStatement($sql, $sqlBindArray);
525   for($iter=0; $row=sqlFetchArray($rez); $iter++)
526       $returnval[$iter]=$row;
527   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
528   return $returnval;
531 // return a collection of Patient PIDs
532 // new arg style by JRM March 2008
533 // 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")
534 function getPatientPID($args)
536     $pid = "%";
537     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
538     $orderby = "lname ASC, fname ASC";
539     $limit="all";
540     $start="0";
542     // alter default values if defined in the passed in args
543     if (isset($args['pid'])) { $pid = $args['pid']; }
544     if (isset($args['given'])) { $given = $args['given']; }
545     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
546     if (isset($args['limit'])) { $limit = $args['limit']; }
547     if (isset($args['start'])) { $start = $args['start']; }
549     $command = "=";
550     if ($pid == -1) $pid = "%";
551     elseif (empty($pid)) $pid = "NULL";
553     if (strstr($pid,"%")) $command = "like";
555     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
556     if ($limit != "all") $sql .= " limit $start, $limit";
558     $rez = sqlStatement($sql);
559     for($iter=0; $row=sqlFetchArray($rez); $iter++)
560         $returnval[$iter]=$row;
562     return $returnval;
565 /* return a patient's name in the format LAST, FIRST */
566 function getPatientName($pid) {
567     if (empty($pid)) return "";
568     $patientData = getPatientPID(array("pid"=>$pid));
569     if (empty($patientData[0]['lname'])) return "";
570     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
571     return $patientName;
574 /* find patient data by DOB */
575 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
577     $DOB = fixDate($DOB, $DOB);
578     $sqlBindArray = array();
579     $where = "DOB like ? ";
580     array_push($sqlBindArray, $DOB."%");
581         if (!empty($GLOBALS['pt_restrict_field'])) {
582                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
583                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
584                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
585                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
586                         array_push($sqlBindArray, $_SESSION{"authUser"});
587                 }
588         }
590     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
592     if ($limit != "all") $sql .= " LIMIT $start, $limit";
594     $rez = sqlStatement($sql, $sqlBindArray);
595     for($iter=0; $row=sqlFetchArray($rez); $iter++)
596         $returnval[$iter]=$row;
598     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
599     return $returnval;
602 /* find patient data by SSN */
603 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
605     $sqlBindArray = array();
606     $where = "ss LIKE ?";
607     array_push($sqlBindArray, $ss."%");
608     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
609     if ($limit != "all") $sql .= " LIMIT $start, $limit";
611     $rez = sqlStatement($sql, $sqlBindArray);
612     for($iter=0; $row=sqlFetchArray($rez); $iter++)
613         $returnval[$iter]=$row;
615     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
616     return $returnval;
619 //(CHEMED) Search by phone number
620 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
622     $phone = ereg_replace( "[[:punct:]]","", $phone );
623     $sqlBindArray = array();
624     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
625     array_push($sqlBindArray, $phone);
626     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
627     if ($limit != "all") $sql .= " LIMIT $start, $limit";
629     $rez = sqlStatement($sql, $sqlBindArray);
630     for($iter=0; $row=sqlFetchArray($rez); $iter++)
631         $returnval[$iter]=$row;
633     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
634     return $returnval;
637 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
639     $sql="select $given from patient_data order by $orderby";
641     if ($limit != "all")
642         $sql .= " limit $start, $limit";
644     $rez = sqlStatement($sql);
645     for($iter=0; $row=sqlFetchArray($rez); $iter++)
646         $returnval[$iter]=$row;
648     return $returnval;
651 //----------------------input functions
652 function newPatientData(    $db_id="",
653                 $title = "",
654                 $fname = "",
655                 $lname = "",
656                 $mname = "",
657                 $sex = "",
658                 $DOB = "",
659                 $street = "",
660                 $postal_code = "",
661                 $city = "",
662                 $state = "",
663                 $country_code = "",
664                 $ss = "",
665                 $occupation = "",
666                 $phone_home = "",
667                 $phone_biz = "",
668                 $phone_contact = "",
669                 $status = "",
670                 $contact_relationship = "",
671                 $referrer = "",
672                 $referrerID = "",
673                 $email = "",
674                 $language = "",
675                 $ethnoracial = "",
676                 $interpretter = "",
677                 $migrantseasonal = "",
678                 $family_size = "",
679                 $monthly_income = "",
680                 $homeless = "",
681                 $financial_review = "",
682                 $pubpid = "",
683                 $pid = "MAX(pid)+1",
684                 $providerID = "",
685                 $genericname1 = "",
686                 $genericval1 = "",
687                 $genericname2 = "",
688                 $genericval2 = "",
689                 $phone_cell = "",
690                 $hipaa_mail = "",
691                 $hipaa_voice = "",
692                 $squad = 0,
693                 $pharmacy_id = 0,
694                 $drivers_license = "",
695                 $hipaa_notice = "",
696                 $hipaa_message = "",
697                 $regdate = ""
698             )
700     $DOB = fixDate($DOB);
701     $regdate = fixDate($regdate);
703     $fitness = 0;
704     $referral_source = '';
705     if ($pid) {
706         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
707         // Check for brain damage:
708         if ($db_id != $rez['id']) {
709             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
710               $rez['id'] . "' to '$db_id' for pid '$pid'";
711             die($errmsg);
712         }
713         $fitness = $rez['fitness'];
714         $referral_source = $rez['referral_source'];
715     }
717     // Get the default price level.
718     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
719       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
720     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
722     $query = ("replace into patient_data set
723         id='$db_id',
724         title='$title',
725         fname='$fname',
726         lname='$lname',
727         mname='$mname',
728         sex='$sex',
729         DOB='$DOB',
730         street='$street',
731         postal_code='$postal_code',
732         city='$city',
733         state='$state',
734         country_code='$country_code',
735         drivers_license='$drivers_license',
736         ss='$ss',
737         occupation='$occupation',
738         phone_home='$phone_home',
739         phone_biz='$phone_biz',
740         phone_contact='$phone_contact',
741         status='$status',
742         contact_relationship='$contact_relationship',
743         referrer='$referrer',
744         referrerID='$referrerID',
745         email='$email',
746         language='$language',
747         ethnoracial='$ethnoracial',
748         interpretter='$interpretter',
749         migrantseasonal='$migrantseasonal',
750         family_size='$family_size',
751         monthly_income='$monthly_income',
752         homeless='$homeless',
753         financial_review='$financial_review',
754         pubpid='$pubpid',
755         pid = $pid,
756         providerID = '$providerID',
757         genericname1 = '$genericname1',
758         genericval1 = '$genericval1',
759         genericname2 = '$genericname2',
760         genericval2 = '$genericval2',
761         phone_cell = '$phone_cell',
762         pharmacy_id = '$pharmacy_id',
763         hipaa_mail = '$hipaa_mail',
764         hipaa_voice = '$hipaa_voice',
765         hipaa_notice = '$hipaa_notice',
766         hipaa_message = '$hipaa_message',
767         squad = '$squad',
768         fitness='$fitness',
769         referral_source='$referral_source',
770         regdate='$regdate',
771         pricelevel='$pricelevel',
772         date=NOW()");
774     $id = sqlInsert($query);
776     if ( !$db_id ) {
777       // find the last inserted id for new patient case
778       $db_id = mysql_insert_id();
779     }
781     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
783     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
784                 $phone_biz,$phone_cell,$email,$pid);
786     return $foo['pid'];
789 // Supported input date formats are:
790 //   mm/dd/yyyy
791 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
792 //   yyyy/mm/dd
793 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
795 function fixDate($date, $default="0000-00-00") {
796     $fixed_date = $default;
797     $date = trim($date);
798     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
799         $dmy = preg_split("'[/.-]'", $date);
800         if ($dmy[0] > 99) {
801             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
802         } else {
803             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
804               if ($dmy[2] < 1000) $dmy[2] += 1900;
805               if ($dmy[2] < 1910) $dmy[2] += 100;
806             }
807             // phone_country_code indicates format of ambiguous input dates.
808             if ($GLOBALS['phone_country_code'] == 1)
809               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
810             else
811               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
812         }
813     }
815     return $fixed_date;
818 function pdValueOrNull($key, $value) {
819   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
820     substr($key, 0, 8) == 'userdate') &&
821     (empty($value) || $value == '0000-00-00'))
822   {
823     return "NULL";
824   }
825   else {
826     return "'$value'";
827   }
830 // Create or update patient data from an array.
832 function updatePatientData($pid, $new, $create=false)
834   /*******************************************************************
835     $real = getPatientData($pid);
836     $new['DOB'] = fixDate($new['DOB']);
837     while(list($key, $value) = each ($new))
838         $real[$key] = $value;
839     $real['date'] = "'+NOW()+'";
840     $real['id'] = "";
841     $sql = "insert into patient_data set ";
842     while(list($key, $value) = each($real))
843         $sql .= $key." = '$value', ";
844     $sql = substr($sql, 0, -2);
845     return sqlInsert($sql);
846   *******************************************************************/
848   // The above was broken, though seems intent to insert a new patient_data
849   // row for each update.  A good idea, but nothing is doing that yet so
850   // the code below does not yet attempt it.
852   $new['DOB'] = fixDate($new['DOB']);
854   if ($create) {
855     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
856     foreach ($new as $key => $value) {
857       if ($key == 'id') continue;
858       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
859     }
860     $db_id = sqlInsert($sql);
861   }
862   else {
863     $db_id = $new['id'];
864     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
865     // Check for brain damage:
866     if ($pid != $rez['pid']) {
867       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
868         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
869       die($errmsg);
870     }
871     $sql = "UPDATE patient_data SET date = NOW()";
872     foreach ($new as $key => $value) {
873       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
874     }
875     $sql .= " WHERE id = '$db_id'";
876     sqlStatement($sql);
877   }
879   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
880   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
881     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
882     $rez['phone_cell'],$rez['email'],$rez['pid']);
884   return $db_id;
887 function newEmployerData(    $pid,
888                 $name = "",
889                 $street = "",
890                 $postal_code = "",
891                 $city = "",
892                 $state = "",
893                 $country = ""
894             )
896     return sqlInsert("insert into employer_data set
897         name='$name',
898         street='$street',
899         postal_code='$postal_code',
900         city='$city',
901         state='$state',
902         country='$country',
903         pid='$pid',
904         date=NOW()
905         ");
908 // Create or update employer data from an array.
910 function updateEmployerData($pid, $new, $create=false)
912   $colnames = array('name','street','city','state','postal_code','country');
914   if ($create) {
915     $set .= "pid = '$pid', date = NOW()";
916     foreach ($colnames as $key) {
917       $value = isset($new[$key]) ? $new[$key] : '';
918       $set .= ", `$key` = '$value'";
919     }
920     return sqlInsert("INSERT INTO employer_data SET $set");
921   }
922   else {
923     $set = '';
924     $old = getEmployerData($pid);
925     $modified = false;
926     foreach ($colnames as $key) {
927       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
928       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
929         $value = $new[$key];
930         $modified = true;
931       }
932       $set .= "`$key` = '$value', ";
933     }
934     if ($modified) {
935       $set .= "pid = '$pid', date = NOW()";
936       return sqlInsert("INSERT INTO employer_data SET $set");
937     }
938     return $old['id'];
939   }
942 // This updates or adds the given insurance data info, while retaining any
943 // previously added insurance_data rows that should be preserved.
944 // This does not directly support the maintenance of non-current insurance.
946 function newInsuranceData(
947   $pid,
948   $type = "",
949   $provider = "",
950   $policy_number = "",
951   $group_number = "",
952   $plan_name = "",
953   $subscriber_lname = "",
954   $subscriber_mname = "",
955   $subscriber_fname = "",
956   $subscriber_relationship = "",
957   $subscriber_ss = "",
958   $subscriber_DOB = "",
959   $subscriber_street = "",
960   $subscriber_postal_code = "",
961   $subscriber_city = "",
962   $subscriber_state = "",
963   $subscriber_country = "",
964   $subscriber_phone = "",
965   $subscriber_employer = "",
966   $subscriber_employer_street = "",
967   $subscriber_employer_city = "",
968   $subscriber_employer_postal_code = "",
969   $subscriber_employer_state = "",
970   $subscriber_employer_country = "",
971   $copay = "",
972   $subscriber_sex = "",
973   $effective_date = "0000-00-00",
974   $accept_assignment = "TRUE",
975   $policy_type = "")
977   if (strlen($type) <= 0) return FALSE;
979   // If a bad date was passed, err on the side of caution.
980   $effective_date = fixDate($effective_date, date('Y-m-d'));
982   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
983     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
984   $idrow = sqlFetchArray($idres);
986   // Replace the most recent entry in any of the following cases:
987   // * Its effective date is >= this effective date.
988   // * It is the first entry and it has no (insurance) provider.
989   // * There is no encounter that is earlier than the new effective date but
990   //   on or after the old effective date.
991   // Otherwise insert a new entry.
993   $replace = false;
994   if ($idrow) {
995     if (strcmp($idrow['date'], $effective_date) > 0) {
996       $replace = true;
997     }
998     else {
999       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1000         $replace = true;
1001       }
1002       else {
1003         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1004           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1005           "date >= '" . $idrow['date'] . " 00:00:00'");
1006         if ($ferow['count'] == 0) $replace = true;
1007       }
1008     }
1009   }
1011   if ($replace) {
1013     // TBD: This is a bit dangerous in that a typo in entering the effective
1014     // date can wipe out previous insurance history.  So we want some data
1015     // entry validation somewhere.
1016     sqlStatement("DELETE FROM insurance_data WHERE " .
1017       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1018       "id != " . $idrow['id']);
1020     $data = array();
1021     $data['type'] = $type;
1022     $data['provider'] = $provider;
1023     $data['policy_number'] = $policy_number;
1024     $data['group_number'] = $group_number;
1025     $data['plan_name'] = $plan_name;
1026     $data['subscriber_lname'] = $subscriber_lname;
1027     $data['subscriber_mname'] = $subscriber_mname;
1028     $data['subscriber_fname'] = $subscriber_fname;
1029     $data['subscriber_relationship'] = $subscriber_relationship;
1030     $data['subscriber_ss'] = $subscriber_ss;
1031     $data['subscriber_DOB'] = $subscriber_DOB;
1032     $data['subscriber_street'] = $subscriber_street;
1033     $data['subscriber_postal_code'] = $subscriber_postal_code;
1034     $data['subscriber_city'] = $subscriber_city;
1035     $data['subscriber_state'] = $subscriber_state;
1036     $data['subscriber_country'] = $subscriber_country;
1037     $data['subscriber_phone'] = $subscriber_phone;
1038     $data['subscriber_employer'] = $subscriber_employer;
1039     $data['subscriber_employer_city'] = $subscriber_employer_city;
1040     $data['subscriber_employer_street'] = $subscriber_employer_street;
1041     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1042     $data['subscriber_employer_state'] = $subscriber_employer_state;
1043     $data['subscriber_employer_country'] = $subscriber_employer_country;
1044     $data['copay'] = $copay;
1045     $data['subscriber_sex'] = $subscriber_sex;
1046     $data['pid'] = $pid;
1047     $data['date'] = $effective_date;
1048     $data['accept_assignment'] = $accept_assignment;
1049     $data['policy_type'] = $policy_type;
1050     updateInsuranceData($idrow['id'], $data);
1051     return $idrow['id'];
1052   }
1053   else {
1054     return sqlInsert("INSERT INTO insurance_data SET
1055       type = '$type',
1056       provider = '$provider',
1057       policy_number = '$policy_number',
1058       group_number = '$group_number',
1059       plan_name = '$plan_name',
1060       subscriber_lname = '$subscriber_lname',
1061       subscriber_mname = '$subscriber_mname',
1062       subscriber_fname = '$subscriber_fname',
1063       subscriber_relationship = '$subscriber_relationship',
1064       subscriber_ss = '$subscriber_ss',
1065       subscriber_DOB = '$subscriber_DOB',
1066       subscriber_street = '$subscriber_street',
1067       subscriber_postal_code = '$subscriber_postal_code',
1068       subscriber_city = '$subscriber_city',
1069       subscriber_state = '$subscriber_state',
1070       subscriber_country = '$subscriber_country',
1071       subscriber_phone = '$subscriber_phone',
1072       subscriber_employer = '$subscriber_employer',
1073       subscriber_employer_city = '$subscriber_employer_city',
1074       subscriber_employer_street = '$subscriber_employer_street',
1075       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1076       subscriber_employer_state = '$subscriber_employer_state',
1077       subscriber_employer_country = '$subscriber_employer_country',
1078       copay = '$copay',
1079       subscriber_sex = '$subscriber_sex',
1080       pid = '$pid',
1081       date = '$effective_date',
1082       accept_assignment = '$accept_assignment',
1083       policy_type = '$policy_type'
1084     ");
1085   }
1088 // This is used internally only.
1089 function updateInsuranceData($id, $new)
1091   $fields = sqlListFields("insurance_data");
1092   $use = array();
1094   while(list($key, $value) = each ($new)) {
1095     if (in_array($key, $fields)) {
1096       $use[$key] = $value;
1097     }
1098   }
1100   $sql = "UPDATE insurance_data SET ";
1101   while(list($key, $value) = each($use))
1102     $sql .= "`$key` = '$value', ";
1103   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1105   sqlStatement($sql);
1108 function newHistoryData($pid, $new=false) {
1109   $arraySqlBind = array();
1110   $sql = "insert into history_data set pid = ?, date = NOW()";
1111   array_push($arraySqlBind,$pid);
1112   if ($new) {
1113     while(list($key, $value) = each($new)) {
1114       array_push($arraySqlBind,$value);
1115       $sql .= ", `$key` = ?";
1116     }
1117   }
1118   return sqlInsert($sql, $arraySqlBind );
1121 function updateHistoryData($pid,$new)
1123         $real = getHistoryData($pid);
1124         while(list($key, $value) = each ($new))
1125                 $real[$key] = $value;
1126         $real['id'] = "";
1127         // need to unset date, so can reset it below
1128         unset($real['date']);
1130         $arraySqlBind = array();
1131         $sql = "insert into history_data set `date` = NOW(), ";
1132         while(list($key, $value) = each($real)) {
1133                 array_push($arraySqlBind,$value);
1134                 $sql .= "`$key` = ?, ";
1135         }
1136         $sql = substr($sql, 0, -2);
1138         return sqlInsert($sql, $arraySqlBind );
1141 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1142                 $phone_biz,$phone_cell,$email,$pid="")
1144     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1145     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1147     $db = $GLOBALS['adodb']['db'];
1148     $customer_info = array();
1150     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1151     $result = $db->Execute($sql);
1152     if ($result && !$result->EOF) {
1153         $customer_info['foreign_update'] = true;
1154         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1155         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1156     }
1158     ///xml rpc code to connect to accounting package and add user to it
1159     $customer_info['firstname'] = $fname;
1160     $customer_info['lastname'] = $lname;
1161     $customer_info['address'] = $street;
1162     $customer_info['suburb'] = $city;
1163     $customer_info['state'] = $state;
1164     $customer_info['postcode'] = $postal_code;
1166     //ezybiz wants state as a code rather than abbreviation
1167     $customer_info['geo_zone_id'] = "";
1168     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1169     $db = $GLOBALS['adodb']['db'];
1170     $result = $db->Execute($sql);
1171     if ($result && !$result->EOF) {
1172         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1173     }
1175     //ezybiz wants country as a code rather than abbreviation
1176     $customer_info['geo_country_id'] = "";
1177     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1178     $db = $GLOBALS['adodb']['db'];
1179     $result = $db->Execute($sql);
1180     if ($result && !$result->EOF) {
1181         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1182     }
1184     $customer_info['phone1'] = $phone_home;
1185     $customer_info['phone1comment'] = "Home Phone";
1186     $customer_info['phone2'] = $phone_biz;
1187     $customer_info['phone2comment'] = "Business Phone";
1188     $customer_info['phone3'] = $phone_cell;
1189     $customer_info['phone3comment'] = "Cell Phone";
1190     $customer_info['email'] = $email;
1191     $customer_info['customernumber'] = $pid;
1193     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1194     $ws = new WSWrapper($function);
1196     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1197     if (is_numeric($ws->value)) {
1198         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1199         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1200     }
1203 // Returns Age 
1204 //   in months if < 2 years old
1205 //   in years  if > 2 years old
1206 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1207 // (optional) nowYMD is a date in YYYYMMDD format
1208 function getPatientAge($dobYMD, $nowYMD=null)
1210     // strip any dashes from the DOB
1211     $dobYMD = preg_replace("/-/", "", $dobYMD);
1212     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1213     
1214     // set the 'now' date values
1215     if ($nowYMD == null) {
1216         $nowDay = date("d");
1217         $nowMonth = date("m");
1218         $nowYear = date("Y");
1219     }
1220     else {
1221         $nowDay = substr($nowYMD,6,2);
1222         $nowMonth = substr($nowYMD,4,2);
1223         $nowYear = substr($nowYMD,0,4);
1224     }
1226     $dayDiff = $nowDay - $dobDay;
1227     $monthDiff = $nowMonth - $dobMonth;
1228     $yearDiff = $nowYear - $dobYear;
1230     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1232     if ( $ageInMonths > 24 ) {
1233         $age = $yearDiff;
1234         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1235         else if ($monthDiff < 0) { $age -= 1; }
1236     }
1237     else  {
1238         $age = "$ageInMonths month"; 
1239     }
1241     return $age;
1245 // Returns Age in days
1246 //   in months if < 2 years old
1247 //   in years  if > 2 years old
1248 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1249 // (optional) nowYMD is a date in YYYYMMDD format
1250 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1251     $age = -1;
1253     // strip any dashes from the DOB
1254     $dobYMD = preg_replace("/-/", "", $dobYMD);
1255     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1256     
1257     // set the 'now' date values
1258     if ($nowYMD == null) {
1259         $nowDay = date("d");
1260         $nowMonth = date("m");
1261         $nowYear = date("Y");
1262     }
1263     else {
1264         $nowDay = substr($nowYMD,6,2);
1265         $nowMonth = substr($nowYMD,4,2);
1266         $nowYear = substr($nowYMD,0,4);
1267     }
1269     // do the date math
1270     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1271     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1272     $timediff = $nowtime - $dobtime;
1273     $age = $timediff / 86400;
1275     return $age;
1278 function dateToDB ($date)
1280     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1281     return $date;
1285 // ----------------------------------------------------------------------------
1287  * DROPDOWN FOR COUNTRIES
1288  * 
1289  * build a dropdown with all countries from geo_country_reference
1290  * 
1291  * @param int $selected - id for selected record
1292  * @param string $name - the name/id for select form
1293  * @return void - just echo the html encoded string
1294  */
1295 function dropdown_countries($selected = 0, $name = 'country_code') {
1296     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1298     $string = "<select name='$name' id='$name'>";
1299     while ( $row = sqlFetchArray($r) ) {
1300         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1301         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1302     }
1304     $string .= '</select>';
1305     echo $string;
1309 // ----------------------------------------------------------------------------
1311  * DROPDOWN FOR YES/NO
1312  * 
1313  * build a dropdown with two options (yes - 1, no - 0)
1314  * 
1315  * @param int $selected - id for selected record
1316  * @param string $name - the name/id for select form
1317  * @return void - just echo the html encoded string 
1318  */
1319 function dropdown_yesno($selected = 0, $name = 'yesno') {
1320     $string = "<select name='$name' id='$name'>";
1322     $selected = (int)$selected;
1323     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1324     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1326     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1327     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1328     $string .= '</select>';
1330     echo $string;
1333 // ----------------------------------------------------------------------------
1335  * DROPDOWN FOR MALE/FEMALE options
1336  * 
1337  * build a dropdown with three options (unselected/male/female)
1338  * 
1339  * @param int $selected - id for selected record
1340  * @param string $name - the name/id for select form
1341  * @return void - just echo the html encoded string
1342  */
1343 function dropdown_sex($selected = 0, $name = 'sex') {
1344     $string = "<select name='$name' id='$name'>";
1346     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1347     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1348     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1350     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1351     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1352     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1353     $string .= '</select>';
1355     echo $string;
1358 // ----------------------------------------------------------------------------
1360  * DROPDOWN FOR MARITAL STATUS
1361  * 
1362  * build a dropdown with marital status
1363  * 
1364  * @param int $selected - id for selected record
1365  * @param string $name - the name/id for select form
1366  * @return void - just echo the html encoded string
1367  */
1368 function dropdown_marital($selected = 0, $name = 'status') {
1369     $string = "<select name='$name' id='$name'>";
1371     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1373     foreach ( $statii as $st ) {
1374         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1375         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1376     }
1378     $string .= '</select>';
1380     echo $string;
1383 // ----------------------------------------------------------------------------
1385  * DROPDOWN FOR PROVIDERS
1386  * 
1387  * build a dropdown with all providers
1388  * 
1389  * @param int $selected - id for selected record
1390  * @param string $name - the name/id for select form
1391  * @return void - just echo the html encoded string
1392  */
1393 function dropdown_providers($selected = 0, $name = 'status') {
1394     $provideri = getProviderInfo();
1396     $string = "<select name='$name' id='$name'>";
1397     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1398     foreach ( $provideri as $s ) {
1399         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1400         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1401     }
1403     $string .= '</select>';
1405     echo $string;
1408 // ----------------------------------------------------------------------------
1410  * DROPDOWN FOR INSURANCE COMPANIES
1411  * 
1412  * build a dropdown with all insurers
1413  * 
1414  * @param int $selected - id for selected record
1415  * @param string $name - the name/id for select form
1416  * @return void - just echo the html encoded string
1417  */
1418 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1419     $insurancei = getInsuranceProviders();
1421     $string = "<select name='$name' id='$name'>";
1422     $string .= '<option value="0">Onbekend</option>';
1423     foreach ( $insurancei as $iid => $iname ) {
1424         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1425         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1426     }
1428     $string .= '</select>';
1430     echo $string;
1434 // ----------------------------------------------------------------------------
1436  * COUNTRY CODE
1437  * 
1438  * return the name or the country code, function of arguments
1439  * 
1440  * @param int $country_code
1441  * @param string $country_name
1442  * @return string | int - name or code
1443  */
1444 function country_code($country_code = 0, $country_name = '') {
1445     $strint = '';
1446     if ( $country_code ) {
1447         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1448     } else {
1449         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1450     }
1452     $db = $GLOBALS['adodb']['db'];
1453     $result = $db->Execute($sql);
1454     if ($result && !$result->EOF) {
1455         $strint = $result->fields['res'];
1456     }
1458     return $strint;
1461 function DBToDate ($date)
1463     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1464     return $date;
1467 function get_patient_balance($pid) {
1468   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1469     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1470       "pid = ? AND activity = 1", array($pid) );
1471     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1472       "pid = ?", array($pid) );
1473     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1474       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1475       "pid = ?", array($pid) );
1476     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1477       - $drow['payments'] - $drow['adjustments']);
1478   }
1479   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1480     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1481     $conn = $GLOBALS['adodb']['db'];
1482     $customer_info['id'] = 0;
1483     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1484       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1485       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1486       "im.foreign_table = 'customer'";
1487     $result = $conn->Execute($sql);
1488     if($result && !$result->EOF) {
1489       $customer_info['id'] = $result->fields['foreign_id'];
1490     }
1491     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1492     $ws = new WSWrapper($function);
1493     if(is_numeric($ws->value)) {
1494       return sprintf('%01.2f', $ws->value);
1495     }
1496   }
1497   return '';
1500 // Function to check if patient is deceased.
1501 //  Param:
1502 //    $pid  - patient id
1503 //    $date - date checking if deceased (will default to current date if blank)
1504 //  Return:
1505 //    If deceased, then will return the number of
1506 //      days that patient has been deceased.
1507 //    If not deceased, then will return false.
1508 function is_patient_deceased($pid,$date='') {
1510   // Set date to current if not set
1511   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1513   // Query for deceased status (gets days deceased if patient is deceased)
1514   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1515                       "FROM `patient_data` " .
1516                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1518   if (empty($results)) {
1519     // Patient is alive, so return false
1520     return false;
1521   }
1522   else {
1523     // Patient is dead, so return the number of days patient has been deceased.
1524     //  Don't let it be zero days or else will confuse calls to this function.
1525     if ($results['days_deceased'] === 0) {
1526       $results['days_deceased'] = 1;
1527     }
1528     return $results['days_deceased'];
1529   }