Display fix: width in manila for demographics (#1909)
[openemr.git] / library / patient.inc
blob8ff0e79bdfdb1b4d29a3fec5f7eb14cd07dfbeed
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         $facility = $facilityService->getById($facid);
195     } else if ($facid == 0) {
196         $facility = $facilityService->getPrimaryBillingLocation();
197     } else {
198         $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
199     }
201     return $facility;
204 // Generate a report title including report name and facility name, address
205 // and phone.
207 function genFacilityTitle($repname = '', $facid = 0)
209     $s = '';
210     $s .= "<table class='ftitletable'>\n";
211     $s .= " <tr>\n";
212     if (empty($logo)) {
213         $s .= "  <td class='ftitlecell1'>$repname</td>\n";
214     } else {
215         $s .= "  <td class='ftitlecell1'>$logo</td>\n";
216         $s .= "  <td class='ftitlecellm'>$repname</td>\n";
217     }
218     $s .= "  <td class='ftitlecell2'>\n";
219     $r = getFacility($facid);
220     if (!empty($r)) {
221         $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
222         if ($r['street']) {
223             $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
224         }
226         if ($r['city'] || $r['state'] || $r['postal_code']) {
227             $s .= "<br />";
228             if ($r['city']) {
229                 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
230             }
232             if ($r['state']) {
233                 if ($r['city']) {
234                     $s .= ", \n";
235                 }
237                 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
238             }
240             if ($r['postal_code']) {
241                 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
242             }
244             $s .= "\n";
245         }
247         if ($r['country_code']) {
248             $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
249         }
251         if (preg_match('/[1-9]/', $r['phone'])) {
252             $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
253         }
254     }
256     $s .= "  </td>\n";
257     $s .= " </tr>\n";
258     $s .= "</table>\n";
259     return $s;
263 GET FACILITIES
265 returns all facilities or just the id for the first one
266 (FACILITY FILTERING (lemonsoftware))
268 @param string - if 'first' return first facility ordered by id
269 @return array | int for 'first' case
271 function getFacilities($first = '')
273     global $facilityService;
275     $fres = $facilityService->getAll();
277     if ($first == 'first') {
278         return $fres[0]['id'];
279     } else {
280         return $fres;
281     }
285 GET SERVICE FACILITIES
287 returns all service_location facilities or just the id for the first one
288 (FACILITY FILTERING (CHEMED))
290 @param string - if 'first' return first facility ordered by id
291 @return array | int for 'first' case
293 function getServiceFacilities($first = '')
295     global $facilityService;
297     $fres = $facilityService->getAllServiceLocations();
299     if ($first == 'first') {
300         return $fres[0]['id'];
301     } else {
302         return $fres;
303     }
306 //(CHEMED) facility filter
307 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
309     $param1 = "";
310     if ($providers_only === 'any') {
311         $param1 = " AND authorized = 1 AND active = 1 ";
312     } else if ($providers_only) {
313         $param1 = " AND authorized = 1 AND calendar = 1 ";
314     }
316     //--------------------------------
317     //(CHEMED) facility filter
318     $param2 = "";
319     if ($facility) {
320         if ($GLOBALS['restrict_user_facility']) {
321             $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))";
322         } else {
323             $param2 = " AND facility_id = '" . add_escape_custom($facility) . "' ";
324         }
325     }
327     //--------------------------------
329     $command = "=";
330     if ($providerID == "%") {
331         $command = "like";
332     }
334     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
335         "from users where username != '' and active = 1 and id $command '" .
336         add_escape_custom($providerID) . "' " . $param1 . $param2;
337     // sort by last name -- JRM June 2008
338     $query .= " ORDER BY lname, fname ";
339     $rez = sqlStatement($query);
340     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
341         $returnval[$iter]=$row;
342     }
344     //if only one result returned take the key/value pairs in array [0] and merge them down into
345     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
347     if ($iter==1) {
348         $akeys = array_keys($returnval[0]);
349         foreach ($akeys as $key) {
350             $returnval[0][$key] = $returnval[0][$key];
351         }
352     }
354     return $returnval;
357 //same as above but does not reduce if only 1 row returned
358 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
360     $param1 = "";
361     if ($providers_only) {
362         $param1 = "AND authorized=1";
363     }
365     $command = "=";
366     if ($providerID == "%") {
367         $command = "like";
368     }
370     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
371         "from users where active = 1 and username != '' and id $command '" .
372         add_escape_custom($providerID) . "' " . $param1;
374     $rez = sqlStatement($query);
375     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
376         $returnval[$iter]=$row;
377     }
379     return $returnval;
382 function getProviderName($providerID)
384     $pi = getProviderInfo($providerID, 'any');
385     if (strlen($pi[0]["lname"]) > 0) {
386         if (strlen($pi[0]["suffix"]) > 0) {
387             $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
388         }
390         return $pi[0]['fname'] . " " . $pi[0]['lname'];
391     }
393     return "";
396 function getProviderId($providerName)
398     $query = "select id from users where username = ?";
399     $rez = sqlStatement($query, array($providerName));
400     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
401         $returnval[$iter]=$row;
402     }
404     return $returnval;
407 function getEthnoRacials()
409     $returnval = array("");
410     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
411     $rez = sqlStatement($sql);
412     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
413         if (($row["ethnoracial"] != "")) {
414             array_push($returnval, $row["ethnoracial"]);
415         }
416     }
418     return $returnval;
421 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
424     if ($dateStart && $dateEnd) {
425         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
426     } else if ($dateStart && !$dateEnd) {
427         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
428     } else if (!$dateStart && $dateEnd) {
429         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
430     } else {
431         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
432     }
434     if ($given == 'tobacco') {
435         $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));
436     }
438     return $res;
441 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
442 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
444     $sql = "select $given from insurance_data as insd " .
445     "left join insurance_companies as ic on ic.id = insd.provider " .
446     "where pid = ? and type = ? order by date DESC limit 1";
447     return sqlQuery($sql, array($pid, $type));
450 function getInsuranceDataByDate(
451     $pid,
452     $date,
453     $type,
454     $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
455 ) {
456  // this must take the date in the following manner: YYYY-MM-DD
457   // this function recalls the insurance value that was most recently enterred from the
458   // given date. it will call up most recent records up to and on the date given,
459   // but not records enterred after the given date
460     $sql = "select $given from insurance_data as insd " .
461     "left join insurance_companies as ic on ic.id = provider " .
462     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
463     "type=? order by date DESC limit 1";
464     return sqlQuery($sql, array($pid,$date,$type));
467 function getEmployerData($pid, $given = "*")
469     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
470     return sqlQuery($sql, array($pid));
473 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
475   // When the limit is exceeded, find out what the unlimited count would be.
476     $GLOBALS['PATIENT_INC_COUNT'] = $count;
477   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
478     if ($limit != "all") {
479         $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
480         $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
481     }
485  * Allow the last name to be followed by a comma and some part of a first name(can
486  *   also place middle name after the first name with a space separating them)
487  * Allows comma alone followed by some part of a first name(can also place middle name
488  *   after the first name with a space separating them).
489  * Allows comma alone preceded by some part of a last name.
490  * If no comma or space, then will search both last name and first name.
491  * If the first letter of either name is capital, searches for name starting
492  *   with given substring (the expected behavior). If it is lower case, it
493  *   searches for the substring anywhere in the name. This applies to either
494  *   last name, first name, and middle name.
495  * Also allows first name followed by middle and/or last name when separated by spaces.
496  * @param string $term
497  * @param string $given
498  * @param string $orderby
499  * @param string $limit
500  * @param string $start
501  * @return array
502  */
503 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")
505     $names = getPatientNameSplit($term);
507     foreach ($names as $key => $val) {
508         if (!empty($val)) {
509             if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
510                 $names[$key] = '%' . $val . '%';
511             } else {
512                 $names[$key] = $val . '%';
513             }
514         }
515     }
517     // Debugging section below
518     //if(array_key_exists('first',$names)) {
519     //    error_log("first name search term :".$names['first']);
520     //}
521     //if(array_key_exists('middle',$names)) {
522     //    error_log("middle name search term :".$names['middle']);
523     //}
524     //if(array_key_exists('last',$names)) {
525     //    error_log("last name search term :".$names['last']);
526     //}
527     // Debugging section above
529     $sqlBindArray = array();
530     if (array_key_exists('last', $names) && $names['last'] == '') {
531         // Do not search last name
532         $where = "fname LIKE ? ";
533         array_push($sqlBindArray, $names['first']);
534         if ($names['middle'] != '') {
535             $where .= "AND mname LIKE ? ";
536             array_push($sqlBindArray, $names['middle']);
537         }
538     } elseif (array_key_exists('first', $names) && $names['first'] == '') {
539         // Do not search first name or middle name
540         $where = "lname LIKE ? ";
541         array_push($sqlBindArray, $names['last']);
542     } elseif ($names['first'] == '' && $names['last'] != '') {
543         // Search both first name and last name with same term
544         $names['first'] = $names['last'];
545         $where = "lname LIKE ? OR fname LIKE ? ";
546         array_push($sqlBindArray, $names['last'], $names['first']);
547     } elseif ($names['middle'] != '') {
548         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
549         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
550     } else {
551         $where = "lname LIKE ? AND fname LIKE ? ";
552         array_push($sqlBindArray, $names['last'], $names['first']);
553     }
555     if (!empty($GLOBALS['pt_restrict_field'])) {
556         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
557             $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
558                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
559                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
560             array_push($sqlBindArray, $_SESSION{"authUser"});
561         }
562     }
564     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
565     if ($limit != "all") {
566         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
567     }
569     $rez = sqlStatement($sql, $sqlBindArray);
571     $returnval=array();
572     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
573         $returnval[$iter] = $row;
574     }
576     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
577     return $returnval;
580  * Accept a string used by a search function expected to find a patient name,
581  * then split up the string if a comma or space exists. Return an array having
582  * from 1 to 3 elements, named first, middle, and last.
583  * See above getPatientLnames() function for details on how the splitting occurs.
584  * @param string $term
585  * @return array
586  */
587 function getPatientNameSplit($term)
589     $term = trim($term);
590     if (strpos($term, ',') !== false) {
591         $names = explode(',', $term);
592         $n['last'] = $names[0];
593         if (strpos(trim($names[1]), ' ') !== false) {
594             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
595         } else {
596             $n['first'] = $names[1];
597         }
598     } elseif (strpos($term, ' ') !== false) {
599         $names = explode(' ', $term);
600         if (count($names) == 1) {
601             $n['last'] = $names[0];
602         } elseif (count($names) == 3) {
603             $n['first'] = $names[0];
604             $n['middle'] = $names[1];
605             $n['last'] = $names[2];
606         } else {
607             // This will handle first and last name or first followed by
608             // multiple names only using just the last of the names in the list.
609             $n['first'] = $names[0];
610             $n['last'] = end($names);
611         }
612     } else {
613         $n['last'] = $term;
614         if (empty($n['last'])) {
615             $n['last'] = '%';
616         }
617     }
619     // Trim whitespace off the names before returning
620     foreach ($n as $key => $val) {
621         $n[$key] = trim($val);
622     }
624     return $n; // associative array containing names
627 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")
630     $sqlBindArray = array();
631     $where = "pubpid LIKE ? ";
632     array_push($sqlBindArray, $pid."%");
633     if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
634         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
635             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
636                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
637                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
638             array_push($sqlBindArray, $_SESSION{"authUser"});
639         }
640     }
642     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
643     if ($limit != "all") {
644         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
645     }
647     $rez = sqlStatement($sql, $sqlBindArray);
648     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
649         $returnval[$iter]=$row;
650     }
652     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
653     return $returnval;
656 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")
658     $layoutCols = sqlStatement(
659         "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
660         array('em\_%')
661     );
663     $sqlBindArray = array();
664     $where = "";
665     for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
666         if ($iter > 0) {
667             $where .= " or ";
668         }
670         $where .= " ".add_escape_custom($row["field_id"])." like ? ";
671         array_push($sqlBindArray, "%".$searchTerm."%");
672     }
674     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
675     if ($limit != "all") {
676         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
677     }
679     $rez = sqlStatement($sql, $sqlBindArray);
680     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
681         $returnval[$iter]=$row;
682     }
684     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
685     return $returnval;
688 function getByPatientDemographicsFilter(
689     $searchFields,
690     $searchTerm = "%",
691     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
692     $orderby = "lname ASC, fname ASC",
693     $limit = "all",
694     $start = "0",
695     $search_service_code = ''
696 ) {
698     $layoutCols = explode('~', $searchFields);
699     $sqlBindArray = array();
700     $where = "";
701     $i = 0;
702     foreach ($layoutCols as $val) {
703         if (empty($val)) {
704             continue;
705         }
707         if ($i > 0) {
708             $where .= " or ";
709         }
711         if ($val == 'pid') {
712             $where .= " ".add_escape_custom($val)." = ? ";
713                 array_push($sqlBindArray, $searchTerm);
714         } else {
715             $where .= " ".add_escape_custom($val)." like ? ";
716                 array_push($sqlBindArray, $searchTerm."%");
717         }
719         $i++;
720     }
722   // If no search terms, ensure valid syntax.
723     if ($i == 0) {
724         $where = "1 = 1";
725     }
727   // If a non-empty service code was given, then restrict to patients who
728   // have been provided that service.  Since the code is used in a LIKE
729   // clause, % and _ wildcards are supported.
730     if ($search_service_code) {
731         $where = "( $where ) AND " .
732         "( SELECT COUNT(*) FROM billing AS b WHERE " .
733         "b.pid = patient_data.pid AND " .
734         "b.activity = 1 AND " .
735         "b.code_type != 'COPAY' AND " .
736         "b.code LIKE ? " .
737         ") > 0";
738         array_push($sqlBindArray, $search_service_code);
739     }
741     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
742     if ($limit != "all") {
743         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
744     }
746     $rez = sqlStatement($sql, $sqlBindArray);
747     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
748         $returnval[$iter]=$row;
749     }
751     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
752     return $returnval;
755 // return a collection of Patient PIDs
756 // new arg style by JRM March 2008
757 // 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")
758 function getPatientPID($args)
760     $pid = "%";
761     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
762     $orderby = "lname ASC, fname ASC";
763     $limit="all";
764     $start="0";
766     // alter default values if defined in the passed in args
767     if (isset($args['pid'])) {
768         $pid = $args['pid'];
769     }
771     if (isset($args['given'])) {
772         $given = $args['given'];
773     }
775     if (isset($args['orderby'])) {
776         $orderby = $args['orderby'];
777     }
779     if (isset($args['limit'])) {
780         $limit = $args['limit'];
781     }
783     if (isset($args['start'])) {
784         $start = $args['start'];
785     }
787     $command = "=";
788     if ($pid == -1) {
789         $pid = "%";
790     } elseif (empty($pid)) {
791         $pid = "NULL";
792     }
794     if (strstr($pid, "%")) {
795         $command = "like";
796     }
798     $sql="select $given from patient_data where pid $command '" . add_escape_custom($pid) . "' order by $orderby";
799     if ($limit != "all") {
800         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
801     }
803     $rez = sqlStatement($sql);
804     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
805         $returnval[$iter]=$row;
806     }
808     return $returnval;
811 /* return a patient's name in the format LAST, FIRST */
812 function getPatientName($pid)
814     if (empty($pid)) {
815         return "";
816     }
818     $patientData = getPatientPID(array("pid"=>$pid));
819     if (empty($patientData[0]['lname'])) {
820         return "";
821     }
823     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
824     return $patientName;
827 /* find patient data by DOB */
828 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
830     $sqlBindArray = array();
831     $where = "DOB like ? ";
832     array_push($sqlBindArray, $DOB."%");
833     if (!empty($GLOBALS['pt_restrict_field'])) {
834         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
835             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
836                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
837                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
838             array_push($sqlBindArray, $_SESSION{"authUser"});
839         }
840     }
842     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
844     if ($limit != "all") {
845         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
846     }
848     $rez = sqlStatement($sql, $sqlBindArray);
849     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
850         $returnval[$iter]=$row;
851     }
853     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
854     return $returnval;
857 /* find patient data by SSN */
858 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
860     $sqlBindArray = array();
861     $where = "ss LIKE ?";
862     array_push($sqlBindArray, $ss."%");
863     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
864     if ($limit != "all") {
865         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
866     }
868     $rez = sqlStatement($sql, $sqlBindArray);
869     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
870         $returnval[$iter]=$row;
871     }
873     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
874     return $returnval;
877 //(CHEMED) Search by phone number
878 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
880     $phone = preg_replace("/[[:punct:]]/", "", $phone);
881     $sqlBindArray = array();
882     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
883     array_push($sqlBindArray, $phone);
884     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
885     if ($limit != "all") {
886         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
887     }
889     $rez = sqlStatement($sql, $sqlBindArray);
890     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
891         $returnval[$iter]=$row;
892     }
894     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
895     return $returnval;
898 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
900     $sql="select $given from patient_data order by $orderby";
902     if ($limit != "all") {
903         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
904     }
906     $rez = sqlStatement($sql);
907     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
908         $returnval[$iter]=$row;
909     }
911     return $returnval;
914 //----------------------input functions
915 function newPatientData(
916     $db_id = "",
917     $title = "",
918     $fname = "",
919     $lname = "",
920     $mname = "",
921     $sex = "",
922     $DOB = "",
923     $street = "",
924     $postal_code = "",
925     $city = "",
926     $state = "",
927     $country_code = "",
928     $ss = "",
929     $occupation = "",
930     $phone_home = "",
931     $phone_biz = "",
932     $phone_contact = "",
933     $status = "",
934     $contact_relationship = "",
935     $referrer = "",
936     $referrerID = "",
937     $email = "",
938     $language = "",
939     $ethnoracial = "",
940     $interpretter = "",
941     $migrantseasonal = "",
942     $family_size = "",
943     $monthly_income = "",
944     $homeless = "",
945     $financial_review = "",
946     $pubpid = "",
947     $pid = "MAX(pid)+1",
948     $providerID = "",
949     $genericname1 = "",
950     $genericval1 = "",
951     $genericname2 = "",
952     $genericval2 = "",
953     $billing_note = "",
954     $phone_cell = "",
955     $hipaa_mail = "",
956     $hipaa_voice = "",
957     $squad = 0,
958     $pharmacy_id = 0,
959     $drivers_license = "",
960     $hipaa_notice = "",
961     $hipaa_message = "",
962     $regdate = ""
963 ) {
965     $fitness = 0;
966     $referral_source = '';
967     if ($pid) {
968         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = ?", array($pid));
969         // Check for brain damage:
970         if ($db_id != $rez['id']) {
971             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
972               text($rez['id']) . "' to '" . text($db_id) . "' for pid '" . text($pid) . "'";
973             die($errmsg);
974         }
976         $fitness = $rez['fitness'];
977         $referral_source = $rez['referral_source'];
978     }
980     // Get the default price level.
981     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
982       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
983     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
985     $query = ("replace into patient_data set
986         id='" . add_escape_custom($db_id) . "',
987         title='" . add_escape_custom($title) . "',
988         fname='" . add_escape_custom($fname) . "',
989         lname='" . add_escape_custom($lname) . "',
990         mname='" . add_escape_custom($mname) . "',
991         sex='" . add_escape_custom($sex) . "',
992         DOB='" . add_escape_custom($DOB) . "',
993         street='" . add_escape_custom($street) . "',
994         postal_code='" . add_escape_custom($postal_code) . "',
995         city='" . add_escape_custom($city) . "',
996         state='" . add_escape_custom($state) . "',
997         country_code='" . add_escape_custom($country_code) . "',
998         drivers_license='" . add_escape_custom($drivers_license) . "',
999         ss='" . add_escape_custom($ss) . "',
1000         occupation='" . add_escape_custom($occupation) . "',
1001         phone_home='" . add_escape_custom($phone_home) . "',
1002         phone_biz='" . add_escape_custom($phone_biz) . "',
1003         phone_contact='" . add_escape_custom($phone_contact) . "',
1004         status='" . add_escape_custom($status) . "',
1005         contact_relationship='" . add_escape_custom($contact_relationship) . "',
1006         referrer='" . add_escape_custom($referrer) . "',
1007         referrerID='" . add_escape_custom($referrerID) . "',
1008         email='" . add_escape_custom($email) . "',
1009         language='" . add_escape_custom($language) . "',
1010         ethnoracial='" . add_escape_custom($ethnoracial) . "',
1011         interpretter='" . add_escape_custom($interpretter) . "',
1012         migrantseasonal='" . add_escape_custom($migrantseasonal) . "',
1013         family_size='" . add_escape_custom($family_size) . "',
1014         monthly_income='" . add_escape_custom($monthly_income) . "',
1015         homeless='" . add_escape_custom($homeless) . "',
1016         financial_review='" . add_escape_custom($financial_review) . "',
1017         pubpid='" . add_escape_custom($pubpid) . "',
1018         pid= '" . add_escape_custom($pid) . "',
1019         providerID = '" . add_escape_custom($providerID) . "',
1020         genericname1 = '" . add_escape_custom($genericname1) . "',
1021         genericval1 = '" . add_escape_custom($genericval1) . "',
1022         genericname2 = '" . add_escape_custom($genericname2) . "',
1023         genericval2 = '" . add_escape_custom($genericval2) . "',
1024         billing_note= '" . add_escape_custom($billing_note) . "',
1025         phone_cell = '" . add_escape_custom($phone_cell) . "',
1026         pharmacy_id = '" . add_escape_custom($pharmacy_id) . "',
1027         hipaa_mail = '" . add_escape_custom($hipaa_mail) . "',
1028         hipaa_voice = '" . add_escape_custom($hipaa_voice) . "',
1029         hipaa_notice = '" . add_escape_custom($hipaa_notice) . "',
1030         hipaa_message = '" . add_escape_custom($hipaa_message) . "',
1031         squad = '" . add_escape_custom($squad) . "',
1032         fitness='" . add_escape_custom($fitness) . "',
1033         referral_source='" . add_escape_custom($referral_source) . "',
1034         regdate='" . add_escape_custom($regdate) . "',
1035         pricelevel='" . add_escape_custom($pricelevel) . "',
1036         date=NOW()");
1038     $id = sqlInsert($query);
1040     if (!$db_id) {
1041       // find the last inserted id for new patient case
1042         $db_id = getSqlLastID();
1043     }
1045     $foo = sqlQuery("select pid from patient_data where id=? order by date limit 0,1", array($id));
1047     return $foo['pid'];
1050 // Supported input date formats are:
1051 //   mm/dd/yyyy
1052 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1053 //   yyyy/mm/dd
1054 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1056 function fixDate($date, $default = "0000-00-00")
1058     $fixed_date = $default;
1059     $date = trim($date);
1060     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1061         $dmy = preg_split("'[/.-]'", $date);
1062         if ($dmy[0] > 99) {
1063             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1064         } else {
1065             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1066                 if ($dmy[2] < 1000) {
1067                     $dmy[2] += 1900;
1068                 }
1070                 if ($dmy[2] < 1910) {
1071                     $dmy[2] += 100;
1072                 }
1073             }
1075             // phone_country_code indicates format of ambiguous input dates.
1076             if ($GLOBALS['phone_country_code'] == 1) {
1077                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1078             } else {
1079                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1080             }
1081         }
1082     }
1084     return $fixed_date;
1087 function pdValueOrNull($key, $value)
1089     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1090     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1091     (empty($value) || $value == '0000-00-00')) {
1092         return "NULL";
1093     } else {
1094         return "'" . add_escape_custom($value) . "'";
1095     }
1098 // Create or update patient data from an array.
1100 function updatePatientData($pid, $new, $create = false)
1102   /*******************************************************************
1103     $real = getPatientData($pid);
1104     foreach ($new as $key => $value)
1105         $real[$key] = $value;
1106     $real['date'] = "'+NOW()+'";
1107     $real['id'] = "";
1108     $sql = "insert into patient_data set ";
1109     foreach ($real as $key => $value)
1110         $sql .= $key." = '$value', ";
1111     $sql = substr($sql, 0, -2);
1112     return sqlInsert($sql);
1113   *******************************************************************/
1115   // The above was broken, though seems intent to insert a new patient_data
1116   // row for each update.  A good idea, but nothing is doing that yet so
1117   // the code below does not yet attempt it.
1119     if ($create) {
1120         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1121         foreach ($new as $key => $value) {
1122             if ($key == 'id') {
1123                 continue;
1124             }
1126             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1127         }
1129         $db_id = sqlInsert($sql);
1130     } else {
1131         $db_id = $new['id'];
1132         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1133         // Check for brain damage:
1134         if ($pid != $rez['pid']) {
1135             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1136             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1137             die($errmsg);
1138         }
1140         $sql = "UPDATE patient_data SET date = NOW()";
1141         foreach ($new as $key => $value) {
1142             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1143         }
1145         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1146         sqlStatement($sql);
1147     }
1149     return $db_id;
1152 function newEmployerData(
1153     $pid,
1154     $name = "",
1155     $street = "",
1156     $postal_code = "",
1157     $city = "",
1158     $state = "",
1159     $country = ""
1160 ) {
1162     return sqlInsert("insert into employer_data set
1163         name='" . add_escape_custom($name) . "',
1164         street='" . add_escape_custom($street) . "',
1165         postal_code='" . add_escape_custom($postal_code) . "',
1166         city='" . add_escape_custom($city) . "',
1167         state='" . add_escape_custom($state) . "',
1168         country='" . add_escape_custom($country) . "',
1169         pid='" . add_escape_custom($pid) . "',
1170         date=NOW()
1171         ");
1174 // Create or update employer data from an array.
1176 function updateEmployerData($pid, $new, $create = false)
1178     $colnames = array('name','street','city','state','postal_code','country');
1180     if ($create) {
1181         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1182         foreach ($colnames as $key) {
1183             $value = isset($new[$key]) ? $new[$key] : '';
1184             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1185         }
1187         return sqlInsert("INSERT INTO employer_data SET $set");
1188     } else {
1189         $set = '';
1190         $old = getEmployerData($pid);
1191         $modified = false;
1192         foreach ($colnames as $key) {
1193             $value = empty($old[$key]) ? '' : $old[$key];
1194             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1195                 $value = $new[$key];
1196                 $modified = true;
1197             }
1199             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1200         }
1202         if ($modified) {
1203             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1204             return sqlInsert("INSERT INTO employer_data SET $set");
1205         }
1207         return $old['id'];
1208     }
1211 // This updates or adds the given insurance data info, while retaining any
1212 // previously added insurance_data rows that should be preserved.
1213 // This does not directly support the maintenance of non-current insurance.
1215 function newInsuranceData(
1216     $pid,
1217     $type = "",
1218     $provider = "",
1219     $policy_number = "",
1220     $group_number = "",
1221     $plan_name = "",
1222     $subscriber_lname = "",
1223     $subscriber_mname = "",
1224     $subscriber_fname = "",
1225     $subscriber_relationship = "",
1226     $subscriber_ss = "",
1227     $subscriber_DOB = "",
1228     $subscriber_street = "",
1229     $subscriber_postal_code = "",
1230     $subscriber_city = "",
1231     $subscriber_state = "",
1232     $subscriber_country = "",
1233     $subscriber_phone = "",
1234     $subscriber_employer = "",
1235     $subscriber_employer_street = "",
1236     $subscriber_employer_city = "",
1237     $subscriber_employer_postal_code = "",
1238     $subscriber_employer_state = "",
1239     $subscriber_employer_country = "",
1240     $copay = "",
1241     $subscriber_sex = "",
1242     $effective_date = "0000-00-00",
1243     $accept_assignment = "TRUE",
1244     $policy_type = ""
1245 ) {
1247     if (strlen($type) <= 0) {
1248         return false;
1249     }
1251     // If empty dates were passed, then zero them.
1252     if (empty($effective_date)) {
1253         $effective_date = '0000-00-00';
1254     }
1255     if (empty($subscriber_DOB)) {
1256         $subscriber_DOB = '0000-00-00';
1257     }
1259     $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1260     "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1261     $idrow = sqlFetchArray($idres);
1263   // Replace the most recent entry in any of the following cases:
1264   // * Its effective date is >= this effective date.
1265   // * It is the first entry and it has no (insurance) provider.
1266   // * There is no encounter that is earlier than the new effective date but
1267   //   on or after the old effective date.
1268   // Otherwise insert a new entry.
1270     $replace = false;
1271     if ($idrow) {
1272         if (strcmp($idrow['date'], $effective_date) > 0) {
1273             $replace = true;
1274         } else {
1275             if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1276                 $replace = true;
1277             } else {
1278                 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1279                 "WHERE pid = ? AND date < ? AND " .
1280                 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1281                 if ($ferow['count'] == 0) {
1282                     $replace = true;
1283                 }
1284             }
1285         }
1286     }
1288     if ($replace) {
1289         // TBD: This is a bit dangerous in that a typo in entering the effective
1290         // date can wipe out previous insurance history.  So we want some data
1291         // entry validation somewhere.
1292         sqlStatement("DELETE FROM insurance_data WHERE " .
1293         "pid = ? AND type = ? AND date >= ? AND " .
1294         "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1296         $data = array();
1297         $data['type'] = $type;
1298         $data['provider'] = $provider;
1299         $data['policy_number'] = $policy_number;
1300         $data['group_number'] = $group_number;
1301         $data['plan_name'] = $plan_name;
1302         $data['subscriber_lname'] = $subscriber_lname;
1303         $data['subscriber_mname'] = $subscriber_mname;
1304         $data['subscriber_fname'] = $subscriber_fname;
1305         $data['subscriber_relationship'] = $subscriber_relationship;
1306         $data['subscriber_ss'] = $subscriber_ss;
1307         $data['subscriber_DOB'] = $subscriber_DOB;
1308         $data['subscriber_street'] = $subscriber_street;
1309         $data['subscriber_postal_code'] = $subscriber_postal_code;
1310         $data['subscriber_city'] = $subscriber_city;
1311         $data['subscriber_state'] = $subscriber_state;
1312         $data['subscriber_country'] = $subscriber_country;
1313         $data['subscriber_phone'] = $subscriber_phone;
1314         $data['subscriber_employer'] = $subscriber_employer;
1315         $data['subscriber_employer_city'] = $subscriber_employer_city;
1316         $data['subscriber_employer_street'] = $subscriber_employer_street;
1317         $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1318         $data['subscriber_employer_state'] = $subscriber_employer_state;
1319         $data['subscriber_employer_country'] = $subscriber_employer_country;
1320         $data['copay'] = $copay;
1321         $data['subscriber_sex'] = $subscriber_sex;
1322         $data['pid'] = $pid;
1323         $data['date'] = $effective_date;
1324         $data['accept_assignment'] = $accept_assignment;
1325         $data['policy_type'] = $policy_type;
1326         updateInsuranceData($idrow['id'], $data);
1327         return $idrow['id'];
1328     } else {
1329         return sqlInsert("INSERT INTO insurance_data SET
1330       type = '" . add_escape_custom($type) . "',
1331       provider = '" . add_escape_custom($provider) . "',
1332       policy_number = '" . add_escape_custom($policy_number) . "',
1333       group_number = '" . add_escape_custom($group_number) . "',
1334       plan_name = '" . add_escape_custom($plan_name) . "',
1335       subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1336       subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1337       subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1338       subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1339       subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1340       subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1341       subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1342       subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1343       subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1344       subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1345       subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1346       subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1347       subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1348       subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1349       subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1350       subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1351       subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1352       subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1353       copay = '" . add_escape_custom($copay) . "',
1354       subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1355       pid = '" . add_escape_custom($pid) . "',
1356       date = '" . add_escape_custom($effective_date) . "',
1357       accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1358       policy_type = '" . add_escape_custom($policy_type) . "'
1359     ");
1360     }
1363 // This is used internally only.
1364 function updateInsuranceData($id, $new)
1366     $fields = sqlListFields("insurance_data");
1367     $use = array();
1369     foreach ($new as $key => $value) {
1370         if (in_array($key, $fields)) {
1371             $use[$key] = $value;
1372         }
1373     }
1375     $sql = "UPDATE insurance_data SET ";
1376     foreach ($use as $key => $value) {
1377         $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1378     }
1380     $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1382     sqlStatement($sql);
1385 function newHistoryData($pid, $new = false)
1387     $arraySqlBind = array();
1388     $sql = "insert into history_data set pid = ?, date = NOW()";
1389     array_push($arraySqlBind, $pid);
1390     if ($new) {
1391         foreach ($new as $key => $value) {
1392             array_push($arraySqlBind, $value);
1393             $sql .= ", `$key` = ?";
1394         }
1395     }
1397     return sqlInsert($sql, $arraySqlBind);
1400 function updateHistoryData($pid, $new)
1402     $real = getHistoryData($pid);
1403     foreach ($new as $key => $value) {
1404         $real[$key] = $value;
1405     }
1407     $real['id'] = "";
1408     // need to unset date, so can reset it below
1409     unset($real['date']);
1411     $arraySqlBind = array();
1412     $sql = "insert into history_data set `date` = NOW(), ";
1413     foreach ($real as $key => $value) {
1414         array_push($arraySqlBind, $value);
1415         $sql .= "`$key` = ?, ";
1416     }
1418     $sql = substr($sql, 0, -2);
1420     return sqlInsert($sql, $arraySqlBind);
1423 // Returns Age
1424 //   in months if < 2 years old
1425 //   in years  if > 2 years old
1426 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1427 // (optional) nowYMD is a date in YYYYMMDD format
1428 function getPatientAge($dobYMD, $nowYMD = null)
1430     // strip any dashes from the DOB
1431     $dobYMD = preg_replace("/-/", "", $dobYMD);
1432     $dobDay = substr($dobYMD, 6, 2);
1433     $dobMonth = substr($dobYMD, 4, 2);
1434     $dobYear = substr($dobYMD, 0, 4);
1436     // set the 'now' date values
1437     if ($nowYMD == null) {
1438         $nowDay = date("d");
1439         $nowMonth = date("m");
1440         $nowYear = date("Y");
1441     } else {
1442         $nowDay = substr($nowYMD, 6, 2);
1443         $nowMonth = substr($nowYMD, 4, 2);
1444         $nowYear = substr($nowYMD, 0, 4);
1445     }
1447     $dayDiff = $nowDay - $dobDay;
1448     $monthDiff = $nowMonth - $dobMonth;
1449     $yearDiff = $nowYear - $dobYear;
1451     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1453     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1454     if ($dayDiff<0) {
1455         $ageInMonths-=1;
1456     }
1458     if ($ageInMonths > 24) {
1459         $age = $yearDiff;
1460         if (($monthDiff == 0) && ($dayDiff < 0)) {
1461             $age -= 1;
1462         } else if ($monthDiff < 0) {
1463             $age -= 1;
1464         }
1465     } else {
1466         $age = "$ageInMonths " . xl('month');
1467     }
1469     return $age;
1473  * Wrapper to make sure the clinical rules dates formats corresponds to the
1474  * format expected by getPatientAgeYMD
1476  * @param  string  $dob     date of birth
1477  * @param  string  $target  date to calculate age on
1478  * @return array containing
1479  *      age - decimal age in years
1480  *      age_in_months - decimal age in months
1481  *      ageinYMD - formatted string #y #m #d */
1482 function parseAgeInfo($dob, $target)
1484     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1485     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1486     ;
1487     // Prepare target (Y-M-D H:M:S)
1488     $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1490     return getPatientAgeYMD($dateDOB, $dateTarget);
1495  * @param type $dob
1496  * @param type $date
1497  * @return array containing
1498  *      age - decimal age in years
1499  *      age_in_months - decimal age in months
1500  *      ageinYMD - formatted string #y #m #d
1501  */
1502 function getPatientAgeYMD($dob, $date = null)
1505     if ($date == null) {
1506         $daynow = date("d");
1507         $monthnow = date("m");
1508         $yearnow = date("Y");
1509         $datenow=$yearnow.$monthnow.$daynow;
1510     } else {
1511         $datenow=preg_replace("/-/", "", $date);
1512         $yearnow=substr($datenow, 0, 4);
1513         $monthnow=substr($datenow, 4, 2);
1514         $daynow=substr($datenow, 6, 2);
1515         $datenow=$yearnow.$monthnow.$daynow;
1516     }
1518     $dob=preg_replace("/-/", "", $dob);
1519     $dobyear=substr($dob, 0, 4);
1520     $dobmonth=substr($dob, 4, 2);
1521     $dobday=substr($dob, 6, 2);
1522     $dob=$dobyear.$dobmonth.$dobday;
1524     //to compensate for 30, 31, 28, 29 days/month
1525     $mo=$monthnow; //to avoid confusion with later calculation
1527     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1
1528         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1529     } // look at April, June, September, November for calculation.  These months only have 30 days.
1530     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1531         $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1532         if (is_int($check_leap_Y)) {
1533             $nd=29;
1534         } //If it true then this is the leap year
1535         else {
1536             $nd=28;
1537         } //otherwise, it is not a leap year.
1538     } else {
1539         $nd=31;
1540     } // other months have 31 days
1542     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1543     if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1544         $age_year = $yearnow - $dobyear - 1;
1545         if ($daynow < $dobday) {
1546             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1547             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1548         } else {
1549             $months_since_birthday=12 - $dobmonth + $monthnow;
1550             $days_since_dobday=$daynow - $dobday;
1551         }
1552     } else // if patient has had birthday this calandar year
1553     {
1554         $age_year = $yearnow - $dobyear;
1555         if ($daynow < $dobday) {
1556             $months_since_birthday=$monthnow - $dobmonth -1;
1557             $days_since_dobday=$nd - $dobday + $daynow;
1558         } else {
1559             $months_since_birthday=$monthnow - $dobmonth;
1560             $days_since_dobday=$daynow - $dobday;
1561         }
1562     }
1564     $day_as_month_decimal = $days_since_dobday / 30;
1565     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1566     $month_as_year_decimal = $months_since_birthday_float / 12;
1567     $age_float = $age_year + $month_as_year_decimal;
1569     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1570     $age_in_months = round($age_in_months, 2);  //round the months to xx.xx 2 floating points
1571     $age = round($age_float, 2);
1573     // round the years to 2 floating points
1574     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1575     return compact('age', 'age_in_months', 'ageinYMD');
1578 // Returns Age in days
1579 //   in months if < 2 years old
1580 //   in years  if > 2 years old
1581 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1582 // (optional) nowYMD is a date in YYYYMMDD format
1583 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1585     $age = -1;
1587     // strip any dashes from the DOB
1588     $dobYMD = preg_replace("/-/", "", $dobYMD);
1589     $dobDay = substr($dobYMD, 6, 2);
1590     $dobMonth = substr($dobYMD, 4, 2);
1591     $dobYear = substr($dobYMD, 0, 4);
1593     // set the 'now' date values
1594     if ($nowYMD == null) {
1595         $nowDay = date("d");
1596         $nowMonth = date("m");
1597         $nowYear = date("Y");
1598     } else {
1599         $nowDay = substr($nowYMD, 6, 2);
1600         $nowMonth = substr($nowYMD, 4, 2);
1601         $nowYear = substr($nowYMD, 0, 4);
1602     }
1604     // do the date math
1605     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1606     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1607     $timediff = $nowtime - $dobtime;
1608     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1610     return $age;
1613  * Returns a string to be used to display a patient's age
1615  * @param type $dobYMD
1616  * @param type $asOfYMD
1617  * @return string suitable for displaying patient's age based on preferences
1618  */
1619 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1621     if ($GLOBALS['age_display_format']=='1') {
1622         $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1623         if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1624             return $ageYMD['ageinYMD'];
1625         } else {
1626             return getPatientAge($dobYMD, $asOfYMD);
1627         }
1628     } else {
1629         return getPatientAge($dobYMD, $asOfYMD);
1630     }
1632 function dateToDB($date)
1634     $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1635     return $date;
1639 // ----------------------------------------------------------------------------
1641  * DROPDOWN FOR COUNTRIES
1643  * build a dropdown with all countries from geo_country_reference
1645  * @param int $selected - id for selected record
1646  * @param string $name - the name/id for select form
1647  * @return void - just echo the html encoded string
1648  */
1649 function dropdown_countries($selected = 0, $name = 'country_code')
1651     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1653     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1654     while ($row = sqlFetchArray($r)) {
1655         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1656         $string .= "<option value='" . attr($row['countries_id']) . "' $sufix>" . text($row['countries_name']) . "</option>";
1657     }
1659     $string .= '</select>';
1660     echo $string;
1664 // ----------------------------------------------------------------------------
1666  * DROPDOWN FOR YES/NO
1668  * build a dropdown with two options (yes - 1, no - 0)
1670  * @param int $selected - id for selected record
1671  * @param string $name - the name/id for select form
1672  * @return void - just echo the html encoded string
1673  */
1674 function dropdown_yesno($selected = 0, $name = 'yesno')
1676     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1678     $selected = (int)$selected;
1679     if ($selected == 0) {
1680         $sel1 = 'selected="selected"';
1681         $sel2 = '';
1682     } else {
1683         $sel2 = 'selected="selected"';
1684         $sel1 = '';
1685     }
1687         $string .= "<option value='0' $sel1>" .xlt('No'). "</option>";
1688         $string .= "<option value='1' $sel2>" .xlt('Yes'). "</option>";
1689         $string .= '</select>';
1691         echo $string;
1694 // ----------------------------------------------------------------------------
1696  * DROPDOWN FOR MALE/FEMALE options
1698  * build a dropdown with three options (unselected/male/female)
1700  * @param int $selected - id for selected record
1701  * @param string $name - the name/id for select form
1702  * @return void - just echo the html encoded string
1703  */
1704 function dropdown_sex($selected = 0, $name = 'sex')
1706     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1708     if ($selected == 1) {
1709         $sel1 = 'selected="selected"';
1710         $sel2 = '';
1711         $sel0 = '';
1712     } else if ($selected == 2) {
1713         $sel2 = 'selected="selected"';
1714         $sel1 = '';
1715         $sel0 = '';
1716     } else {
1717             $sel0 = 'selected="selected"';
1718             $sel1 = '';
1719             $sel2 = '';
1720     }
1722         $string .= "<option value='0' $sel0>" .xlt('Unselected'). "</option>";
1723         $string .= "<option value='1' $sel1>" .xlt('Male'). "</option>";
1724         $string .= "<option value='2' $sel2>" .xlt('Female'). "</option>";
1725         $string .= '</select>';
1727         echo $string;
1730 // ----------------------------------------------------------------------------
1732  * DROPDOWN FOR MARITAL STATUS
1734  * build a dropdown with marital status
1736  * @param int $selected - id for selected record
1737  * @param string $name - the name/id for select form
1738  * @return void - just echo the html encoded string
1739  */
1740 function dropdown_marital($selected = 0, $name = 'status')
1742     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1744     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1746     foreach ($statii as $st) {
1747         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1748         $string .= '<option value="' . attr($st) . '" '.$sel.' >' .xlt($st). '</option>';
1749     }
1751     $string .= '</select>';
1753     echo $string;
1756 // ----------------------------------------------------------------------------
1758  * DROPDOWN FOR PROVIDERS
1760  * build a dropdown with all providers
1762  * @param int $selected - id for selected record
1763  * @param string $name - the name/id for select form
1764  * @return void - just echo the html encoded string
1765  */
1766 function dropdown_providers($selected = 0, $name = 'status')
1768     $provideri = getProviderInfo();
1770     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1771     $string .= '<option value="">' .xlt('Unassigned'). '</option>';
1772     foreach ($provideri as $s) {
1773         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1774         $string .= '<option value="' . attr($s['id']) . '" '.$sel.' >' . text(ucwords($s['fname']." ".$s['lname'])) . '</option>';
1775     }
1777     $string .= '</select>';
1779     echo $string;
1782 // ----------------------------------------------------------------------------
1784  * DROPDOWN FOR INSURANCE COMPANIES
1786  * build a dropdown with all insurers
1788  * @param int $selected - id for selected record
1789  * @param string $name - the name/id for select form
1790  * @return void - just echo the html encoded string
1791  */
1792 function dropdown_insurance($selected = 0, $name = 'iprovider')
1794     $insurancei = getInsuranceProviders();
1796     $string = "<select name='" . attr($name) . "' id='" . attr($name) . "'>";
1797     $string .= '<option value="0">Onbekend</option>';
1798     foreach ($insurancei as $iid => $iname) {
1799         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1800         $string .= '<option value="' . attr($iid) . '" '.$sel.' >' . text($iname) . '(' . text($iid) . ')</option>';
1801     }
1803     $string .= '</select>';
1805     echo $string;
1809 // ----------------------------------------------------------------------------
1811  * COUNTRY CODE
1813  * return the name or the country code, function of arguments
1815  * @param int $country_code
1816  * @param string $country_name
1817  * @return string | int - name or code
1818  */
1819 function country_code($country_code = 0, $country_name = '')
1821     $strint = '';
1822     $sqlBindArray = array();
1823     if ($country_code) {
1824         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = ?";
1825         array_push($sqlBindArray, $country_code);
1826     } else {
1827         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = ?";
1828         array_push($sqlBindArray, $country_name);
1829     }
1831     $db = $GLOBALS['adodb']['db'];
1832     $result = $db->Execute($sql, $sqlBindArray);
1833     if ($result && !$result->EOF) {
1834         $strint = $result->fields['res'];
1835     }
1837     return $strint;
1840 function DBToDate($date)
1842     $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1843     return $date;
1847  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1848  * for the given patient on the given date.
1850  * @param int     The PID of the patient.
1851  * @param string  Date in yyyy-mm-dd format.
1852  * @return array  Array of 0-3 insurance_data rows.
1853  */
1854 function getEffectiveInsurances($patient_id, $encdate)
1856     $insarr = array();
1857     foreach (array('primary','secondary','tertiary') as $instype) {
1858         $tmp = sqlQuery(
1859             "SELECT * FROM insurance_data " .
1860             "WHERE pid = ? AND type = ? " .
1861             "AND date <= ? ORDER BY date DESC LIMIT 1",
1862             array($patient_id, $instype, $encdate)
1863         );
1864         if (empty($tmp['provider'])) {
1865             break;
1866         }
1868         $insarr[] = $tmp;
1869     }
1871     return $insarr;
1875  * Get all requisition insurance companies
1878  */
1880 function getAllinsurances($pid)
1882     $insarr = array();
1883     $sql = "SELECT a.type, a.provider, a.plan_name, a.policy_number, a.group_number, 
1884            a.subscriber_lname, a.subscriber_fname, a.subscriber_relationship, a.subscriber_employer, 
1885                    b.name, c.line1, c.line2, c.city, c.state, c.zip 
1886            FROM `insurance_data` AS a
1887            RIGHT JOIN insurance_companies AS b
1888            ON a.provider = b.id
1889            RIGHT JOIN addresses AS c 
1890            ON a.provider = c.foreign_id
1891            WHERE a.pid = ? ";
1892     $inco = sqlStatement($sql, array($pid));
1894     while ($icl = sqlFetchArray($inco)) {
1895         $insarr[] = $icl;
1896     }
1897     return $insarr;
1901  * Get the patient's balance due. Normally this excludes amounts that are out
1902  * to insurance.  If you want to include what insurance owes, set the second
1903  * parameter to true.
1905  * @param int     The PID of the patient.
1906  * @param boolean Indicates if amounts owed by insurance are to be included.
1907  * @param int     Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1908  * @return number The balance.
1909  */
1910 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1912     $balance = 0;
1913     $bindarray = array($pid);
1914     $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1915       "last_level_closed, stmt_count " .
1916       "FROM form_encounter WHERE pid = ?";
1917     if ($eid) {
1918         $sqlstatement .= " AND encounter = ?";
1919         array_push($bindarray, $eid);
1920     }
1921     $feres = sqlStatement($sqlstatement, $bindarray);
1922     while ($ferow = sqlFetchArray($feres)) {
1923         $encounter = $ferow['encounter'];
1924         $dos = substr($ferow['date'], 0, 10);
1925         $insarr = getEffectiveInsurances($pid, $dos);
1926         $inscount = count($insarr);
1927         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1928             // It's out to insurance so only the co-pay might be due.
1929             $brow = sqlQuery(
1930                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1931                 "pid = ? AND encounter = ? AND " .
1932                 "code_type = 'copay' AND activity = 1",
1933                 array($pid, $encounter)
1934             );
1935             $drow = sqlQuery(
1936                 "SELECT SUM(pay_amount) AS payments " .
1937                 "FROM ar_activity WHERE " .
1938                 "pid = ? AND encounter = ? AND payer_type = 0",
1939                 array($pid, $encounter)
1940             );
1941             $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1942             if ($ptbal > 0) {
1943                 $balance += $ptbal;
1944             }
1945         } else {
1946             // Including insurance or not out to insurance, everything is due.
1947             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1948             "pid = ? AND encounter = ? AND " .
1949             "activity = 1", array($pid, $encounter));
1950             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1951               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1952               "pid = ? AND encounter = ?", array($pid, $encounter));
1953             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1954               "pid = ? AND encounter = ?", array($pid, $encounter));
1955             $balance += $brow['amount'] + $srow['amount']
1956               - $drow['payments'] - $drow['adjustments'];
1957         }
1958     }
1960     return sprintf('%01.2f', $balance);
1963 // Function to check if patient is deceased.
1964 //  Param:
1965 //    $pid  - patient id
1966 //    $date - date checking if deceased (will default to current date if blank)
1967 //  Return:
1968 //    If deceased, then will return the number of
1969 //      days that patient has been deceased and the deceased date.
1970 //    If not deceased, then will return false.
1971 function is_patient_deceased($pid, $date = '')
1974   // Set date to current if not set
1975     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1977   // Query for deceased status (if person is deceased gets days_deceased and date_deceased)
1978     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) AS `days_deceased`, `deceased_date` AS `date_deceased` " .
1979                       "FROM `patient_data` " .
1980                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND 
1981                       `deceased_date` <= ?", array($date,$pid,$date));
1983     if (empty($results)) {
1984         // Patient is alive, so return false
1985         return false;
1986     } else {
1987         // Patient is dead, so return the number of days patient has been deceased.
1988         //  Don't let it be zero days or else will confuse calls to this function.
1989         if ($results['days_deceased'] === 0) {
1990             $results['days_deceased'] = 1;
1991         }
1993         return $results;
1994     }