Space to separate "&&" so that all "&$var" can be made into "$var" later
[openemr.git] / library / patient.inc
blobab38ea02f6f724dd0348df877ca13929ea4a6020
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     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1237     if($dayDiff<0) { $ageInMonths-=1; } 
1238     
1239     if ( $ageInMonths > 24 ) {
1240         $age = $yearDiff;
1241         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1242         else if ($monthDiff < 0) { $age -= 1; }
1243     }
1244     else  {
1245         $age = "$ageInMonths month"; 
1246     }
1248     return $age;
1252  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1253  * format expected by getPatientAgeYMD
1255  * @param  string  $dob     date of birth
1256  * @param  string  $target  date to calculate age on
1257  * @return array containing
1258  *      age - decimal age in years
1259  *      age_in_months - decimal age in months
1260  *      ageinYMD - formatted string #y #m #d */
1261 function parseAgeInfo($dob,$target)
1263     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1264     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1265     // Prepare target (Y-M-D H:M:S)
1266     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1268     return getPatientAgeYMD($dateDOB,$dateTarget);
1273  * 
1274  * @param type $dob
1275  * @param type $date
1276  * @return array containing
1277  *      age - decimal age in years
1278  *      age_in_months - decimal age in months
1279  *      ageinYMD - formatted string #y #m #d
1280  */
1281 function getPatientAgeYMD($dob, $date=null) {
1282         
1283     if ($date == null) {
1284         $daynow = date("d");
1285         $monthnow = date("m");
1286         $yearnow = date("Y");
1287         $datenow=$yearnow.$monthnow.$daynow;
1288     }
1289     else {
1290         $datenow=preg_replace("/-/", "", $date);
1291         $yearnow=substr($datenow,0,4);
1292         $monthnow=substr($datenow,4,2);
1293         $daynow=substr($datenow,6,2);
1294         $datenow=$yearnow.$monthnow.$daynow;
1295     }
1297     $dob=preg_replace("/-/", "", $dob);
1298     $dobyear=substr($dob,0,4);
1299     $dobmonth=substr($dob,4,2);
1300     $dobday=substr($dob,6,2);
1301     $dob=$dobyear.$dobmonth.$dobday;
1303     //to compensate for 30, 31, 28, 29 days/month
1304     $mo=$monthnow; //to avoid confusion with later calculation
1306     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1307         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1308     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1309     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1310         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1311         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1312         else {$nd=28;} //otherwise, it is not a leap year.
1313     }
1314     else {$nd=31;} // other months have 31 days
1316     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1317     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1318     {
1319         $age_year = $yearnow - $dobyear - 1;
1320         if ($daynow < $dobday) {
1321             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1322             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1323         }
1324         else {
1325             $months_since_birthday=12 - $dobmonth + $monthnow;
1326             $days_since_dobday=$daynow - $dobday;
1327         }
1328     }
1329     else // if patient has had birthday this calandar year
1330     {
1331         $age_year = $yearnow - $dobyear;
1332         if ($daynow < $dobday) {
1333             $months_since_birthday=$monthnow - $dobmonth -1;
1334             $days_since_dobday=$nd - $dobday + $daynow;
1335         }
1336         else {
1337             $months_since_birthday=$monthnow - $dobmonth;
1338             $days_since_dobday=$daynow - $dobday;
1339         }       
1340     }
1341     
1342     $day_as_month_decimal = $days_since_dobday / 30;
1343     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1344     $month_as_year_decimal = $months_since_birthday_float / 12;
1345     $age_float = $age_year + $month_as_year_decimal;
1347     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1348     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1349     $age = round($age_float,2);
1351     // round the years to 2 floating points
1352     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1353     return compact('age','age_in_months','ageinYMD');
1356 // Returns Age in days
1357 //   in months if < 2 years old
1358 //   in years  if > 2 years old
1359 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1360 // (optional) nowYMD is a date in YYYYMMDD format
1361 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1362     $age = -1;
1364     // strip any dashes from the DOB
1365     $dobYMD = preg_replace("/-/", "", $dobYMD);
1366     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1367     
1368     // set the 'now' date values
1369     if ($nowYMD == null) {
1370         $nowDay = date("d");
1371         $nowMonth = date("m");
1372         $nowYear = date("Y");
1373     }
1374     else {
1375         $nowDay = substr($nowYMD,6,2);
1376         $nowMonth = substr($nowYMD,4,2);
1377         $nowYear = substr($nowYMD,0,4);
1378     }
1380     // do the date math
1381     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1382     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1383     $timediff = $nowtime - $dobtime;
1384     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1386     return $age;
1389  * Returns a string to be used to display a patient's age
1390  * 
1391  * @param type $dobYMD
1392  * @param type $asOfYMD
1393  * @return string suitable for displaying patient's age based on preferences
1394  */
1395 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1397     if($GLOBALS['age_display_format']=='1')
1398     {
1399         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1400         return $ageYMD['ageinYMD'];
1401     }
1402     else
1403     {
1404         return getPatientAge($dobYMD, $asOfYMD);
1405     }
1406     
1408 function dateToDB ($date)
1410     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1411     return $date;
1415 // ----------------------------------------------------------------------------
1417  * DROPDOWN FOR COUNTRIES
1418  * 
1419  * build a dropdown with all countries from geo_country_reference
1420  * 
1421  * @param int $selected - id for selected record
1422  * @param string $name - the name/id for select form
1423  * @return void - just echo the html encoded string
1424  */
1425 function dropdown_countries($selected = 0, $name = 'country_code') {
1426     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1428     $string = "<select name='$name' id='$name'>";
1429     while ( $row = sqlFetchArray($r) ) {
1430         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1431         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1432     }
1434     $string .= '</select>';
1435     echo $string;
1439 // ----------------------------------------------------------------------------
1441  * DROPDOWN FOR YES/NO
1442  * 
1443  * build a dropdown with two options (yes - 1, no - 0)
1444  * 
1445  * @param int $selected - id for selected record
1446  * @param string $name - the name/id for select form
1447  * @return void - just echo the html encoded string 
1448  */
1449 function dropdown_yesno($selected = 0, $name = 'yesno') {
1450     $string = "<select name='$name' id='$name'>";
1452     $selected = (int)$selected;
1453     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1454     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1456     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1457     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1458     $string .= '</select>';
1460     echo $string;
1463 // ----------------------------------------------------------------------------
1465  * DROPDOWN FOR MALE/FEMALE options
1466  * 
1467  * build a dropdown with three options (unselected/male/female)
1468  * 
1469  * @param int $selected - id for selected record
1470  * @param string $name - the name/id for select form
1471  * @return void - just echo the html encoded string
1472  */
1473 function dropdown_sex($selected = 0, $name = 'sex') {
1474     $string = "<select name='$name' id='$name'>";
1476     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1477     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1478     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1480     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1481     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1482     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1483     $string .= '</select>';
1485     echo $string;
1488 // ----------------------------------------------------------------------------
1490  * DROPDOWN FOR MARITAL STATUS
1491  * 
1492  * build a dropdown with marital status
1493  * 
1494  * @param int $selected - id for selected record
1495  * @param string $name - the name/id for select form
1496  * @return void - just echo the html encoded string
1497  */
1498 function dropdown_marital($selected = 0, $name = 'status') {
1499     $string = "<select name='$name' id='$name'>";
1501     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1503     foreach ( $statii as $st ) {
1504         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1505         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1506     }
1508     $string .= '</select>';
1510     echo $string;
1513 // ----------------------------------------------------------------------------
1515  * DROPDOWN FOR PROVIDERS
1516  * 
1517  * build a dropdown with all providers
1518  * 
1519  * @param int $selected - id for selected record
1520  * @param string $name - the name/id for select form
1521  * @return void - just echo the html encoded string
1522  */
1523 function dropdown_providers($selected = 0, $name = 'status') {
1524     $provideri = getProviderInfo();
1526     $string = "<select name='$name' id='$name'>";
1527     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1528     foreach ( $provideri as $s ) {
1529         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1530         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1531     }
1533     $string .= '</select>';
1535     echo $string;
1538 // ----------------------------------------------------------------------------
1540  * DROPDOWN FOR INSURANCE COMPANIES
1541  * 
1542  * build a dropdown with all insurers
1543  * 
1544  * @param int $selected - id for selected record
1545  * @param string $name - the name/id for select form
1546  * @return void - just echo the html encoded string
1547  */
1548 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1549     $insurancei = getInsuranceProviders();
1551     $string = "<select name='$name' id='$name'>";
1552     $string .= '<option value="0">Onbekend</option>';
1553     foreach ( $insurancei as $iid => $iname ) {
1554         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1555         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1556     }
1558     $string .= '</select>';
1560     echo $string;
1564 // ----------------------------------------------------------------------------
1566  * COUNTRY CODE
1567  * 
1568  * return the name or the country code, function of arguments
1569  * 
1570  * @param int $country_code
1571  * @param string $country_name
1572  * @return string | int - name or code
1573  */
1574 function country_code($country_code = 0, $country_name = '') {
1575     $strint = '';
1576     if ( $country_code ) {
1577         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1578     } else {
1579         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1580     }
1582     $db = $GLOBALS['adodb']['db'];
1583     $result = $db->Execute($sql);
1584     if ($result && !$result->EOF) {
1585         $strint = $result->fields['res'];
1586     }
1588     return $strint;
1591 function DBToDate ($date)
1593     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1594     return $date;
1598  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1599  * for the given patient on the given date.
1601  * @param int     The PID of the patient.
1602  * @param string  Date in yyyy-mm-dd format.
1603  * @return array  Array of 0-3 insurance_data rows.
1604  */
1605 function getEffectiveInsurances($patient_id, $encdate) {
1606   $insarr = array();
1607   foreach (array('primary','secondary','tertiary') as $instype) {
1608     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1609       "WHERE pid = ? AND type = ? " .
1610       "AND date <= ? ORDER BY date DESC LIMIT 1",
1611       array($patient_id, $instype, $encdate));
1612     if (empty($tmp['provider'])) break;
1613     $insarr[] = $tmp;
1614   }
1615   return $insarr;
1619  * Get the patient's balance due. Normally this excludes amounts that are out
1620  * to insurance.  If you want to include what insurance owes, set the second
1621  * parameter to true.
1623  * @param int     The PID of the patient.
1624  * @param boolean Indicates if amounts owed by insurance are to be included.
1625  * @return number The balance.
1626  */
1627 function get_patient_balance($pid, $with_insurance=false) {
1628   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1629     $balance = 0;
1630     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1631       "last_level_closed, stmt_count " .
1632       "FROM form_encounter WHERE pid = ?", array($pid));
1633     while ($ferow = sqlFetchArray($feres)) {
1634       $encounter = $ferow['encounter'];
1635       $dos = substr($ferow['date'], 0, 10);
1636       $insarr = getEffectiveInsurances($pid, $dos);
1637       $inscount = count($insarr);
1638       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1639         // It's out to insurance so only the co-pay might be due.
1640         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1641           "pid = ? AND encounter = ? AND " .
1642           "code_type = 'copay' AND activity = 1",
1643           array($pid, $encounter));
1644         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1645           "FROM ar_activity WHERE " .
1646           "pid = ? AND encounter = ? AND payer_type = 0",
1647           array($pid, $encounter));
1648         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1649         if ($ptbal > 0) $balance += $ptbal;
1650       }
1651       else {
1652         // Including insurance or not out to insurance, everything is due.
1653         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1654           "pid = ? AND encounter = ? AND " .
1655           "activity = 1", array($pid, $encounter));
1656         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1657           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1658           "pid = ? AND encounter = ?", array($pid, $encounter));
1659         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1660           "pid = ? AND encounter = ?", array($pid, $encounter));
1661         $balance += $brow['amount'] + $srow['amount']
1662           - $drow['payments'] - $drow['adjustments'];
1663       }
1664     }
1665     return sprintf('%01.2f', $balance);
1666   }
1667   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1668     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1669     $conn = $GLOBALS['adodb']['db'];
1670     $customer_info['id'] = 0;
1671     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1672       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1673       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1674       "im.foreign_table = 'customer'";
1675     $result = $conn->Execute($sql);
1676     if($result && !$result->EOF) {
1677       $customer_info['id'] = $result->fields['foreign_id'];
1678     }
1679     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1680     $ws = new WSWrapper($function);
1681     if(is_numeric($ws->value)) {
1682       return sprintf('%01.2f', $ws->value);
1683     }
1684   }
1685   return '';
1688 // Function to check if patient is deceased.
1689 //  Param:
1690 //    $pid  - patient id
1691 //    $date - date checking if deceased (will default to current date if blank)
1692 //  Return:
1693 //    If deceased, then will return the number of
1694 //      days that patient has been deceased.
1695 //    If not deceased, then will return false.
1696 function is_patient_deceased($pid,$date='') {
1698   // Set date to current if not set
1699   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1701   // Query for deceased status (gets days deceased if patient is deceased)
1702   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1703                       "FROM `patient_data` " .
1704                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1706   if (empty($results)) {
1707     // Patient is alive, so return false
1708     return false;
1709   }
1710   else {
1711     // Patient is dead, so return the number of days patient has been deceased.
1712     //  Don't let it be zero days or else will confuse calls to this function.
1713     if ($results['days_deceased'] === 0) {
1714       $results['days_deceased'] = 1;
1715     }
1716     return $results['days_deceased'];
1717   }