minor fix in hover for prior commit
[openemr.git] / library / patient.inc
blob45cc39bd6a0118c183f3bfcdd5fdfd73a7b3c6e9
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("{$GLOBALS['srcdir']}/formdata.inc.php");
14 // These are for sports team use:
15 $PLAYER_FITNESSES = array(
16   xl('Full Play'),
17   xl('Full Training'),
18   xl('Restricted Training'),
19   xl('Injured Out'),
20   xl('Rehabilitation'),
21   xl('Illness'),
22   xl('International Duty')
24 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
26 // Hard-coding this array because its values and meanings are fixed by the 837p
27 // standard and we don't want people messing with them.
28 $policy_types = array(
29   ''   => xl('N/A'),
30   '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
31   '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
32   '14' => xl('No-fault Insurance including Auto is Primary'),
33   '15' => xl('Worker`s Compensation'),
34   '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
35   '41' => xl('Black Lung'),
36   '42' => xl('Veteran`s Administration'),
37   '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
38   '47' => xl('Other Liability Insurance is Primary'),
41 /**
42  * Get a patient's demographic data.
43  *
44  * @param int    $pid   The PID of the patient
45  * @param string $given an optional subsection of the patient's demographic
46  *                      data to retrieve.
47  * @return array The requested subsection of a patient's demographic data.
48  *               If no subsection was given, returns everything, with the
49  *               date of birth as the last field.
50  */
51 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
52     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
53     return sqlQuery($sql, array($pid) );
56 function getLanguages() {
57     $returnval = array('','english');
58     $sql = "select distinct lower(language) as language from patient_data";
59     $rez = sqlStatement($sql);
60     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
61         if (($row["language"] != "english") && ($row["language"] != "")) {
62             array_push($returnval, $row["language"]);
63         }
64     }
65     return $returnval;
68 function getInsuranceProvider($ins_id) {
69     
70     $sql = "select name from insurance_companies where id=?";
71     $row = sqlQuery($sql,array($ins_id));
72     return $row['name'];
73     
76 function getInsuranceProviders() {
77     $returnval = array();
79     if (true) {
80         $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
81         $rez = sqlStatement($sql);
82         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
83             $returnval[$row['id']] = $row['name'];
84         }
85     }
87     // Please leave this here. I have a user who wants to see zip codes and PO
88     // box numbers listed along with the insurance company names, as many companies
89     // have different billing addresses for different plans.  -- Rod Roark
90     //
91     else {
92         $sql = "select insurance_companies.name, insurance_companies.id, " .
93           "addresses.zip, addresses.line1 " .
94           "from insurance_companies, addresses " .
95           "where addresses.foreign_id = insurance_companies.id " .
96           "order by insurance_companies.name, addresses.zip";
98         $rez = sqlStatement($sql);
100         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
101             preg_match("/\d+/", $row['line1'], $matches);
102             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
103               "," . $matches[0] . ")";
104         }
105     }
107     return $returnval;
110 function getInsuranceProvidersExtra() {
111     $returnval = array();
112 // add a global and if for where to allow inactive inscompanies
114         $sql = "select insurance_companies.name, insurance_companies.id, " .
115           "addresses.zip, addresses.line1, addresses.state " .
116           "from insurance_companies, addresses " .
117           "where addresses.foreign_id = insurance_companies.id " .
118                   "and insurance_companies.inactive != 1 "  .
119           "order by insurance_companies.name, addresses.zip";
121         $rez = sqlStatement($sql);
123         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
124     switch ($GLOBALS['insurance_information']) {
125         case $GLOBALS['insurance_information'] = '0':
126             $returnval[$row['id']] = $row['name'];
127         break;
128         case $GLOBALS['insurance_information'] = '1':
129             $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
130         break; 
131         case $GLOBALS['insurance_information'] = '2':
132            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";      
133         break;
134         case $GLOBALS['insurance_information'] = '3':
135            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
136         break; 
137         case $GLOBALS['insurance_information'] = '4':
138                $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
139            "," . $row['zip'] . ")";
140         break;
141         case $GLOBALS['insurance_information'] = '5':
142             preg_match("/\d+/", $row['line1'], $matches);
143             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
144               "," . $matches[0] . ")";
145         break; 
146         }
147     }
149     return $returnval;
152 function getProviders() {
153     $returnval = array("");
154     $sql = "select fname, lname, suffix from users where authorized = 1 and " .
155         "active = 1 and username != ''";
156     $rez = sqlStatement($sql);
157     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
158         if (($row["fname"] != "") && ($row["lname"] != "")) {
159           if ($row["suffix"] != "") $row["lname"] .= ", ".$row["suffix"];
160             array_push($returnval, $row["fname"] . " " . $row["lname"]);
161         }
162     }
163     return $returnval;
166 // ----------------------------------------------------------------------------
167 // Get one facility row.  If the ID is not specified, then get either the
168 // "main" (billing) facility, or the default facility of the currently
169 // logged-in user.  This was created to support genFacilityTitle() but
170 // may find additional uses.
172 function getFacility($facid=0) {
174   //create a sql binding array
175   $sqlBindArray = array();
176   
177   if ($facid > 0) {
178     $query = "SELECT * FROM facility WHERE id = ?";
179     array_push($sqlBindArray,$facid);
180   }
181   else if ($facid == 0) {
182     $query = "SELECT * FROM facility ORDER BY " .
183       "billing_location DESC, service_location, id LIMIT 1";
184   }
185   else {
186     $query = "SELECT facility.* FROM users, facility WHERE " .
187       "users.id = ? AND " .
188       "facility.id = users.facility_id";
189     array_push($sqlBindArray,$_SESSION['authUserID']);
190   }
191   return sqlQuery($query,$sqlBindArray);
194 // Generate a report title including report name and facility name, address
195 // and phone.
197 function genFacilityTitle($repname='', $facid=0) {
198   $s = '';
199   $s .= "<table class='ftitletable'>\n";
200   $s .= " <tr>\n";
201   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
202   $s .= "  <td class='ftitlecell2'>\n";
203   $r = getFacility($facid);
204   if (!empty($r)) {
205     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
206     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
207     if ($r['city'] || $r['state'] || $r['postal_code']) {
208       $s .= "<br />";
209       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
210       if ($r['state']) {
211         if ($r['city']) $s .= ", \n";
212         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
213       }
214       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
215       $s .= "\n";
216     }
217     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
218     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
219   }
220   $s .= "  </td>\n";
221   $s .= " </tr>\n";
222   $s .= "</table>\n";
223   return $s;
227 GET FACILITIES
229 returns all facilities or just the id for the first one
230 (FACILITY FILTERING (lemonsoftware))
232 @param string - if 'first' return first facility ordered by id
233 @return array | int for 'first' case
235 function getFacilities($first = '') {
236     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
237     $ret = array();
238     while ( $row = sqlFetchArray($r) ) {
239        $ret[] = $row;
242         if ( $first == 'first') {
243             return $ret[0]['id'];
244         } else {
245             return $ret;
246         }
250 GET SERVICE FACILITIES
252 returns all service_location facilities or just the id for the first one
253 (FACILITY FILTERING (CHEMED))
255 @param string - if 'first' return first facility ordered by id
256 @return array | int for 'first' case
258 function getServiceFacilities($first = '') {
259     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
260     $ret = array();
261     while ( $row = sqlFetchArray($r) ) {
262        $ret[] = $row;
265         if ( $first == 'first') {
266             return $ret[0]['id'];
267         } else {
268             return $ret;
269         }
272 //(CHEMED) facility filter
273 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
274     $param1 = "";
275     if ($providers_only === 'any') {
276       $param1 = " AND authorized = 1 AND active = 1 ";
277     }
278     else if ($providers_only) {
279       $param1 = " AND authorized = 1 AND calendar = 1 ";
280     }
282     //--------------------------------
283     //(CHEMED) facility filter
284     $param2 = "";
285     if ($facility) {
286       if ($GLOBALS['restrict_user_facility']) {
287         $param2 = " AND (facility_id = $facility 
288           OR  $facility IN
289                 (select facility_id 
290                 from users_facility
291                 where tablename = 'users'
292                 and table_id = id)
293                 )
294           ";
295       }
296       else {
297         $param2 = " AND facility_id = $facility ";
298       }
299     }
300     //--------------------------------
302     $command = "=";
303     if ($providerID == "%") {
304         $command = "like";
305     }
306     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
307         "from users where username != '' and active = 1 and id $command '" .
308         add_escape_custom($providerID) . "' " . $param1 . $param2;
309     // sort by last name -- JRM June 2008
310     $query .= " ORDER BY lname, fname ";
311     $rez = sqlStatement($query);
312     for($iter=0; $row=sqlFetchArray($rez); $iter++)
313         $returnval[$iter]=$row;
315     //if only one result returned take the key/value pairs in array [0] and merge them down into
316     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
318     if($iter==1) {
319         $akeys = array_keys($returnval[0]);
320         foreach($akeys as $key) {
321             $returnval[0][$key] = $returnval[0][$key];
322         }
323     }
324     return $returnval;
327 //same as above but does not reduce if only 1 row returned
328 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
329     $param1 = "";
330     if ($providers_only) {
331         $param1 = "AND authorized=1";
332     }
333     $command = "=";
334     if ($providerID == "%") {
335         $command = "like";
336     }
337     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
338         "from users where active = 1 and username != '' and id $command '" .
339         add_escape_custom($providerID) . "' " . $param1;
341     $rez = sqlStatement($query);
342     for($iter=0; $row=sqlFetchArray($rez); $iter++)
343         $returnval[$iter]=$row;
345     return $returnval;
348 function getProviderName($providerID) {
349     $pi = getProviderInfo($providerID, 'any');
350     if (strlen($pi[0]["lname"]) > 0) {
351       if (strlen($pi[0]["suffix"]) > 0) $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
352         return $pi[0]['fname'] . " " . $pi[0]['lname'];
353     }
354     return "";
357 function getProviderId($providerName) {
358     $query = "select id from users where username = ?";
359     $rez = sqlStatement($query, array($providerName) );
360     for($iter=0; $row=sqlFetchArray($rez); $iter++)
361         $returnval[$iter]=$row;
362     return $returnval;
365 function getEthnoRacials() {
366     $returnval = array("");
367     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
368     $rez = sqlStatement($sql);
369     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
370         if (($row["ethnoracial"] != "")) {
371             array_push($returnval, $row["ethnoracial"]);
372         }
373     }
374     return $returnval;
377 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
380     if ($dateStart && $dateEnd) {
381         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
382     }
383     else if ($dateStart && !$dateEnd) {
384         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
385     }
386     else if (!$dateStart && $dateEnd) {
387         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
388     }
389     else {
390         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
391     }
392     
393     if($given == 'tobacco'){
394         $res = sqlQuery("select $given from history_data where pid = ? and tobacco is not null and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
395     }
397     return $res;
400 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
401 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
403   $sql = "select $given from insurance_data as insd " .
404     "left join insurance_companies as ic on ic.id = insd.provider " .
405     "where pid = ? and type = ? order by date DESC limit 1";
406   return sqlQuery($sql, array($pid, $type) );
409 function getInsuranceDataByDate($pid, $date, $type,
410   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
411 { // this must take the date in the following manner: YYYY-MM-DD
412   // this function recalls the insurance value that was most recently enterred from the
413   // given date. it will call up most recent records up to and on the date given,
414   // but not records enterred after the given date
415   $sql = "select $given from insurance_data as insd " .
416     "left join insurance_companies as ic on ic.id = provider " .
417     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
418     "type=? order by date DESC limit 1";
419   return sqlQuery($sql, array($pid,$date,$type) );
422 function getEmployerData($pid, $given = "*")
424     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
425     return sqlQuery($sql, array($pid) );
428 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
429   // When the limit is exceeded, find out what the unlimited count would be.
430   $GLOBALS['PATIENT_INC_COUNT'] = $count;
431   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
432   if ($limit != "all") {
433     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
434     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
435   }
439  * Allow the last name to be followed by a comma and some part of a first name(can
440  *   also place middle name after the first name with a space separating them)
441  * Allows comma alone followed by some part of a first name(can also place middle name
442  *   after the first name with a space separating them).
443  * Allows comma alone preceded by some part of a last name.
444  * If no comma or space, then will search both last name and first name.
445  * If the first letter of either name is capital, searches for name starting
446  *   with given substring (the expected behavior). If it is lower case, it
447  *   searches for the substring anywhere in the name. This applies to either
448  *   last name, first name, and middle name.
449  * Also allows first name followed by middle and/or last name when separated by spaces.
450  * @param string $term
451  * @param string $given
452  * @param string $orderby
453  * @param string $limit
454  * @param string $start
455  * @return array
456  */
457 function getPatientLnames($term = "%", $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")
459     $names = getPatientNameSplit($term);
460     
461     foreach ($names as $key => $val) {
462       if (!empty($val)) {
463         if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
464             $names[$key] = '%' . $val . '%';            
465         } else { 
466             $names[$key] = $val . '%';            
467         }
468       }
469     }
471     // Debugging section below
472     //if(array_key_exists('first',$names)) {
473     //    error_log("first name search term :".$names['first']);
474     //}
475     //if(array_key_exists('middle',$names)) {
476     //    error_log("middle name search term :".$names['middle']);
477     //}
478     //if(array_key_exists('last',$names)) {
479     //    error_log("last name search term :".$names['last']);
480     //}
481     // Debugging section above
483     $sqlBindArray = array();
484     if(array_key_exists('last',$names) && $names['last'] == '') {
485         // Do not search last name
486         $where = "fname LIKE ? ";
487         array_push($sqlBindArray, $names['first']);
488         if ($names['middle'] != '') {        
489             $where .= "AND mname LIKE ? ";  
490             array_push($sqlBindArray, $names['middle']);
491         }
492     } elseif(array_key_exists('first',$names) && $names['first'] == '') {
493         // Do not search first name or middle name
494         $where = "lname LIKE ? ";
495         array_push($sqlBindArray, $names['last']);
496     } elseif($names['first'] == '' && $names['last'] != '') {
497         // Search both first name and last name with same term
498         $names['first'] = $names['last']; 
499         $where = "lname LIKE ? OR fname LIKE ? ";
500         array_push($sqlBindArray, $names['last'], $names['first']);
501     } elseif ($names['middle'] != '') {        
502         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";  
503         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
504     } else {
505         $where = "lname LIKE ? AND fname LIKE ? ";
506         array_push($sqlBindArray, $names['last'], $names['first']);
507     }
509         if (!empty($GLOBALS['pt_restrict_field'])) {
510                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
511                         $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
512                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
513                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
514                         array_push($sqlBindArray, $_SESSION{"authUser"});
515                 }
516         }
518     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
519     if ($limit != "all") $sql .= " LIMIT $start, $limit";
521     $rez = sqlStatement($sql, $sqlBindArray);
523     $returnval=array();
524     for($iter=0; $row=sqlFetchArray($rez); $iter++)
525         $returnval[$iter] = $row;
527     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
528     return $returnval;
531  * Accept a string used by a search function expected to find a patient name, 
532  * then split up the string if a comma or space exists. Return an array having 
533  * from 1 to 3 elements, named first, middle, and last.
534  * See above getPatientLnames() function for details on how the splitting occurs.
535  * @param string $term
536  * @return array
537  */
538 function getPatientNameSplit($term) {
539     $term = trim($term);
540     if (strpos($term, ',') !== false) {
541         $names = explode(',', $term);        
542         $n['last'] = $names[0];
543         if (strpos(trim($names[1]), ' ') !== false) {
544             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
545         } else {
546             $n['first'] = $names[1];
547         }
548     } elseif (strpos($term, ' ') !== false) {
549         $names = explode(' ', $term);
550         if (count($names) == 1) {
551             $n['last'] = $names[0];
552         } elseif (count($names) == 3) {
553             $n['first'] = $names[0];
554             $n['middle'] = $names[1];
555             $n['last'] = $names[2];
556         } else {
557             // This will handle first and last name or first followed by 
558             // multiple names only using just the last of the names in the list.
559             $n['first'] = $names[0];
560             $n['last'] = end($names);
561         }
562     } else {
563         $n['last'] = $term;
564         if(empty($n['last'])) $n['last'] = '%';
565     }
566     // Trim whitespace off the names before returning
567     foreach($n as $key => $val) {
568         $n[$key] = trim($val);
569     }
570     return $n; // associative array containing names
573 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")
576     $sqlBindArray = array();
577     $where = "pubpid LIKE ? ";
578     array_push($sqlBindArray, $pid."%");
579         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
580                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
581                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
582                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
583                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
584                         array_push($sqlBindArray, $_SESSION{"authUser"});
585                 }
586         }
588     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
589     if ($limit != "all") $sql .= " limit $start, $limit";
590     $rez = sqlStatement($sql, $sqlBindArray);
591     for($iter=0; $row=sqlFetchArray($rez); $iter++)
592         $returnval[$iter]=$row;
594     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
595     return $returnval;
598 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")
600   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
602   $sqlBindArray = array();
603   $where = "";
604   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
605     if ( $iter > 0 ) {
606       $where .= " or ";
607     }
608     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
609     array_push($sqlBindArray, "%".$searchTerm."%");
610   }
612   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
613   if ($limit != "all") $sql .= " limit $start, $limit";
614   $rez = sqlStatement($sql, $sqlBindArray);
615   for($iter=0; $row=sqlFetchArray($rez); $iter++)
616     $returnval[$iter]=$row;
617   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
618   return $returnval;
621 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
622   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
623   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
625         $layoutCols = explode( '~', $searchFields );
626   $sqlBindArray = array();
627   $where = "";
628   $i = 0;
629   foreach ($layoutCols as $val) {
630     if (empty($val)) continue;
631                 if ( $i > 0 ) {
632                    $where .= " or ";
633                 }
634     if ($val == 'pid') {
635                 $where .= " ".add_escape_custom($val)." = ? ";
636                 array_push($sqlBindArray, $searchTerm);
637     }
638     else {
639                 $where .= " ".add_escape_custom($val)." like ? ";
640                 array_push($sqlBindArray, $searchTerm."%");
641     }
642                 $i++;
643         }
645   // If no search terms, ensure valid syntax.
646   if ($i == 0) $where = "1 = 1";
648   // If a non-empty service code was given, then restrict to patients who
649   // have been provided that service.  Since the code is used in a LIKE
650   // clause, % and _ wildcards are supported.
651   if ($search_service_code) {
652     $where = "( $where ) AND " .
653       "( SELECT COUNT(*) FROM billing AS b WHERE " .
654       "b.pid = patient_data.pid AND " .
655       "b.activity = 1 AND " .
656       "b.code_type != 'COPAY' AND " .
657       "b.code LIKE ? " .
658       ") > 0";
659     array_push($sqlBindArray, $search_service_code);
660   }
662   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
663   if ($limit != "all") $sql .= " limit $start, $limit";
664   $rez = sqlStatement($sql, $sqlBindArray);
665   for($iter=0; $row=sqlFetchArray($rez); $iter++)
666       $returnval[$iter]=$row;
667   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
668   return $returnval;
671 // return a collection of Patient PIDs
672 // new arg style by JRM March 2008
673 // 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")
674 function getPatientPID($args)
676     $pid = "%";
677     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
678     $orderby = "lname ASC, fname ASC";
679     $limit="all";
680     $start="0";
682     // alter default values if defined in the passed in args
683     if (isset($args['pid'])) { $pid = $args['pid']; }
684     if (isset($args['given'])) { $given = $args['given']; }
685     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
686     if (isset($args['limit'])) { $limit = $args['limit']; }
687     if (isset($args['start'])) { $start = $args['start']; }
689     $command = "=";
690     if ($pid == -1) $pid = "%";
691     elseif (empty($pid)) $pid = "NULL";
693     if (strstr($pid,"%")) $command = "like";
695     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
696     if ($limit != "all") $sql .= " limit $start, $limit";
698     $rez = sqlStatement($sql);
699     for($iter=0; $row=sqlFetchArray($rez); $iter++)
700         $returnval[$iter]=$row;
702     return $returnval;
705 /* return a patient's name in the format LAST, FIRST */
706 function getPatientName($pid) {
707     if (empty($pid)) return "";
708     $patientData = getPatientPID(array("pid"=>$pid));
709     if (empty($patientData[0]['lname'])) return "";
710     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
711     return $patientName;
714 /* find patient data by DOB */
715 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
717     $DOB = fixDate($DOB, $DOB);
718     $sqlBindArray = array();
719     $where = "DOB like ? ";
720     array_push($sqlBindArray, $DOB."%");
721         if (!empty($GLOBALS['pt_restrict_field'])) {
722                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
723                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
724                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
725                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
726                         array_push($sqlBindArray, $_SESSION{"authUser"});
727                 }
728         }
730     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
732     if ($limit != "all") $sql .= " LIMIT $start, $limit";
734     $rez = sqlStatement($sql, $sqlBindArray);
735     for($iter=0; $row=sqlFetchArray($rez); $iter++)
736         $returnval[$iter]=$row;
738     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
739     return $returnval;
742 /* find patient data by SSN */
743 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
745     $sqlBindArray = array();
746     $where = "ss LIKE ?";
747     array_push($sqlBindArray, $ss."%");
748     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
749     if ($limit != "all") $sql .= " LIMIT $start, $limit";
751     $rez = sqlStatement($sql, $sqlBindArray);
752     for($iter=0; $row=sqlFetchArray($rez); $iter++)
753         $returnval[$iter]=$row;
755     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
756     return $returnval;
759 //(CHEMED) Search by phone number
760 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
762     $phone = preg_replace( "/[[:punct:]]/","", $phone );
763     $sqlBindArray = array();
764     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
765     array_push($sqlBindArray, $phone);
766     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
767     if ($limit != "all") $sql .= " LIMIT $start, $limit";
769     $rez = sqlStatement($sql, $sqlBindArray);
770     for($iter=0; $row=sqlFetchArray($rez); $iter++)
771         $returnval[$iter]=$row;
773     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
774     return $returnval;
777 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
779     $sql="select $given from patient_data order by $orderby";
781     if ($limit != "all")
782         $sql .= " limit $start, $limit";
784     $rez = sqlStatement($sql);
785     for($iter=0; $row=sqlFetchArray($rez); $iter++)
786         $returnval[$iter]=$row;
788     return $returnval;
791 //----------------------input functions
792 function newPatientData(    $db_id="",
793                 $title = "",
794                 $fname = "",
795                 $lname = "",
796                 $mname = "",
797                 $sex = "",
798                 $DOB = "",
799                 $street = "",
800                 $postal_code = "",
801                 $city = "",
802                 $state = "",
803                 $country_code = "",
804                 $ss = "",
805                 $occupation = "",
806                 $phone_home = "",
807                 $phone_biz = "",
808                 $phone_contact = "",
809                 $status = "",
810                 $contact_relationship = "",
811                 $referrer = "",
812                 $referrerID = "",
813                 $email = "",
814                 $language = "",
815                 $ethnoracial = "",
816                 $interpretter = "",
817                 $migrantseasonal = "",
818                 $family_size = "",
819                 $monthly_income = "",
820                 $homeless = "",
821                 $financial_review = "",
822                 $pubpid = "",
823                 $pid = "MAX(pid)+1",
824                 $providerID = "",
825                 $genericname1 = "",
826                 $genericval1 = "",
827                 $genericname2 = "",
828                 $genericval2 = "",
829                 $billing_note="",
830                 $phone_cell = "",
831                 $hipaa_mail = "",
832                 $hipaa_voice = "",
833                 $squad = 0,
834                 $pharmacy_id = 0,
835                 $drivers_license = "",
836                 $hipaa_notice = "",
837                 $hipaa_message = "",
838                 $regdate = ""
839             )
841     $DOB = fixDate($DOB);
842     $regdate = fixDate($regdate);
844     $fitness = 0;
845     $referral_source = '';
846     if ($pid) {
847         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
848         // Check for brain damage:
849         if ($db_id != $rez['id']) {
850             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
851               $rez['id'] . "' to '$db_id' for pid '$pid'";
852             die($errmsg);
853         }
854         $fitness = $rez['fitness'];
855         $referral_source = $rez['referral_source'];
856     }
858     // Get the default price level.
859     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
860       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
861     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
863     $query = ("replace into patient_data set
864         id='$db_id',
865         title='$title',
866         fname='$fname',
867         lname='$lname',
868         mname='$mname',
869         sex='$sex',
870         DOB='$DOB',
871         street='$street',
872         postal_code='$postal_code',
873         city='$city',
874         state='$state',
875         country_code='$country_code',
876         drivers_license='$drivers_license',
877         ss='$ss',
878         occupation='$occupation',
879         phone_home='$phone_home',
880         phone_biz='$phone_biz',
881         phone_contact='$phone_contact',
882         status='$status',
883         contact_relationship='$contact_relationship',
884         referrer='$referrer',
885         referrerID='$referrerID',
886         email='$email',
887         language='$language',
888         ethnoracial='$ethnoracial',
889         interpretter='$interpretter',
890         migrantseasonal='$migrantseasonal',
891         family_size='$family_size',
892         monthly_income='$monthly_income',
893         homeless='$homeless',
894         financial_review='$financial_review',
895         pubpid='$pubpid',
896         pid = $pid,
897         providerID = '$providerID',
898         genericname1 = '$genericname1',
899         genericval1 = '$genericval1',
900         genericname2 = '$genericname2',
901         genericval2 = '$genericval2',
902         billing_note= '$billing_note';
903         phone_cell = '$phone_cell',
904         pharmacy_id = '$pharmacy_id',
905         hipaa_mail = '$hipaa_mail',
906         hipaa_voice = '$hipaa_voice',
907         hipaa_notice = '$hipaa_notice',
908         hipaa_message = '$hipaa_message',
909         squad = '$squad',
910         fitness='$fitness',
911         referral_source='$referral_source',
912         regdate='$regdate',
913         pricelevel='$pricelevel',
914         date=NOW()");
916     $id = sqlInsert($query);
918     if ( !$db_id ) {
919       // find the last inserted id for new patient case
920       $db_id = getSqlLastID();
921     }
923     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
925     return $foo['pid'];
928 // Supported input date formats are:
929 //   mm/dd/yyyy
930 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
931 //   yyyy/mm/dd
932 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
934 function fixDate($date, $default="0000-00-00") {
935     $fixed_date = $default;
936     $date = trim($date);
937     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
938         $dmy = preg_split("'[/.-]'", $date);
939         if ($dmy[0] > 99) {
940             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
941         } else {
942             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
943               if ($dmy[2] < 1000) $dmy[2] += 1900;
944               if ($dmy[2] < 1910) $dmy[2] += 100;
945             }
946             // phone_country_code indicates format of ambiguous input dates.
947             if ($GLOBALS['phone_country_code'] == 1)
948               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
949             else
950               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
951         }
952     }
954     return $fixed_date;
957 function pdValueOrNull($key, $value) {
958   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
959     substr($key, 0, 8) == 'userdate') &&
960     (empty($value) || $value == '0000-00-00'))
961   {
962     return "NULL";
963   }
964   else {
965     return "'$value'";
966   }
969 // Create or update patient data from an array.
971 function updatePatientData($pid, $new, $create=false)
973   /*******************************************************************
974     $real = getPatientData($pid);
975     $new['DOB'] = fixDate($new['DOB']);
976     while(list($key, $value) = each ($new))
977         $real[$key] = $value;
978     $real['date'] = "'+NOW()+'";
979     $real['id'] = "";
980     $sql = "insert into patient_data set ";
981     while(list($key, $value) = each($real))
982         $sql .= $key." = '$value', ";
983     $sql = substr($sql, 0, -2);
984     return sqlInsert($sql);
985   *******************************************************************/
987   // The above was broken, though seems intent to insert a new patient_data
988   // row for each update.  A good idea, but nothing is doing that yet so
989   // the code below does not yet attempt it.
991   $new['DOB'] = fixDate($new['DOB']);
993   if ($create) {
994     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
995     foreach ($new as $key => $value) {
996       if ($key == 'id') continue;
997       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
998     }
999     $db_id = sqlInsert($sql);
1000   }
1001   else {
1002     $db_id = $new['id'];
1003     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1004     // Check for brain damage:
1005     if ($pid != $rez['pid']) {
1006       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1007         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1008       die($errmsg);
1009     }
1010     $sql = "UPDATE patient_data SET date = NOW()";
1011     foreach ($new as $key => $value) {
1012       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1013     }
1014     $sql .= " WHERE id = '$db_id'";
1015     sqlStatement($sql);
1016   }
1018   return $db_id;
1021 function newEmployerData(    $pid,
1022                 $name = "",
1023                 $street = "",
1024                 $postal_code = "",
1025                 $city = "",
1026                 $state = "",
1027                 $country = ""
1028             )
1030     return sqlInsert("insert into employer_data set
1031         name='$name',
1032         street='$street',
1033         postal_code='$postal_code',
1034         city='$city',
1035         state='$state',
1036         country='$country',
1037         pid='$pid',
1038         date=NOW()
1039         ");
1042 // Create or update employer data from an array.
1044 function updateEmployerData($pid, $new, $create=false)
1046   $colnames = array('name','street','city','state','postal_code','country');
1048   if ($create) {
1049     $set .= "pid = '$pid', date = NOW()";
1050     foreach ($colnames as $key) {
1051       $value = isset($new[$key]) ? $new[$key] : '';
1052       $set .= ", `$key` = '$value'";
1053     }
1054     return sqlInsert("INSERT INTO employer_data SET $set");
1055   }
1056   else {
1057     $set = '';
1058     $old = getEmployerData($pid);
1059     $modified = false;
1060     foreach ($colnames as $key) {
1061       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1062       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1063         $value = $new[$key];
1064         $modified = true;
1065       }
1066       $set .= "`$key` = '$value', ";
1067     }
1068     if ($modified) {
1069       $set .= "pid = '$pid', date = NOW()";
1070       return sqlInsert("INSERT INTO employer_data SET $set");
1071     }
1072     return $old['id'];
1073   }
1076 // This updates or adds the given insurance data info, while retaining any
1077 // previously added insurance_data rows that should be preserved.
1078 // This does not directly support the maintenance of non-current insurance.
1080 function newInsuranceData(
1081   $pid,
1082   $type = "",
1083   $provider = "",
1084   $policy_number = "",
1085   $group_number = "",
1086   $plan_name = "",
1087   $subscriber_lname = "",
1088   $subscriber_mname = "",
1089   $subscriber_fname = "",
1090   $subscriber_relationship = "",
1091   $subscriber_ss = "",
1092   $subscriber_DOB = "",
1093   $subscriber_street = "",
1094   $subscriber_postal_code = "",
1095   $subscriber_city = "",
1096   $subscriber_state = "",
1097   $subscriber_country = "",
1098   $subscriber_phone = "",
1099   $subscriber_employer = "",
1100   $subscriber_employer_street = "",
1101   $subscriber_employer_city = "",
1102   $subscriber_employer_postal_code = "",
1103   $subscriber_employer_state = "",
1104   $subscriber_employer_country = "",
1105   $copay = "",
1106   $subscriber_sex = "",
1107   $effective_date = "0000-00-00",
1108   $accept_assignment = "TRUE",
1109   $policy_type = "")
1111   if (strlen($type) <= 0) return FALSE;
1113   // If a bad date was passed, err on the side of caution.
1114   $effective_date = fixDate($effective_date, date('Y-m-d'));
1116   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1117     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1118   $idrow = sqlFetchArray($idres);
1120   // Replace the most recent entry in any of the following cases:
1121   // * Its effective date is >= this effective date.
1122   // * It is the first entry and it has no (insurance) provider.
1123   // * There is no encounter that is earlier than the new effective date but
1124   //   on or after the old effective date.
1125   // Otherwise insert a new entry.
1127   $replace = false;
1128   if ($idrow) {
1129     if (strcmp($idrow['date'], $effective_date) > 0) {
1130       $replace = true;
1131     }
1132     else {
1133       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1134         $replace = true;
1135       }
1136       else {
1137         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1138           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1139           "date >= '" . $idrow['date'] . " 00:00:00'");
1140         if ($ferow['count'] == 0) $replace = true;
1141       }
1142     }
1143   }
1145   if ($replace) {
1147     // TBD: This is a bit dangerous in that a typo in entering the effective
1148     // date can wipe out previous insurance history.  So we want some data
1149     // entry validation somewhere.
1150     sqlStatement("DELETE FROM insurance_data WHERE " .
1151       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1152       "id != " . $idrow['id']);
1154     $data = array();
1155     $data['type'] = $type;
1156     $data['provider'] = $provider;
1157     $data['policy_number'] = $policy_number;
1158     $data['group_number'] = $group_number;
1159     $data['plan_name'] = $plan_name;
1160     $data['subscriber_lname'] = $subscriber_lname;
1161     $data['subscriber_mname'] = $subscriber_mname;
1162     $data['subscriber_fname'] = $subscriber_fname;
1163     $data['subscriber_relationship'] = $subscriber_relationship;
1164     $data['subscriber_ss'] = $subscriber_ss;
1165     $data['subscriber_DOB'] = $subscriber_DOB;
1166     $data['subscriber_street'] = $subscriber_street;
1167     $data['subscriber_postal_code'] = $subscriber_postal_code;
1168     $data['subscriber_city'] = $subscriber_city;
1169     $data['subscriber_state'] = $subscriber_state;
1170     $data['subscriber_country'] = $subscriber_country;
1171     $data['subscriber_phone'] = $subscriber_phone;
1172     $data['subscriber_employer'] = $subscriber_employer;
1173     $data['subscriber_employer_city'] = $subscriber_employer_city;
1174     $data['subscriber_employer_street'] = $subscriber_employer_street;
1175     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1176     $data['subscriber_employer_state'] = $subscriber_employer_state;
1177     $data['subscriber_employer_country'] = $subscriber_employer_country;
1178     $data['copay'] = $copay;
1179     $data['subscriber_sex'] = $subscriber_sex;
1180     $data['pid'] = $pid;
1181     $data['date'] = $effective_date;
1182     $data['accept_assignment'] = $accept_assignment;
1183     $data['policy_type'] = $policy_type;
1184     updateInsuranceData($idrow['id'], $data);
1185     return $idrow['id'];
1186   }
1187   else {
1188     return sqlInsert("INSERT INTO insurance_data SET
1189       type = '$type',
1190       provider = '$provider',
1191       policy_number = '$policy_number',
1192       group_number = '$group_number',
1193       plan_name = '$plan_name',
1194       subscriber_lname = '$subscriber_lname',
1195       subscriber_mname = '$subscriber_mname',
1196       subscriber_fname = '$subscriber_fname',
1197       subscriber_relationship = '$subscriber_relationship',
1198       subscriber_ss = '$subscriber_ss',
1199       subscriber_DOB = '$subscriber_DOB',
1200       subscriber_street = '$subscriber_street',
1201       subscriber_postal_code = '$subscriber_postal_code',
1202       subscriber_city = '$subscriber_city',
1203       subscriber_state = '$subscriber_state',
1204       subscriber_country = '$subscriber_country',
1205       subscriber_phone = '$subscriber_phone',
1206       subscriber_employer = '$subscriber_employer',
1207       subscriber_employer_city = '$subscriber_employer_city',
1208       subscriber_employer_street = '$subscriber_employer_street',
1209       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1210       subscriber_employer_state = '$subscriber_employer_state',
1211       subscriber_employer_country = '$subscriber_employer_country',
1212       copay = '$copay',
1213       subscriber_sex = '$subscriber_sex',
1214       pid = '$pid',
1215       date = '$effective_date',
1216       accept_assignment = '$accept_assignment',
1217       policy_type = '$policy_type'
1218     ");
1219   }
1222 // This is used internally only.
1223 function updateInsuranceData($id, $new)
1225   $fields = sqlListFields("insurance_data");
1226   $use = array();
1228   while(list($key, $value) = each ($new)) {
1229     if (in_array($key, $fields)) {
1230       $use[$key] = $value;
1231     }
1232   }
1234   $sql = "UPDATE insurance_data SET ";
1235   while(list($key, $value) = each($use))
1236     $sql .= "`$key` = '$value', ";
1237   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1239   sqlStatement($sql);
1242 function newHistoryData($pid, $new=false) {
1243   $arraySqlBind = array();
1244   $sql = "insert into history_data set pid = ?, date = NOW()";
1245   array_push($arraySqlBind,$pid);
1246   if ($new) {
1247     while(list($key, $value) = each($new)) {
1248       array_push($arraySqlBind,$value);
1249       $sql .= ", `$key` = ?";
1250     }
1251   }
1252   return sqlInsert($sql, $arraySqlBind );
1255 function updateHistoryData($pid,$new)
1257         $real = getHistoryData($pid);
1258         while(list($key, $value) = each ($new))
1259                 $real[$key] = $value;
1260         $real['id'] = "";
1261         // need to unset date, so can reset it below
1262         unset($real['date']);
1264         $arraySqlBind = array();
1265         $sql = "insert into history_data set `date` = NOW(), ";
1266         while(list($key, $value) = each($real)) {
1267                 array_push($arraySqlBind,$value);
1268                 $sql .= "`$key` = ?, ";
1269         }
1270         $sql = substr($sql, 0, -2);
1272         return sqlInsert($sql, $arraySqlBind );
1275 // Returns Age 
1276 //   in months if < 2 years old
1277 //   in years  if > 2 years old
1278 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1279 // (optional) nowYMD is a date in YYYYMMDD format
1280 function getPatientAge($dobYMD, $nowYMD=null)
1282     // strip any dashes from the DOB
1283     $dobYMD = preg_replace("/-/", "", $dobYMD);
1284     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1285     
1286     // set the 'now' date values
1287     if ($nowYMD == null) {
1288         $nowDay = date("d");
1289         $nowMonth = date("m");
1290         $nowYear = date("Y");
1291     }
1292     else {
1293         $nowDay = substr($nowYMD,6,2);
1294         $nowMonth = substr($nowYMD,4,2);
1295         $nowYear = substr($nowYMD,0,4);
1296     }
1298     $dayDiff = $nowDay - $dobDay;
1299     $monthDiff = $nowMonth - $dobMonth;
1300     $yearDiff = $nowYear - $dobYear;
1302     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1304     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1305     if($dayDiff<0) { $ageInMonths-=1; } 
1306     
1307     if ( $ageInMonths > 24 ) {
1308         $age = $yearDiff;
1309         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1310         else if ($monthDiff < 0) { $age -= 1; }
1311     }
1312     else  {
1313         $age = "$ageInMonths " . xl('month');
1314     }
1316     return $age;
1320  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1321  * format expected by getPatientAgeYMD
1323  * @param  string  $dob     date of birth
1324  * @param  string  $target  date to calculate age on
1325  * @return array containing
1326  *      age - decimal age in years
1327  *      age_in_months - decimal age in months
1328  *      ageinYMD - formatted string #y #m #d */
1329 function parseAgeInfo($dob,$target)
1331     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1332     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1333     // Prepare target (Y-M-D H:M:S)
1334     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1336     return getPatientAgeYMD($dateDOB,$dateTarget);
1341  * 
1342  * @param type $dob
1343  * @param type $date
1344  * @return array containing
1345  *      age - decimal age in years
1346  *      age_in_months - decimal age in months
1347  *      ageinYMD - formatted string #y #m #d
1348  */
1349 function getPatientAgeYMD($dob, $date=null) {
1350         
1351     if ($date == null) {
1352         $daynow = date("d");
1353         $monthnow = date("m");
1354         $yearnow = date("Y");
1355         $datenow=$yearnow.$monthnow.$daynow;
1356     }
1357     else {
1358         $datenow=preg_replace("/-/", "", $date);
1359         $yearnow=substr($datenow,0,4);
1360         $monthnow=substr($datenow,4,2);
1361         $daynow=substr($datenow,6,2);
1362         $datenow=$yearnow.$monthnow.$daynow;
1363     }
1365     $dob=preg_replace("/-/", "", $dob);
1366     $dobyear=substr($dob,0,4);
1367     $dobmonth=substr($dob,4,2);
1368     $dobday=substr($dob,6,2);
1369     $dob=$dobyear.$dobmonth.$dobday;
1371     //to compensate for 30, 31, 28, 29 days/month
1372     $mo=$monthnow; //to avoid confusion with later calculation
1374     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1375         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1376     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1377     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1378         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1379         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1380         else {$nd=28;} //otherwise, it is not a leap year.
1381     }
1382     else {$nd=31;} // other months have 31 days
1384     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1385     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1386     {
1387         $age_year = $yearnow - $dobyear - 1;
1388         if ($daynow < $dobday) {
1389             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1390             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1391         }
1392         else {
1393             $months_since_birthday=12 - $dobmonth + $monthnow;
1394             $days_since_dobday=$daynow - $dobday;
1395         }
1396     }
1397     else // if patient has had birthday this calandar year
1398     {
1399         $age_year = $yearnow - $dobyear;
1400         if ($daynow < $dobday) {
1401             $months_since_birthday=$monthnow - $dobmonth -1;
1402             $days_since_dobday=$nd - $dobday + $daynow;
1403         }
1404         else {
1405             $months_since_birthday=$monthnow - $dobmonth;
1406             $days_since_dobday=$daynow - $dobday;
1407         }       
1408     }
1409     
1410     $day_as_month_decimal = $days_since_dobday / 30;
1411     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1412     $month_as_year_decimal = $months_since_birthday_float / 12;
1413     $age_float = $age_year + $month_as_year_decimal;
1415     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1416     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1417     $age = round($age_float,2);
1419     // round the years to 2 floating points
1420     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1421     return compact('age','age_in_months','ageinYMD');
1424 // Returns Age in days
1425 //   in months if < 2 years old
1426 //   in years  if > 2 years old
1427 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1428 // (optional) nowYMD is a date in YYYYMMDD format
1429 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1430     $age = -1;
1432     // strip any dashes from the DOB
1433     $dobYMD = preg_replace("/-/", "", $dobYMD);
1434     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1435     
1436     // set the 'now' date values
1437     if ($nowYMD == null) {
1438         $nowDay = date("d");
1439         $nowMonth = date("m");
1440         $nowYear = date("Y");
1441     }
1442     else {
1443         $nowDay = substr($nowYMD,6,2);
1444         $nowMonth = substr($nowYMD,4,2);
1445         $nowYear = substr($nowYMD,0,4);
1446     }
1448     // do the date math
1449     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1450     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1451     $timediff = $nowtime - $dobtime;
1452     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1454     return $age;
1457  * Returns a string to be used to display a patient's age
1458  * 
1459  * @param type $dobYMD
1460  * @param type $asOfYMD
1461  * @return string suitable for displaying patient's age based on preferences
1462  */
1463 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1465     if($GLOBALS['age_display_format']=='1')
1466     {
1467         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1468         if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1469         {
1470             return $ageYMD['ageinYMD'];
1471         }
1472         else
1473         {
1474             return getPatientAge($dobYMD, $asOfYMD);                    
1475         }
1476     }
1477     else
1478     {
1479         return getPatientAge($dobYMD, $asOfYMD);
1480     }
1481     
1483 function dateToDB ($date)
1485     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1486     return $date;
1490 // ----------------------------------------------------------------------------
1492  * DROPDOWN FOR COUNTRIES
1493  * 
1494  * build a dropdown with all countries from geo_country_reference
1495  * 
1496  * @param int $selected - id for selected record
1497  * @param string $name - the name/id for select form
1498  * @return void - just echo the html encoded string
1499  */
1500 function dropdown_countries($selected = 0, $name = 'country_code') {
1501     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1503     $string = "<select name='$name' id='$name'>";
1504     while ( $row = sqlFetchArray($r) ) {
1505         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1506         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1507     }
1509     $string .= '</select>';
1510     echo $string;
1514 // ----------------------------------------------------------------------------
1516  * DROPDOWN FOR YES/NO
1517  * 
1518  * build a dropdown with two options (yes - 1, no - 0)
1519  * 
1520  * @param int $selected - id for selected record
1521  * @param string $name - the name/id for select form
1522  * @return void - just echo the html encoded string 
1523  */
1524 function dropdown_yesno($selected = 0, $name = 'yesno') {
1525     $string = "<select name='$name' id='$name'>";
1527     $selected = (int)$selected;
1528     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1529     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1531     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1532     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1533     $string .= '</select>';
1535     echo $string;
1538 // ----------------------------------------------------------------------------
1540  * DROPDOWN FOR MALE/FEMALE options
1541  * 
1542  * build a dropdown with three options (unselected/male/female)
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_sex($selected = 0, $name = 'sex') {
1549     $string = "<select name='$name' id='$name'>";
1551     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1552     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1553     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1555     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1556     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1557     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1558     $string .= '</select>';
1560     echo $string;
1563 // ----------------------------------------------------------------------------
1565  * DROPDOWN FOR MARITAL STATUS
1566  * 
1567  * build a dropdown with marital status
1568  * 
1569  * @param int $selected - id for selected record
1570  * @param string $name - the name/id for select form
1571  * @return void - just echo the html encoded string
1572  */
1573 function dropdown_marital($selected = 0, $name = 'status') {
1574     $string = "<select name='$name' id='$name'>";
1576     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1578     foreach ( $statii as $st ) {
1579         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1580         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1581     }
1583     $string .= '</select>';
1585     echo $string;
1588 // ----------------------------------------------------------------------------
1590  * DROPDOWN FOR PROVIDERS
1591  * 
1592  * build a dropdown with all providers
1593  * 
1594  * @param int $selected - id for selected record
1595  * @param string $name - the name/id for select form
1596  * @return void - just echo the html encoded string
1597  */
1598 function dropdown_providers($selected = 0, $name = 'status') {
1599     $provideri = getProviderInfo();
1601     $string = "<select name='$name' id='$name'>";
1602     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1603     foreach ( $provideri as $s ) {
1604         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1605         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1606     }
1608     $string .= '</select>';
1610     echo $string;
1613 // ----------------------------------------------------------------------------
1615  * DROPDOWN FOR INSURANCE COMPANIES
1616  * 
1617  * build a dropdown with all insurers
1618  * 
1619  * @param int $selected - id for selected record
1620  * @param string $name - the name/id for select form
1621  * @return void - just echo the html encoded string
1622  */
1623 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1624     $insurancei = getInsuranceProviders();
1626     $string = "<select name='$name' id='$name'>";
1627     $string .= '<option value="0">Onbekend</option>';
1628     foreach ( $insurancei as $iid => $iname ) {
1629         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1630         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1631     }
1633     $string .= '</select>';
1635     echo $string;
1639 // ----------------------------------------------------------------------------
1641  * COUNTRY CODE
1642  * 
1643  * return the name or the country code, function of arguments
1644  * 
1645  * @param int $country_code
1646  * @param string $country_name
1647  * @return string | int - name or code
1648  */
1649 function country_code($country_code = 0, $country_name = '') {
1650     $strint = '';
1651     if ( $country_code ) {
1652         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1653     } else {
1654         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1655     }
1657     $db = $GLOBALS['adodb']['db'];
1658     $result = $db->Execute($sql);
1659     if ($result && !$result->EOF) {
1660         $strint = $result->fields['res'];
1661     }
1663     return $strint;
1666 function DBToDate ($date)
1668     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1669     return $date;
1673  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1674  * for the given patient on the given date.
1676  * @param int     The PID of the patient.
1677  * @param string  Date in yyyy-mm-dd format.
1678  * @return array  Array of 0-3 insurance_data rows.
1679  */
1680 function getEffectiveInsurances($patient_id, $encdate) {
1681   $insarr = array();
1682   foreach (array('primary','secondary','tertiary') as $instype) {
1683     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1684       "WHERE pid = ? AND type = ? " .
1685       "AND date <= ? ORDER BY date DESC LIMIT 1",
1686       array($patient_id, $instype, $encdate));
1687     if (empty($tmp['provider'])) break;
1688     $insarr[] = $tmp;
1689   }
1690   return $insarr;
1694  * Get the patient's balance due. Normally this excludes amounts that are out
1695  * to insurance.  If you want to include what insurance owes, set the second
1696  * parameter to true.
1698  * @param int     The PID of the patient.
1699  * @param boolean Indicates if amounts owed by insurance are to be included.
1700  * @return number The balance.
1701  */
1702 function get_patient_balance($pid, $with_insurance=false) {
1703     $balance = 0;
1704     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1705       "last_level_closed, stmt_count " .
1706       "FROM form_encounter WHERE pid = ?", array($pid));
1707     while ($ferow = sqlFetchArray($feres)) {
1708       $encounter = $ferow['encounter'];
1709       $dos = substr($ferow['date'], 0, 10);
1710       $insarr = getEffectiveInsurances($pid, $dos);
1711       $inscount = count($insarr);
1712       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1713         // It's out to insurance so only the co-pay might be due.
1714         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1715           "pid = ? AND encounter = ? AND " .
1716           "code_type = 'copay' AND activity = 1",
1717           array($pid, $encounter));
1718         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1719           "FROM ar_activity WHERE " .
1720           "pid = ? AND encounter = ? AND payer_type = 0",
1721           array($pid, $encounter));
1722         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1723         if ($ptbal > 0) $balance += $ptbal;
1724       }
1725       else {
1726         // Including insurance or not out to insurance, everything is due.
1727         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1728           "pid = ? AND encounter = ? AND " .
1729           "activity = 1", array($pid, $encounter));
1730         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1731           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1732           "pid = ? AND encounter = ?", array($pid, $encounter));
1733         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1734           "pid = ? AND encounter = ?", array($pid, $encounter));
1735         $balance += $brow['amount'] + $srow['amount']
1736           - $drow['payments'] - $drow['adjustments'];
1737       }
1738     }
1739     return sprintf('%01.2f', $balance);
1742 // Function to check if patient is deceased.
1743 //  Param:
1744 //    $pid  - patient id
1745 //    $date - date checking if deceased (will default to current date if blank)
1746 //  Return:
1747 //    If deceased, then will return the number of
1748 //      days that patient has been deceased.
1749 //    If not deceased, then will return false.
1750 function is_patient_deceased($pid,$date='') {
1752   // Set date to current if not set
1753   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1755   // Query for deceased status (gets days deceased if patient is deceased)
1756   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1757                       "FROM `patient_data` " .
1758                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1760   if (empty($results)) {
1761     // Patient is alive, so return false
1762     return false;
1763   }
1764   else {
1765     // Patient is dead, so return the number of days patient has been deceased.
1766     //  Don't let it be zero days or else will confuse calls to this function.
1767     if ($results['days_deceased'] === 0) {
1768       $results['days_deceased'] = 1;
1769     }
1770     return $results['days_deceased'];
1771   }