Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / patient.inc
bloba4946372a27b773b53b6221cbd6cbc73a562d33b
1 <?php
2 /**
3  * patient.inc includes functions for manipulating patient information.
4  *
5  * @package   OpenEMR
6  * @link      http://www.open-emr.org
7  * @author    Brady Miller <brady.g.miller@gmail.com>
8  * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>
9  * @license   https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
10  */
13 use OpenEMR\Services\FacilityService;
15 $facilityService = new FacilityService();
17 // These are for sports team use:
18 $PLAYER_FITNESSES = array(
19   xl('Full Play'),
20   xl('Full Training'),
21   xl('Restricted Training'),
22   xl('Injured Out'),
23   xl('Rehabilitation'),
24   xl('Illness'),
25   xl('International Duty')
27 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
29 // Hard-coding this array because its values and meanings are fixed by the 837p
30 // standard and we don't want people messing with them.
31 $policy_types = array(
32   ''   => xl('N/A'),
33   '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
34   '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
35   '14' => xl('No-fault Insurance including Auto is Primary'),
36   '15' => xl('Worker`s Compensation'),
37   '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
38   '41' => xl('Black Lung'),
39   '42' => xl('Veteran`s Administration'),
40   '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
41   '47' => xl('Other Liability Insurance is Primary'),
44 /**
45  * Get a patient's demographic data.
46  *
47  * @param int    $pid   The PID of the patient
48  * @param string $given an optional subsection of the patient's demographic
49  *                      data to retrieve.
50  * @return array The requested subsection of a patient's demographic data.
51  *               If no subsection was given, returns everything, with the
52  *               date of birth as the last field.
53  */
54 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
56     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
57     return sqlQuery($sql, array($pid));
60 function getLanguages()
62     $returnval = array('','english');
63     $sql = "select distinct lower(language) as language from patient_data";
64     $rez = sqlStatement($sql);
65     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
66         if (($row["language"] != "english") && ($row["language"] != "")) {
67             array_push($returnval, $row["language"]);
68         }
69     }
71     return $returnval;
74 function getInsuranceProvider($ins_id)
77     $sql = "select name from insurance_companies where id=?";
78     $row = sqlQuery($sql, array($ins_id));
79     return $row['name'];
82 function getInsuranceProviders()
84     $returnval = array();
86     if (true) {
87         $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
88         $rez = sqlStatement($sql);
89         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
90             $returnval[$row['id']] = $row['name'];
91         }
92     } // Please leave this here. I have a user who wants to see zip codes and PO
93     // box numbers listed along with the insurance company names, as many companies
94     // have different billing addresses for different plans.  -- Rod Roark
95     //
96     else {
97         $sql = "select insurance_companies.name, insurance_companies.id, " .
98           "addresses.zip, addresses.line1 " .
99           "from insurance_companies, addresses " .
100           "where addresses.foreign_id = insurance_companies.id " .
101           "order by insurance_companies.name, addresses.zip";
103         $rez = sqlStatement($sql);
105         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
106             preg_match("/\d+/", $row['line1'], $matches);
107             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
108               "," . $matches[0] . ")";
109         }
110     }
112     return $returnval;
115 function getInsuranceProvidersExtra()
117     $returnval = array();
118     // add a global and if for where to allow inactive inscompanies
120     $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
121             addresses.state, addresses.zip
122             FROM insurance_companies, addresses
123             WHERE addresses.foreign_id = insurance_companies.id
124             AND insurance_companies.inactive != 1
125             ORDER BY insurance_companies.name, addresses.zip";
127     $rez = sqlStatement($sql);
129     for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
130         switch ($GLOBALS['insurance_information']) {
131             case $GLOBALS['insurance_information'] = '0':
132                 $returnval[$row['id']] = $row['name'];
133                 break;
134             case $GLOBALS['insurance_information'] = '1':
135                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
136                 break;
137             case $GLOBALS['insurance_information'] = '2':
138                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
139                 break;
140             case $GLOBALS['insurance_information'] = '3':
141                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
142                 break;
143             case $GLOBALS['insurance_information'] = '4':
144                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
145                     ", " . $row['zip'] . ")";
146                 break;
147             case $GLOBALS['insurance_information'] = '5':
148                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
149                     ", " . $row['state'] . ", " . $row['zip'] . ")";
150                 break;
151             case $GLOBALS['insurance_information'] = '6':
152                 preg_match("/\d+/", $row['line1'], $matches);
153                 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
154                     "," . $matches[0] . ")";
155                 break;
156         }
157     }
159     return $returnval;
162 function getProviders()
164     $returnval = array();
165     $sql = "select fname, lname, suffix from users where authorized = 1 and " .
166         "active = 1 and username != ''";
167     $rez = sqlStatement($sql);
168     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
169         if (($row["fname"] != "") && ($row["lname"] != "")) {
170             if ($row["suffix"] != "") {
171                 $row["lname"] .= ", ".$row["suffix"];
172             }
174             array_push($returnval, $row["fname"] . " " . $row["lname"]);
175         }
176     }
178     return $returnval;
181 // ----------------------------------------------------------------------------
182 // Get one facility row.  If the ID is not specified, then get either the
183 // "main" (billing) facility, or the default facility of the currently
184 // logged-in user.  This was created to support genFacilityTitle() but
185 // may find additional uses.
187 function getFacility($facid = 0)
189     global $facilityService;
191     $facility = null;
193     if ($facid > 0) {
194         return $facilityService->getById($facid);
195     }
197     if ($GLOBALS['login_into_facility']) {
198         //facility is saved in sessions
199         $facility  = $facilityService->getById($_SESSION['facilityId']);
200     } else {
201         if ($facid == 0) {
202             $facility = $facilityService->getPrimaryBillingLocation();
203         } else {
204             $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
205         }
206     }
208     return $facility;
211 // Generate a report title including report name and facility name, address
212 // and phone.
214 function genFacilityTitle($repname = '', $facid = 0, $logo = '')
216     $s = '';
217     $s .= "<table class='ftitletable'>\n";
218     $s .= " <tr>\n";
219     if (empty($logo)) {
220         $s .= "  <td class='ftitlecell1'>" . text($repname) . "</td>\n";
221     } else {
222         $s .= "  <td class='ftitlecell1'>" . $logo . "</td>\n";
223         $s .= "  <td class='ftitlecellm'>" . text($repname) . "</td>\n";
224     }
225     $s .= "  <td class='ftitlecell2'>\n";
226     $r = getFacility($facid);
227     if (!empty($r)) {
228         $s .= "<b>" . text($r['name']) . "</b>\n";
229         if ($r['street']) {
230             $s .= "<br />" . text($r['street']) . "\n";
231         }
233         if ($r['city'] || $r['state'] || $r['postal_code']) {
234             $s .= "<br />";
235             if ($r['city']) {
236                 $s .= text($r['city']);
237             }
239             if ($r['state']) {
240                 if ($r['city']) {
241                     $s .= ", \n";
242                 }
244                 $s .= text($r['state']);
245             }
247             if ($r['postal_code']) {
248                 $s .= " " . text($r['postal_code']);
249             }
251             $s .= "\n";
252         }
254         if ($r['country_code']) {
255             $s .= "<br />" . text($r['country_code']) . "\n";
256         }
258         if (preg_match('/[1-9]/', $r['phone'])) {
259             $s .= "<br />" . text($r['phone']) . "\n";
260         }
261     }
263     $s .= "  </td>\n";
264     $s .= " </tr>\n";
265     $s .= "</table>\n";
266     return $s;
270 GET FACILITIES
272 returns all facilities or just the id for the first one
273 (FACILITY FILTERING (lemonsoftware))
275 @param string - if 'first' return first facility ordered by id
276 @return array | int for 'first' case
278 function getFacilities($first = '')
280     global $facilityService;
282     $fres = $facilityService->getAll();
284     if ($first == 'first') {
285         return $fres[0]['id'];
286     } else {
287         return $fres;
288     }
292 GET SERVICE FACILITIES
294 returns all service_location facilities or just the id for the first one
295 (FACILITY FILTERING (CHEMED))
297 @param string - if 'first' return first facility ordered by id
298 @return array | int for 'first' case
300 function getServiceFacilities($first = '')
302     global $facilityService;
304     $fres = $facilityService->getAllServiceLocations();
306     if ($first == 'first') {
307         return $fres[0]['id'];
308     } else {
309         return $fres;
310     }
313 //(CHEMED) facility filter
314 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
316     $param1 = "";
317     if ($providers_only === 'any') {
318         $param1 = " AND authorized = 1 AND active = 1 ";
319     } elseif ($providers_only) {
320         $param1 = " AND authorized = 1 AND calendar = 1 ";
321     }
323     //--------------------------------
324     //(CHEMED) facility filter
325     $param2 = "";
326     if ($facility) {
327         if ($GLOBALS['restrict_user_facility']) {
328             $param2 = " AND (facility_id = '" . add_escape_custom($facility) . "' OR  '" . add_escape_custom($facility) . "' IN (select facility_id from users_facility where tablename = 'users' and table_id = id))";
329         } else {
330             $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
331         }
332     }
334     //--------------------------------
336     $command = "=";
337     if ($providerID == "%") {
338         $command = "like";
339     }
341     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
342         "from users where username != '' and active = 1 and id $command '" .
343         add_escape_custom($providerID) . "' " . $param1 . $param2;
344     // sort by last name -- JRM June 2008
345     $query .= " ORDER BY lname, fname ";
346     $rez = sqlStatement($query);
347     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
348         $returnval[$iter]=$row;
349     }
351     //if only one result returned take the key/value pairs in array [0] and merge them down into
352     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
354     if ($iter==1) {
355         $akeys = array_keys($returnval[0]);
356         foreach ($akeys as $key) {
357             $returnval[0][$key] = $returnval[0][$key];
358         }
359     }
361     return $returnval;
364 //same as above but does not reduce if only 1 row returned
365 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
367     $param1 = "";
368     if ($providers_only) {
369         $param1 = "AND authorized=1";
370     }
372     $command = "=";
373     if ($providerID == "%") {
374         $command = "like";
375     }
377     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
378         "from users where active = 1 and username != '' and id $command '" .
379         add_escape_custom($providerID) . "' " . $param1;
381     $rez = sqlStatement($query);
382     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
383         $returnval[$iter]=$row;
384     }
386     return $returnval;
389 function getProviderName($providerID)
391     $pi = getProviderInfo($providerID, 'any');
392     if (strlen($pi[0]["lname"]) > 0) {
393         if (strlen($pi[0]["suffix"]) > 0) {
394             $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
395         }
397         return $pi[0]['fname'] . " " . $pi[0]['lname'];
398     }
400     return "";
403 function getProviderId($providerName)
405     $query = "select id from users where username = ?";
406     $rez = sqlStatement($query, array($providerName));
407     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
408         $returnval[$iter]=$row;
409     }
411     return $returnval;
414 function getEthnoRacials()
416     $returnval = array("");
417     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
418     $rez = sqlStatement($sql);
419     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
420         if (($row["ethnoracial"] != "")) {
421             array_push($returnval, $row["ethnoracial"]);
422         }
423     }
425     return $returnval;
428 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
431     if ($dateStart && $dateEnd) {
432         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
433     } elseif ($dateStart && !$dateEnd) {
434         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
435     } elseif (!$dateStart && $dateEnd) {
436         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
437     } else {
438         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
439     }
441     if ($given == 'tobacco') {
442         $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));
443     }
445     return $res;
448 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
449 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
451     $sql = "select $given from insurance_data as insd " .
452     "left join insurance_companies as ic on ic.id = insd.provider " .
453     "where pid = ? and type = ? order by date DESC limit 1";
454     return sqlQuery($sql, array($pid, $type));
457 function getInsuranceDataByDate(
458     $pid,
459     $date,
460     $type,
461     $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
462 ) {
463  // this must take the date in the following manner: YYYY-MM-DD
464   // this function recalls the insurance value that was most recently enterred from the
465   // given date. it will call up most recent records up to and on the date given,
466   // but not records enterred after the given date
467     $sql = "select $given from insurance_data as insd " .
468     "left join insurance_companies as ic on ic.id = provider " .
469     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
470     "type=? order by date DESC limit 1";
471     return sqlQuery($sql, array($pid,$date,$type));
474 function getEmployerData($pid, $given = "*")
476     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
477     return sqlQuery($sql, array($pid));
480 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
482   // When the limit is exceeded, find out what the unlimited count would be.
483     $GLOBALS['PATIENT_INC_COUNT'] = $count;
484   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
485     if ($limit != "all") {
486         $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
487         $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
488     }
492  * Allow the last name to be followed by a comma and some part of a first name(can
493  *   also place middle name after the first name with a space separating them)
494  * Allows comma alone followed by some part of a first name(can also place middle name
495  *   after the first name with a space separating them).
496  * Allows comma alone preceded by some part of a last name.
497  * If no comma or space, then will search both last name and first name.
498  * If the first letter of either name is capital, searches for name starting
499  *   with given substring (the expected behavior). If it is lower case, it
500  *   searches for the substring anywhere in the name. This applies to either
501  *   last name, first name, and middle name.
502  * Also allows first name followed by middle and/or last name when separated by spaces.
503  * @param string $term
504  * @param string $given
505  * @param string $orderby
506  * @param string $limit
507  * @param string $start
508  * @return array
509  */
510 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")
512     $names = getPatientNameSplit($term);
514     foreach ($names as $key => $val) {
515         if (!empty($val)) {
516             if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
517                 $names[$key] = '%' . $val . '%';
518             } else {
519                 $names[$key] = $val . '%';
520             }
521         }
522     }
524     // Debugging section below
525     //if(array_key_exists('first',$names)) {
526     //    error_log("first name search term :".$names['first']);
527     //}
528     //if(array_key_exists('middle',$names)) {
529     //    error_log("middle name search term :".$names['middle']);
530     //}
531     //if(array_key_exists('last',$names)) {
532     //    error_log("last name search term :".$names['last']);
533     //}
534     // Debugging section above
536     $sqlBindArray = array();
537     if (array_key_exists('last', $names) && $names['last'] == '') {
538         // Do not search last name
539         $where = "fname LIKE ? ";
540         array_push($sqlBindArray, $names['first']);
541         if ($names['middle'] != '') {
542             $where .= "AND mname LIKE ? ";
543             array_push($sqlBindArray, $names['middle']);
544         }
545     } elseif (array_key_exists('first', $names) && $names['first'] == '') {
546         // Do not search first name or middle name
547         $where = "lname LIKE ? ";
548         array_push($sqlBindArray, $names['last']);
549     } elseif ($names['first'] == '' && $names['last'] != '') {
550         // Search both first name and last name with same term
551         $names['first'] = $names['last'];
552         $where = "lname LIKE ? OR fname LIKE ? ";
553         array_push($sqlBindArray, $names['last'], $names['first']);
554     } elseif ($names['middle'] != '') {
555         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
556         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
557     } else {
558         $where = "lname LIKE ? AND fname LIKE ? ";
559         array_push($sqlBindArray, $names['last'], $names['first']);
560     }
562     if (!empty($GLOBALS['pt_restrict_field'])) {
563         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
564             $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
565                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
566                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
567             array_push($sqlBindArray, $_SESSION{"authUser"});
568         }
569     }
571     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
572     if ($limit != "all") {
573         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
574     }
576     $rez = sqlStatement($sql, $sqlBindArray);
578     $returnval=array();
579     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
580         $returnval[$iter] = $row;
581     }
583     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
584     return $returnval;
587  * Accept a string used by a search function expected to find a patient name,
588  * then split up the string if a comma or space exists. Return an array having
589  * from 1 to 3 elements, named first, middle, and last.
590  * See above getPatientLnames() function for details on how the splitting occurs.
591  * @param string $term
592  * @return array
593  */
594 function getPatientNameSplit($term)
596     $term = trim($term);
597     if (strpos($term, ',') !== false) {
598         $names = explode(',', $term);
599         $n['last'] = $names[0];
600         if (strpos(trim($names[1]), ' ') !== false) {
601             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
602         } else {
603             $n['first'] = $names[1];
604         }
605     } elseif (strpos($term, ' ') !== false) {
606         $names = explode(' ', $term);
607         if (count($names) == 1) {
608             $n['last'] = $names[0];
609         } elseif (count($names) == 3) {
610             $n['first'] = $names[0];
611             $n['middle'] = $names[1];
612             $n['last'] = $names[2];
613         } else {
614             // This will handle first and last name or first followed by
615             // multiple names only using just the last of the names in the list.
616             $n['first'] = $names[0];
617             $n['last'] = end($names);
618         }
619     } else {
620         $n['last'] = $term;
621         if (empty($n['last'])) {
622             $n['last'] = '%';
623         }
624     }
626     // Trim whitespace off the names before returning
627     foreach ($n as $key => $val) {
628         $n[$key] = trim($val);
629     }
631     return $n; // associative array containing names
634 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")
637     $sqlBindArray = array();
638     $where = "pubpid LIKE ? ";
639     array_push($sqlBindArray, $pid."%");
640     if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
641         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
642             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
643                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
644                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
645             array_push($sqlBindArray, $_SESSION{"authUser"});
646         }
647     }
649     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
650     if ($limit != "all") {
651         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
652     }
654     $rez = sqlStatement($sql, $sqlBindArray);
655     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
656         $returnval[$iter]=$row;
657     }
659     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
660     return $returnval;
663 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")
665     $layoutCols = sqlStatement(
666         "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
667         array('em\_%')
668     );
670     $sqlBindArray = array();
671     $where = "";
672     for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
673         if ($iter > 0) {
674             $where .= " or ";
675         }
677         $where .= " ".add_escape_custom($row["field_id"])." like ? ";
678         array_push($sqlBindArray, "%".$searchTerm."%");
679     }
681     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
682     if ($limit != "all") {
683         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
684     }
686     $rez = sqlStatement($sql, $sqlBindArray);
687     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
688         $returnval[$iter]=$row;
689     }
691     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
692     return $returnval;
695 function getByPatientDemographicsFilter(
696     $searchFields,
697     $searchTerm = "%",
698     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
699     $orderby = "lname ASC, fname ASC",
700     $limit = "all",
701     $start = "0",
702     $search_service_code = ''
703 ) {
705     $layoutCols = explode('~', $searchFields);
706     $sqlBindArray = array();
707     $where = "";
708     $i = 0;
709     foreach ($layoutCols as $val) {
710         if (empty($val)) {
711             continue;
712         }
714         if ($i > 0) {
715             $where .= " or ";
716         }
718         if ($val == 'pid') {
719             $where .= " ".add_escape_custom($val)." = ? ";
720                 array_push($sqlBindArray, $searchTerm);
721         } else {
722             $where .= " ".add_escape_custom($val)." like ? ";
723                 array_push($sqlBindArray, $searchTerm."%");
724         }
726         $i++;
727     }
729   // If no search terms, ensure valid syntax.
730     if ($i == 0) {
731         $where = "1 = 1";
732     }
734   // If a non-empty service code was given, then restrict to patients who
735   // have been provided that service.  Since the code is used in a LIKE
736   // clause, % and _ wildcards are supported.
737     if ($search_service_code) {
738         $where = "( $where ) AND " .
739         "( SELECT COUNT(*) FROM billing AS b WHERE " .
740         "b.pid = patient_data.pid AND " .
741         "b.activity = 1 AND " .
742         "b.code_type != 'COPAY' AND " .
743         "b.code LIKE ? " .
744         ") > 0";
745         array_push($sqlBindArray, $search_service_code);
746     }
748     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
749     if ($limit != "all") {
750         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
751     }
753     $rez = sqlStatement($sql, $sqlBindArray);
754     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
755         $returnval[$iter]=$row;
756     }
758     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
759     return $returnval;
762 // return a collection of Patient PIDs
763 // new arg style by JRM March 2008
764 // 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")
765 function getPatientPID($args)
767     $pid = "%";
768     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
769     $orderby = "lname ASC, fname ASC";
770     $limit="all";
771     $start="0";
773     // alter default values if defined in the passed in args
774     if (isset($args['pid'])) {
775         $pid = $args['pid'];
776     }
778     if (isset($args['given'])) {
779         $given = $args['given'];
780     }
782     if (isset($args['orderby'])) {
783         $orderby = $args['orderby'];
784     }
786     if (isset($args['limit'])) {
787         $limit = $args['limit'];
788     }
790     if (isset($args['start'])) {
791         $start = $args['start'];
792     }
794     $command = "=";
795     if ($pid == -1) {
796         $pid = "%";
797     } elseif (empty($pid)) {
798         $pid = "NULL";
799     }
801     if (strstr($pid, "%")) {
802         $command = "like";
803     }
805     $sql="select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
806     if ($limit != "all") {
807         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
808     }
810     $rez = sqlStatement($sql);
811     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
812         $returnval[$iter]=$row;
813     }
815     return $returnval;
818 /* return a patient's name in the format LAST, FIRST */
819 function getPatientName($pid)
821     if (empty($pid)) {
822         return "";
823     }
825     $patientData = getPatientPID(array("pid"=>$pid));
826     if (empty($patientData[0]['lname'])) {
827         return "";
828     }
830     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
831     return $patientName;
834 /* return a patient's name in the format FIRST LAST */
835 function getPatientNameFirstLast($pid)
837     if (empty($pid)) {
838         return "";
839     }
841     $patientData = getPatientPID(array("pid"=>$pid));
842     if (empty($patientData[0]['lname'])) {
843         return "";
844     }
846     $patientName =  $patientData[0]['fname'] . " " . $patientData[0]['lname'];
847     return $patientName;
850 /* find patient data by DOB */
851 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
853     $sqlBindArray = array();
854     $where = "DOB like ? ";
855     array_push($sqlBindArray, $DOB."%");
856     if (!empty($GLOBALS['pt_restrict_field'])) {
857         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
858             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
859                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
860                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
861             array_push($sqlBindArray, $_SESSION{"authUser"});
862         }
863     }
865     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
867     if ($limit != "all") {
868         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
869     }
871     $rez = sqlStatement($sql, $sqlBindArray);
872     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
873         $returnval[$iter]=$row;
874     }
876     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
877     return $returnval;
880 /* find patient data by SSN */
881 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
883     $sqlBindArray = array();
884     $where = "ss LIKE ?";
885     array_push($sqlBindArray, $ss."%");
886     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
887     if ($limit != "all") {
888         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
889     }
891     $rez = sqlStatement($sql, $sqlBindArray);
892     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
893         $returnval[$iter]=$row;
894     }
896     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
897     return $returnval;
900 //(CHEMED) Search by phone number
901 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
903     $phone = preg_replace("/[[:punct:]]/", "", $phone);
904     $sqlBindArray = array();
905     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
906     array_push($sqlBindArray, $phone);
907     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
908     if ($limit != "all") {
909         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
910     }
912     $rez = sqlStatement($sql, $sqlBindArray);
913     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
914         $returnval[$iter]=$row;
915     }
917     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
918     return $returnval;
921 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
923     $sql="select $given from patient_data order by $orderby";
925     if ($limit != "all") {
926         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
927     }
929     $rez = sqlStatement($sql);
930     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
931         $returnval[$iter]=$row;
932     }
934     return $returnval;
937 //----------------------input functions
938 function newPatientData(
939     $db_id = "",
940     $title = "",
941     $fname = "",
942     $lname = "",
943     $mname = "",
944     $sex = "",
945     $DOB = "",
946     $street = "",
947     $postal_code = "",
948     $city = "",
949     $state = "",
950     $country_code = "",
951     $ss = "",
952     $occupation = "",
953     $phone_home = "",
954     $phone_biz = "",
955     $phone_contact = "",
956     $status = "",
957     $contact_relationship = "",
958     $referrer = "",
959     $referrerID = "",
960     $email = "",
961     $language = "",
962     $ethnoracial = "",
963     $interpretter = "",
964     $migrantseasonal = "",
965     $family_size = "",
966     $monthly_income = "",
967     $homeless = "",
968     $financial_review = "",
969     $pubpid = "",
970     $pid = "MAX(pid)+1",
971     $providerID = "",
972     $genericname1 = "",
973     $genericval1 = "",
974     $genericname2 = "",
975     $genericval2 = "",
976     $billing_note = "",
977     $phone_cell = "",
978     $hipaa_mail = "",
979     $hipaa_voice = "",
980     $squad = 0,
981     $pharmacy_id = 0,
982     $drivers_license = "",
983     $hipaa_notice = "",
984     $hipaa_message = "",
985     $regdate = ""
986 ) {
988     $fitness = 0;
989     $referral_source = '';
990     if ($pid) {
991         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
992         // Check for brain damage:
993         if ($db_id != $rez['id']) {
994             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
995               text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
996             die($errmsg);
997         }
999         $fitness = $rez['fitness'];
1000         $referral_source = $rez['referral_source'];
1001     }
1003     // Get the default price level.
1004     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
1005       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
1006     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
1008     $query = ("replace into patient_data set
1009         id='" . add_escape_custom($db_id) . "',
1010         title='" . add_escape_custom($title) . "',
1011         fname='" . add_escape_custom($fname) . "',
1012         lname='" . add_escape_custom($lname) . "',
1013         mname='" . add_escape_custom($mname) . "',
1014         sex='" . add_escape_custom($sex) . "',
1015         DOB='" . add_escape_custom($DOB) . "',
1016         street='" . add_escape_custom($street) . "',
1017         postal_code='" . add_escape_custom($postal_code) . "',
1018         city='" . add_escape_custom($city) . "',
1019         state='" . add_escape_custom($state) . "',
1020         country_code='" . add_escape_custom($country_code) . "',
1021         drivers_license='" . add_escape_custom($drivers_license) . "',
1022         ss='" . add_escape_custom($ss) . "',
1023         occupation='" . add_escape_custom($occupation) . "',
1024         phone_home='" . add_escape_custom($phone_home) . "',
1025         phone_biz='" . add_escape_custom($phone_biz) . "',
1026         phone_contact='" . add_escape_custom($phone_contact) . "',
1027         status='" . add_escape_custom($status) . "',
1028         contact_relationship='" . add_escape_custom($contact_relationship) . "',
1029         referrer='" . add_escape_custom($referrer) . "',
1030         referrerID='" . add_escape_custom($referrerID) . "',
1031         email='" . add_escape_custom($email) . "',
1032         language='" . add_escape_custom($language) . "',
1033         ethnoracial='" . add_escape_custom($ethnoracial) . "',
1034         interpretter='" . add_escape_custom($interpretter) . "',
1035         migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1036         family_size='" . add_escape_custom($family_size) . "',
1037         monthly_income='" . add_escape_custom($monthly_income) . "',
1038         homeless='" . add_escape_custom($homeless) . "',
1039         financial_review='" . add_escape_custom($financial_review) . "',
1040         pubpid='" . add_escape_custom($pubpid) . "',
1041         pid= '" . add_escape_custom($pid) . "',
1042         providerID = '" . add_escape_custom($providerID) . "',
1043         genericname1 = '" . add_escape_custom($genericname1) . "',
1044         genericval1 = '" . add_escape_custom($genericval1) . "',
1045         genericname2 = '" . add_escape_custom($genericname2) . "',
1046         genericval2 = '" . add_escape_custom($genericval2) . "',
1047         billing_note= '" . add_escape_custom($billing_note) . "',
1048         phone_cell = '" . add_escape_custom($phone_cell) . "',
1049         pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1050         hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1051         hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1052         hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1053         hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1054         squad = '" . add_escape_custom($squad) . "',
1055         fitness='" . add_escape_custom($fitness) . "',
1056         referral_source='" . add_escape_custom($referral_source) . "',
1057         regdate='" . add_escape_custom($regdate) . "',
1058         pricelevel='" . add_escape_custom($pricelevel) . "',
1059         date=NOW()");
1061     $id = sqlInsert($query);
1063     if (!$db_id) {
1064       // find the last inserted id for new patient case
1065         $db_id = $id;
1066     }
1068     $foo = sqlQuery("select pid from patient_data where id=? order by date limit 0,1", array($id));
1070     return $foo['pid'];
1073 // Supported input date formats are:
1074 //   mm/dd/yyyy
1075 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1076 //   yyyy/mm/dd
1077 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1079 function fixDate($date, $default = "0000-00-00")
1081     $fixed_date = $default;
1082     $date = trim($date);
1083     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1084         $dmy = preg_split("'[/.-]'", $date);
1085         if ($dmy[0] > 99) {
1086             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1087         } else {
1088             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1089                 if ($dmy[2] < 1000) {
1090                     $dmy[2] += 1900;
1091                 }
1093                 if ($dmy[2] < 1910) {
1094                     $dmy[2] += 100;
1095                 }
1096             }
1098             // phone_country_code indicates format of ambiguous input dates.
1099             if ($GLOBALS['phone_country_code'] == 1) {
1100                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1101             } else {
1102                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1103             }
1104         }
1105     }
1107     return $fixed_date;
1110 function pdValueOrNull($key, $value)
1112     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1113     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1114     (empty($value) || $value == '0000-00-00')) {
1115         return "NULL";
1116     } else {
1117         return "'" . add_escape_custom($value) . "'";
1118     }
1121 // Create or update patient data from an array.
1123 function updatePatientData($pid, $new, $create = false)
1125   /*******************************************************************
1126     $real = getPatientData($pid);
1127     foreach ($new as $key => $value)
1128         $real[$key] = $value;
1129     $real['date'] = "'+NOW()+'";
1130     $real['id'] = "";
1131     $sql = "insert into patient_data set ";
1132     foreach ($real as $key => $value)
1133         $sql .= $key." = '$value', ";
1134     $sql = substr($sql, 0, -2);
1135     return sqlInsert($sql);
1136   *******************************************************************/
1138   // The above was broken, though seems intent to insert a new patient_data
1139   // row for each update.  A good idea, but nothing is doing that yet so
1140   // the code below does not yet attempt it.
1142     if ($create) {
1143         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1144         foreach ($new as $key => $value) {
1145             if ($key == 'id') {
1146                 continue;
1147             }
1149             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1150         }
1152         $db_id = sqlInsert($sql);
1153     } else {
1154         $db_id = $new['id'];
1155         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1156         // Check for brain damage:
1157         if ($pid != $rez['pid']) {
1158             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1159             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1160             die($errmsg);
1161         }
1163         $sql = "UPDATE patient_data SET date = NOW()";
1164         foreach ($new as $key => $value) {
1165             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1166         }
1168         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1169         sqlStatement($sql);
1170     }
1172     return $db_id;
1175 function newEmployerData(
1176     $pid,
1177     $name = "",
1178     $street = "",
1179     $postal_code = "",
1180     $city = "",
1181     $state = "",
1182     $country = ""
1183 ) {
1185     return sqlInsert("insert into employer_data set
1186         name='" . add_escape_custom($name) . "',
1187         street='" . add_escape_custom($street) . "',
1188         postal_code='" . add_escape_custom($postal_code) . "',
1189         city='" . add_escape_custom($city) . "',
1190         state='" . add_escape_custom($state) . "',
1191         country='" . add_escape_custom($country) . "',
1192         pid='" . add_escape_custom($pid) . "',
1193         date=NOW()
1194         ");
1197 // Create or update employer data from an array.
1199 function updateEmployerData($pid, $new, $create = false)
1201     $colnames = array('name','street','city','state','postal_code','country');
1203     if ($create) {
1204         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1205         foreach ($colnames as $key) {
1206             $value = isset($new[$key]) ? $new[$key] : '';
1207             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1208         }
1210         return sqlInsert("INSERT INTO employer_data SET $set");
1211     } else {
1212         $set = '';
1213         $old = getEmployerData($pid);
1214         $modified = false;
1215         foreach ($colnames as $key) {
1216             $value = empty($old[$key]) ? '' : $old[$key];
1217             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1218                 $value = $new[$key];
1219                 $modified = true;
1220             }
1222             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1223         }
1225         if ($modified) {
1226             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1227             return sqlInsert("INSERT INTO employer_data SET $set");
1228         }
1230         return $old['id'];
1231     }
1234 // This updates or adds the given insurance data info, while retaining any
1235 // previously added insurance_data rows that should be preserved.
1236 // This does not directly support the maintenance of non-current insurance.
1238 function newInsuranceData(
1239     $pid,
1240     $type = "",
1241     $provider = "",
1242     $policy_number = "",
1243     $group_number = "",
1244     $plan_name = "",
1245     $subscriber_lname = "",
1246     $subscriber_mname = "",
1247     $subscriber_fname = "",
1248     $subscriber_relationship = "",
1249     $subscriber_ss = "",
1250     $subscriber_DOB = "",
1251     $subscriber_street = "",
1252     $subscriber_postal_code = "",
1253     $subscriber_city = "",
1254     $subscriber_state = "",
1255     $subscriber_country = "",
1256     $subscriber_phone = "",
1257     $subscriber_employer = "",
1258     $subscriber_employer_street = "",
1259     $subscriber_employer_city = "",
1260     $subscriber_employer_postal_code = "",
1261     $subscriber_employer_state = "",
1262     $subscriber_employer_country = "",
1263     $copay = "",
1264     $subscriber_sex = "",
1265     $effective_date = "0000-00-00",
1266     $accept_assignment = "TRUE",
1267     $policy_type = ""
1268 ) {
1270     if (strlen($type) <= 0) {
1271         return false;
1272     }
1274     // If empty dates were passed, then zero them.
1275     if (empty($effective_date)) {
1276         $effective_date = '0000-00-00';
1277     }
1278     if (empty($subscriber_DOB)) {
1279         $subscriber_DOB = '0000-00-00';
1280     }
1282     $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1283     "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1284     $idrow = sqlFetchArray($idres);
1286   // Replace the most recent entry in any of the following cases:
1287   // * Its effective date is >= this effective date.
1288   // * It is the first entry and it has no (insurance) provider.
1289   // * There is no encounter that is earlier than the new effective date but
1290   //   on or after the old effective date.
1291   // Otherwise insert a new entry.
1293     $replace = false;
1294     if ($idrow) {
1295         if (strcmp($idrow['date'], $effective_date) > 0) {
1296             $replace = true;
1297         } else {
1298             if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1299                 $replace = true;
1300             } else {
1301                 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1302                 "WHERE pid = ? AND date < ? AND " .
1303                 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1304                 if ($ferow['count'] == 0) {
1305                     $replace = true;
1306                 }
1307             }
1308         }
1309     }
1311     if ($replace) {
1312         // TBD: This is a bit dangerous in that a typo in entering the effective
1313         // date can wipe out previous insurance history.  So we want some data
1314         // entry validation somewhere.
1315         sqlStatement("DELETE FROM insurance_data WHERE " .
1316         "pid = ? AND type = ? AND date >= ? AND " .
1317         "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1319         $data = array();
1320         $data['type'] = $type;
1321         $data['provider'] = $provider;
1322         $data['policy_number'] = $policy_number;
1323         $data['group_number'] = $group_number;
1324         $data['plan_name'] = $plan_name;
1325         $data['subscriber_lname'] = $subscriber_lname;
1326         $data['subscriber_mname'] = $subscriber_mname;
1327         $data['subscriber_fname'] = $subscriber_fname;
1328         $data['subscriber_relationship'] = $subscriber_relationship;
1329         $data['subscriber_ss'] = $subscriber_ss;
1330         $data['subscriber_DOB'] = $subscriber_DOB;
1331         $data['subscriber_street'] = $subscriber_street;
1332         $data['subscriber_postal_code'] = $subscriber_postal_code;
1333         $data['subscriber_city'] = $subscriber_city;
1334         $data['subscriber_state'] = $subscriber_state;
1335         $data['subscriber_country'] = $subscriber_country;
1336         $data['subscriber_phone'] = $subscriber_phone;
1337         $data['subscriber_employer'] = $subscriber_employer;
1338         $data['subscriber_employer_city'] = $subscriber_employer_city;
1339         $data['subscriber_employer_street'] = $subscriber_employer_street;
1340         $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1341         $data['subscriber_employer_state'] = $subscriber_employer_state;
1342         $data['subscriber_employer_country'] = $subscriber_employer_country;
1343         $data['copay'] = $copay;
1344         $data['subscriber_sex'] = $subscriber_sex;
1345         $data['pid'] = $pid;
1346         $data['date'] = $effective_date;
1347         $data['accept_assignment'] = $accept_assignment;
1348         $data['policy_type'] = $policy_type;
1349         updateInsuranceData($idrow['id'], $data);
1350         return $idrow['id'];
1351     } else {
1352         return sqlInsert("INSERT INTO insurance_data SET
1353       type = '" . add_escape_custom($type) . "',
1354       provider = '" . add_escape_custom($provider) . "',
1355       policy_number = '" . add_escape_custom($policy_number) . "',
1356       group_number = '" . add_escape_custom($group_number) . "',
1357       plan_name = '" . add_escape_custom($plan_name) . "',
1358       subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1359       subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1360       subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1361       subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1362       subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1363       subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1364       subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1365       subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1366       subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1367       subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1368       subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1369       subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1370       subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1371       subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1372       subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1373       subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1374       subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1375       subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1376       copay = '" . add_escape_custom($copay) . "',
1377       subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1378       pid = '" . add_escape_custom($pid) . "',
1379       date = '" . add_escape_custom($effective_date) . "',
1380       accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1381       policy_type = '" . add_escape_custom($policy_type) . "'
1382     ");
1383     }
1386 // This is used internally only.
1387 function updateInsuranceData($id, $new)
1389     $fields = sqlListFields("insurance_data");
1390     $use = array();
1392     foreach ($new as $key => $value) {
1393         if (in_array($key, $fields)) {
1394             $use[$key] = $value;
1395         }
1396     }
1398     $sql = "UPDATE insurance_data SET ";
1399     foreach ($use as $key => $value) {
1400         $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1401     }
1403     $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1405     sqlStatement($sql);
1408 function newHistoryData($pid, $new = false)
1410     $arraySqlBind = array();
1411     $sql = "insert into history_data set pid = ?, date = NOW()";
1412     array_push($arraySqlBind, $pid);
1413     if ($new) {
1414         foreach ($new as $key => $value) {
1415             array_push($arraySqlBind, $value);
1416             $sql .= ", `$key` = ?";
1417         }
1418     }
1420     return sqlInsert($sql, $arraySqlBind);
1423 function updateHistoryData($pid, $new)
1425     $real = getHistoryData($pid);
1426     foreach ($new as $key => $value) {
1427         $real[$key] = $value;
1428     }
1430     $real['id'] = "";
1431     // need to unset date, so can reset it below
1432     unset($real['date']);
1434     $arraySqlBind = array();
1435     $sql = "insert into history_data set `date` = NOW(), ";
1436     foreach ($real as $key => $value) {
1437         array_push($arraySqlBind, $value);
1438         $sql .= "`$key` = ?, ";
1439     }
1441     $sql = substr($sql, 0, -2);
1443     return sqlInsert($sql, $arraySqlBind);
1446 // Returns Age
1447 //   in months if < 2 years old
1448 //   in years  if > 2 years old
1449 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1450 // (optional) nowYMD is a date in YYYYMMDD format
1451 function getPatientAge($dobYMD, $nowYMD = null)
1453     // strip any dashes from the DOB
1454     $dobYMD = preg_replace("/-/", "", $dobYMD);
1455     $dobDay = substr($dobYMD, 6, 2);
1456     $dobMonth = substr($dobYMD, 4, 2);
1457     $dobYear = substr($dobYMD, 0, 4);
1459     // set the 'now' date values
1460     if ($nowYMD == null) {
1461         $nowDay = date("d");
1462         $nowMonth = date("m");
1463         $nowYear = date("Y");
1464     } else {
1465         $nowDay = substr($nowYMD, 6, 2);
1466         $nowMonth = substr($nowYMD, 4, 2);
1467         $nowYear = substr($nowYMD, 0, 4);
1468     }
1470     $dayDiff = $nowDay - $dobDay;
1471     $monthDiff = $nowMonth - $dobMonth;
1472     $yearDiff = $nowYear - $dobYear;
1474     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1476     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1477     if ($dayDiff<0) {
1478         $ageInMonths-=1;
1479     }
1481     if ($ageInMonths > 24) {
1482         $age = $yearDiff;
1483         if (($monthDiff == 0) && ($dayDiff < 0)) {
1484             $age -= 1;
1485         } elseif ($monthDiff < 0) {
1486             $age -= 1;
1487         }
1488     } else {
1489         $age = "$ageInMonths " . xl('month');
1490     }
1492     return $age;
1496  * Wrapper to make sure the clinical rules dates formats corresponds to the
1497  * format expected by getPatientAgeYMD
1499  * @param  string  $dob     date of birth
1500  * @param  string  $target  date to calculate age on
1501  * @return array containing
1502  *      age - decimal age in years
1503  *      age_in_months - decimal age in months
1504  *      ageinYMD - formatted string #y #m #d */
1505 function parseAgeInfo($dob, $target)
1507     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1508     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1509     ;
1510     // Prepare target (Y-M-D H:M:S)
1511     $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1513     return getPatientAgeYMD($dateDOB, $dateTarget);
1518  * @param type $dob
1519  * @param type $date
1520  * @return array containing
1521  *      age - decimal age in years
1522  *      age_in_months - decimal age in months
1523  *      ageinYMD - formatted string #y #m #d
1524  */
1525 function getPatientAgeYMD($dob, $date = null)
1528     if ($date == null) {
1529         $daynow = date("d");
1530         $monthnow = date("m");
1531         $yearnow = date("Y");
1532         $datenow=$yearnow.$monthnow.$daynow;
1533     } else {
1534         $datenow=preg_replace("/-/", "", $date);
1535         $yearnow=substr($datenow, 0, 4);
1536         $monthnow=substr($datenow, 4, 2);
1537         $daynow=substr($datenow, 6, 2);
1538         $datenow=$yearnow.$monthnow.$daynow;
1539     }
1541     $dob=preg_replace("/-/", "", $dob);
1542     $dobyear=substr($dob, 0, 4);
1543     $dobmonth=substr($dob, 4, 2);
1544     $dobday=substr($dob, 6, 2);
1545     $dob=$dobyear.$dobmonth.$dobday;
1547     //to compensate for 30, 31, 28, 29 days/month
1548     $mo=$monthnow; //to avoid confusion with later calculation
1550     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1
1551         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1552     } // look at April, June, September, November for calculation.  These months only have 30 days.
1553     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1554         $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1555         if (is_int($check_leap_Y)) {
1556             $nd=29;
1557         } //If it true then this is the leap year
1558         else {
1559             $nd=28;
1560         } //otherwise, it is not a leap year.
1561     } else {
1562         $nd=31;
1563     } // other months have 31 days
1565     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1566     if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1567         $age_year = $yearnow - $dobyear - 1;
1568         if ($daynow < $dobday) {
1569             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1570             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1571         } else {
1572             $months_since_birthday=12 - $dobmonth + $monthnow;
1573             $days_since_dobday=$daynow - $dobday;
1574         }
1575     } else // if patient has had birthday this calandar year
1576     {
1577         $age_year = $yearnow - $dobyear;
1578         if ($daynow < $dobday) {
1579             $months_since_birthday=$monthnow - $dobmonth -1;
1580             $days_since_dobday=$nd - $dobday + $daynow;
1581         } else {
1582             $months_since_birthday=$monthnow - $dobmonth;
1583             $days_since_dobday=$daynow - $dobday;
1584         }
1585     }
1587     $day_as_month_decimal = $days_since_dobday / 30;
1588     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1589     $month_as_year_decimal = $months_since_birthday_float / 12;
1590     $age_float = $age_year + $month_as_year_decimal;
1592     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1593     $age_in_months = round($age_in_months, 2);  //round the months to xx.xx 2 floating points
1594     $age = round($age_float, 2);
1596     // round the years to 2 floating points
1597     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1598     return compact('age', 'age_in_months', 'ageinYMD');
1601 // Returns Age in days
1602 //   in months if < 2 years old
1603 //   in years  if > 2 years old
1604 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1605 // (optional) nowYMD is a date in YYYYMMDD format
1606 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1608     $age = -1;
1610     // strip any dashes from the DOB
1611     $dobYMD = preg_replace("/-/", "", $dobYMD);
1612     $dobDay = substr($dobYMD, 6, 2);
1613     $dobMonth = substr($dobYMD, 4, 2);
1614     $dobYear = substr($dobYMD, 0, 4);
1616     // set the 'now' date values
1617     if ($nowYMD == null) {
1618         $nowDay = date("d");
1619         $nowMonth = date("m");
1620         $nowYear = date("Y");
1621     } else {
1622         $nowDay = substr($nowYMD, 6, 2);
1623         $nowMonth = substr($nowYMD, 4, 2);
1624         $nowYear = substr($nowYMD, 0, 4);
1625     }
1627     // do the date math
1628     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1629     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1630     $timediff = $nowtime - $dobtime;
1631     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1633     return $age;
1636  * Returns a string to be used to display a patient's age
1638  * @param type $dobYMD
1639  * @param type $asOfYMD
1640  * @return string suitable for displaying patient's age based on preferences
1641  */
1642 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1644     if ($GLOBALS['age_display_format']=='1') {
1645         $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1646         if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1647             return $ageYMD['ageinYMD'];
1648         } else {
1649             return getPatientAge($dobYMD, $asOfYMD);
1650         }
1651     } else {
1652         return getPatientAge($dobYMD, $asOfYMD);
1653     }
1655 function dateToDB($date)
1657     $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1658     return $date;
1662 // ----------------------------------------------------------------------------
1664  * DROPDOWN FOR COUNTRIES
1666  * build a dropdown with all countries from geo_country_reference
1668  * @param int $selected - id for selected record
1669  * @param string $name - the name/id for select form
1670  * @return void - just echo the html encoded string
1671  */
1672 function dropdown_countries($selected = 0, $name = 'country_code')
1674     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1676     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1677     while ($row = sqlFetchArray($r)) {
1678         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1679         $string .= "<option value='" . attr($row['countries_id']) . "' $sufix>" . text($row['countries_name']) . "</option>";
1680     }
1682     $string .= '</select>';
1683     echo $string;
1687 // ----------------------------------------------------------------------------
1689  * DROPDOWN FOR YES/NO
1691  * build a dropdown with two options (yes - 1, no - 0)
1693  * @param int $selected - id for selected record
1694  * @param string $name - the name/id for select form
1695  * @return void - just echo the html encoded string
1696  */
1697 function dropdown_yesno($selected = 0, $name = 'yesno')
1699     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1701     $selected = (int)$selected;
1702     if ($selected == 0) {
1703         $sel1 = 'selected="selected"';
1704         $sel2 = '';
1705     } else {
1706         $sel2 = 'selected="selected"';
1707         $sel1 = '';
1708     }
1710         $string .= "<option value='0' $sel1>" .xlt('No'). "</option>";
1711         $string .= "<option value='1' $sel2>" .xlt('Yes'). "</option>";
1712         $string .= '</select>';
1714         echo $string;
1717 // ----------------------------------------------------------------------------
1719  * DROPDOWN FOR MALE/FEMALE options
1721  * build a dropdown with three options (unselected/male/female)
1723  * @param int $selected - id for selected record
1724  * @param string $name - the name/id for select form
1725  * @return void - just echo the html encoded string
1726  */
1727 function dropdown_sex($selected = 0, $name = 'sex')
1729     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1731     if ($selected == 1) {
1732         $sel1 = 'selected="selected"';
1733         $sel2 = '';
1734         $sel0 = '';
1735     } elseif ($selected == 2) {
1736         $sel2 = 'selected="selected"';
1737         $sel1 = '';
1738         $sel0 = '';
1739     } else {
1740             $sel0 = 'selected="selected"';
1741             $sel1 = '';
1742             $sel2 = '';
1743     }
1745         $string .= "<option value='0' $sel0>" .xlt('Unselected'). "</option>";
1746         $string .= "<option value='1' $sel1>" .xlt('Male'). "</option>";
1747         $string .= "<option value='2' $sel2>" .xlt('Female'). "</option>";
1748         $string .= '</select>';
1750         echo $string;
1753 // ----------------------------------------------------------------------------
1755  * DROPDOWN FOR MARITAL STATUS
1757  * build a dropdown with marital status
1759  * @param int $selected - id for selected record
1760  * @param string $name - the name/id for select form
1761  * @return void - just echo the html encoded string
1762  */
1763 function dropdown_marital($selected = 0, $name = 'status')
1765     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1767     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1769     foreach ($statii as $st) {
1770         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1771         $string .= '<option value="' . attr($st) . '" '.$sel.' >' .xlt($st). '</option>';
1772     }
1774     $string .= '</select>';
1776     echo $string;
1779 // ----------------------------------------------------------------------------
1781  * DROPDOWN FOR PROVIDERS
1783  * build a dropdown with all providers
1785  * @param int $selected - id for selected record
1786  * @param string $name - the name/id for select form
1787  * @return void - just echo the html encoded string
1788  */
1789 function dropdown_providers($selected = 0, $name = 'status')
1791     $provideri = getProviderInfo();
1793     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1794     $string .= '<option value="">' .xlt('Unassigned'). '</option>';
1795     foreach ($provideri as $s) {
1796         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1797         $string .= '<option value="' . attr($s['id']) . '" '.$sel.' >' . text(ucwords($s['fname']." ".$s['lname'])) . '</option>';
1798     }
1800     $string .= '</select>';
1802     echo $string;
1805 // ----------------------------------------------------------------------------
1807  * DROPDOWN FOR INSURANCE COMPANIES
1809  * build a dropdown with all insurers
1811  * @param int $selected - id for selected record
1812  * @param string $name - the name/id for select form
1813  * @return void - just echo the html encoded string
1814  */
1815 function dropdown_insurance($selected = 0, $name = 'iprovider')
1817     $insurancei = getInsuranceProviders();
1819     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1820     $string .= '<option value="0">Onbekend</option>';
1821     foreach ($insurancei as $iid => $iname) {
1822         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1823         $string .= '<option value="' . attr($iid) . '" '.$sel.' >' . text($iname) . '(' . text($iid) . ')</option>';
1824     }
1826     $string .= '</select>';
1828     echo $string;
1832 // ----------------------------------------------------------------------------
1834  * COUNTRY CODE
1836  * return the name or the country code, function of arguments
1838  * @param int $country_code
1839  * @param string $country_name
1840  * @return string | int - name or code
1841  */
1842 function country_code($country_code = 0, $country_name = '')
1844     $strint = '';
1845     $sqlBindArray = array();
1846     if ($country_code) {
1847         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = ?";
1848         array_push($sqlBindArray, $country_code);
1849     } else {
1850         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = ?";
1851         array_push($sqlBindArray, $country_name);
1852     }
1854     $db = $GLOBALS['adodb']['db'];
1855     $result = $db->Execute($sql, $sqlBindArray);
1856     if ($result && !$result->EOF) {
1857         $strint = $result->fields['res'];
1858     }
1860     return $strint;
1863 function DBToDate($date)
1865     $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1866     return $date;
1870  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1871  * for the given patient on the given date.
1873  * @param int     The PID of the patient.
1874  * @param string  Date in yyyy-mm-dd format.
1875  * @return array  Array of 0-3 insurance_data rows.
1876  */
1877 function getEffectiveInsurances($patient_id, $encdate)
1879     $insarr = array();
1880     foreach (array('primary','secondary','tertiary') as $instype) {
1881         $tmp = sqlQuery(
1882             "SELECT * FROM insurance_data " .
1883             "WHERE pid = ? AND type = ? " .
1884             "AND date <= ? ORDER BY date DESC LIMIT 1",
1885             array($patient_id, $instype, $encdate)
1886         );
1887         if (empty($tmp['provider'])) {
1888             break;
1889         }
1891         $insarr[] = $tmp;
1892     }
1894     return $insarr;
1898  * Get all requisition insurance companies
1901  */
1903 function getAllinsurances($pid)
1905     $insarr = array();
1906     $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number, 
1907            a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer, 
1908                    b.name, c.line1, c.line2, c.city, c.state, c.zip 
1909            FROM `insurance_data` AS a
1910            RIGHT JOIN insurance_companies AS b
1911            ON a.provider = b.id
1912            RIGHT JOIN addresses AS c 
1913            ON a.provider = c.foreign_id
1914            WHERE a.pid = ? ";
1915     $inco = sqlStatement($sql, array($pid));
1917     while ($icl = sqlFetchArray($inco)) {
1918         $insarr[] = $icl;
1919     }
1920     return $insarr;
1924  * Get the patient's balance due. Normally this excludes amounts that are out
1925  * to insurance.  If you want to include what insurance owes, set the second
1926  * parameter to true.
1928  * @param int     The PID of the patient.
1929  * @param boolean Indicates if amounts owed by insurance are to be included.
1930  * @param int     Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1931  * @return number The balance.
1932  */
1933 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1935     $balance = 0;
1936     $bindarray = array($pid);
1937     $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1938       "last_level_closed, stmt_count " .
1939       "FROM form_encounter WHERE pid = ?";
1940     if ($eid) {
1941         $sqlstatement .= " AND encounter = ?";
1942         array_push($bindarray, $eid);
1943     }
1944     $feres = sqlStatement($sqlstatement, $bindarray);
1945     while ($ferow = sqlFetchArray($feres)) {
1946         $encounter = $ferow['encounter'];
1947         $dos = substr($ferow['date'], 0, 10);
1948         $insarr = getEffectiveInsurances($pid, $dos);
1949         $inscount = count($insarr);
1950         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1951             // It's out to insurance so only the co-pay might be due.
1952             $brow = sqlQuery(
1953                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1954                 "pid = ? AND encounter = ? AND " .
1955                 "code_type = 'copay' AND activity = 1",
1956                 array($pid, $encounter)
1957             );
1958             $drow = sqlQuery(
1959                 "SELECT SUM(pay_amount) AS payments " .
1960                 "FROM ar_activity WHERE " .
1961                 "pid = ? AND encounter = ? AND payer_type = 0",
1962                 array($pid, $encounter)
1963             );
1964             $copay = !empty($insarr[0]['copay']) ? $insarr[0]['copay'] * 1 : 0;
1965             $amt = !empty($brow['amount']) ? $brow['amount'] * 1 : 0;
1966             $pay = !empty($drow['payments']) ? $drow['payments'] * 1 : 0;
1967             $ptbal = $copay + $amt - $pay;
1968             if ($ptbal) { // @TODO check if we want to show patient payment credits.
1969                 $balance += $ptbal;
1970             }
1971         } else {
1972             // Including insurance or not out to insurance, everything is due.
1973             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1974             "pid = ? AND encounter = ? AND " .
1975             "activity = 1", array($pid, $encounter));
1976             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1977               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1978               "pid = ? AND encounter = ?", array($pid, $encounter));
1979             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1980               "pid = ? AND encounter = ?", array($pid, $encounter));
1981             $balance += $brow['amount'] + $srow['amount']
1982               - $drow['payments'] - $drow['adjustments'];
1983         }
1984     }
1986     return sprintf('%01.2f', $balance);
1989 // Function to check if patient is deceased.
1990 //  Param:
1991 //    $pid  - patient id
1992 //    $date - date checking if deceased (will default to current date if blank)
1993 //  Return:
1994 //    If deceased, then will return the number of
1995 //      days that patient has been deceased and the deceased date.
1996 //    If not deceased, then will return false.
1997 function is_patient_deceased($pid, $date = '')
2000   // Set date to current if not set
2001     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
2003   // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
2004     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
2005                       "FROM `patient_data` " .
2006                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND 
2007                       `deceased_date` <= ?", array($date,$pid,$date));
2009     if (empty($results)) {
2010         // Patient is alive, so return false
2011         return false;
2012     } else {
2013         // Patient is dead, so return the number of days patient has been deceased.
2014         //  Don't let it be zero days or else will confuse calls to this function.
2015         if ($results['days_deceased'] === 0) {
2016             $results['days_deceased'] = 1;
2017         }
2019         return $results;
2020     }