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