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