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