Merge pull request #1650 from bradymiller/docker-dev-env_2
[openemr.git] / library / patient.inc
blobc60d02b19172784368bc271bb9839d47b851944d
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 = $facility
322           OR  $facility IN
323                 (select facility_id
324                 from users_facility
325                 where tablename = 'users'
326                 and table_id = id)
327                 )
328           ";
329         } else {
330             $param2 = " AND facility_id = $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     } else if ($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     } else if (!$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 '$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 /* find patient data by DOB */
835 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
837     $sqlBindArray = array();
838     $where = "DOB like ? ";
839     array_push($sqlBindArray, $DOB."%");
840     if (!empty($GLOBALS['pt_restrict_field'])) {
841         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
842             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
843                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
844                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
845             array_push($sqlBindArray, $_SESSION{"authUser"});
846         }
847     }
849     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
851     if ($limit != "all") {
852         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
853     }
855     $rez = sqlStatement($sql, $sqlBindArray);
856     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
857         $returnval[$iter]=$row;
858     }
860     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
861     return $returnval;
864 /* find patient data by SSN */
865 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
867     $sqlBindArray = array();
868     $where = "ss LIKE ?";
869     array_push($sqlBindArray, $ss."%");
870     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
871     if ($limit != "all") {
872         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
873     }
875     $rez = sqlStatement($sql, $sqlBindArray);
876     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
877         $returnval[$iter]=$row;
878     }
880     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
881     return $returnval;
884 //(CHEMED) Search by phone number
885 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
887     $phone = preg_replace("/[[:punct:]]/", "", $phone);
888     $sqlBindArray = array();
889     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
890     array_push($sqlBindArray, $phone);
891     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
892     if ($limit != "all") {
893         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
894     }
896     $rez = sqlStatement($sql, $sqlBindArray);
897     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
898         $returnval[$iter]=$row;
899     }
901     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
902     return $returnval;
905 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
907     $sql="select $given from patient_data order by $orderby";
909     if ($limit != "all") {
910         $sql .= " limit " . escape_limit($start) . ", " . escape_limit($limit);
911     }
913     $rez = sqlStatement($sql);
914     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
915         $returnval[$iter]=$row;
916     }
918     return $returnval;
921 //----------------------input functions
922 function newPatientData(
923     $db_id = "",
924     $title = "",
925     $fname = "",
926     $lname = "",
927     $mname = "",
928     $sex = "",
929     $DOB = "",
930     $street = "",
931     $postal_code = "",
932     $city = "",
933     $state = "",
934     $country_code = "",
935     $ss = "",
936     $occupation = "",
937     $phone_home = "",
938     $phone_biz = "",
939     $phone_contact = "",
940     $status = "",
941     $contact_relationship = "",
942     $referrer = "",
943     $referrerID = "",
944     $email = "",
945     $language = "",
946     $ethnoracial = "",
947     $interpretter = "",
948     $migrantseasonal = "",
949     $family_size = "",
950     $monthly_income = "",
951     $homeless = "",
952     $financial_review = "",
953     $pubpid = "",
954     $pid = "MAX(pid)+1",
955     $providerID = "",
956     $genericname1 = "",
957     $genericval1 = "",
958     $genericname2 = "",
959     $genericval2 = "",
960     $billing_note = "",
961     $phone_cell = "",
962     $hipaa_mail = "",
963     $hipaa_voice = "",
964     $squad = 0,
965     $pharmacy_id = 0,
966     $drivers_license = "",
967     $hipaa_notice = "",
968     $hipaa_message = "",
969     $regdate = ""
970 ) {
972     $fitness = 0;
973     $referral_source = '';
974     if ($pid) {
975         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
976         // Check for brain damage:
977         if ($db_id != $rez['id']) {
978             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
979               $rez['id'] . "' to '$db_id' for pid '$pid'";
980             die($errmsg);
981         }
983         $fitness = $rez['fitness'];
984         $referral_source = $rez['referral_source'];
985     }
987     // Get the default price level.
988     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
989       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
990     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
992     $query = ("replace into patient_data set
993         id='$db_id',
994         title='$title',
995         fname='$fname',
996         lname='$lname',
997         mname='$mname',
998         sex='$sex',
999         DOB='$DOB',
1000         street='$street',
1001         postal_code='$postal_code',
1002         city='$city',
1003         state='$state',
1004         country_code='$country_code',
1005         drivers_license='$drivers_license',
1006         ss='$ss',
1007         occupation='$occupation',
1008         phone_home='$phone_home',
1009         phone_biz='$phone_biz',
1010         phone_contact='$phone_contact',
1011         status='$status',
1012         contact_relationship='$contact_relationship',
1013         referrer='$referrer',
1014         referrerID='$referrerID',
1015         email='$email',
1016         language='$language',
1017         ethnoracial='$ethnoracial',
1018         interpretter='$interpretter',
1019         migrantseasonal='$migrantseasonal',
1020         family_size='$family_size',
1021         monthly_income='$monthly_income',
1022         homeless='$homeless',
1023         financial_review='$financial_review',
1024         pubpid='$pubpid',
1025         pid = $pid,
1026         providerID = '$providerID',
1027         genericname1 = '$genericname1',
1028         genericval1 = '$genericval1',
1029         genericname2 = '$genericname2',
1030         genericval2 = '$genericval2',
1031         billing_note= '$billing_note',
1032         phone_cell = '$phone_cell',
1033         pharmacy_id = '$pharmacy_id',
1034         hipaa_mail = '$hipaa_mail',
1035         hipaa_voice = '$hipaa_voice',
1036         hipaa_notice = '$hipaa_notice',
1037         hipaa_message = '$hipaa_message',
1038         squad = '$squad',
1039         fitness='$fitness',
1040         referral_source='$referral_source',
1041         regdate='$regdate',
1042         pricelevel='$pricelevel',
1043         date=NOW()");
1045     $id = sqlInsert($query);
1047     if (!$db_id) {
1048       // find the last inserted id for new patient case
1049         $db_id = getSqlLastID();
1050     }
1052     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1054     return $foo['pid'];
1057 // Supported input date formats are:
1058 //   mm/dd/yyyy
1059 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1060 //   yyyy/mm/dd
1061 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1063 function fixDate($date, $default = "0000-00-00")
1065     $fixed_date = $default;
1066     $date = trim($date);
1067     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1068         $dmy = preg_split("'[/.-]'", $date);
1069         if ($dmy[0] > 99) {
1070             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1071         } else {
1072             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1073                 if ($dmy[2] < 1000) {
1074                     $dmy[2] += 1900;
1075                 }
1077                 if ($dmy[2] < 1910) {
1078                     $dmy[2] += 100;
1079                 }
1080             }
1082             // phone_country_code indicates format of ambiguous input dates.
1083             if ($GLOBALS['phone_country_code'] == 1) {
1084                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1085             } else {
1086                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1087             }
1088         }
1089     }
1091     return $fixed_date;
1094 function pdValueOrNull($key, $value)
1096     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1097     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1098     (empty($value) || $value == '0000-00-00')) {
1099         return "NULL";
1100     } else {
1101         return "'" . add_escape_custom($value) . "'";
1102     }
1105 // Create or update patient data from an array.
1107 function updatePatientData($pid, $new, $create = false)
1109   /*******************************************************************
1110     $real = getPatientData($pid);
1111     foreach ($new as $key => $value)
1112         $real[$key] = $value;
1113     $real['date'] = "'+NOW()+'";
1114     $real['id'] = "";
1115     $sql = "insert into patient_data set ";
1116     foreach ($real as $key => $value)
1117         $sql .= $key." = '$value', ";
1118     $sql = substr($sql, 0, -2);
1119     return sqlInsert($sql);
1120   *******************************************************************/
1122   // The above was broken, though seems intent to insert a new patient_data
1123   // row for each update.  A good idea, but nothing is doing that yet so
1124   // the code below does not yet attempt it.
1126     if ($create) {
1127         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1128         foreach ($new as $key => $value) {
1129             if ($key == 'id') {
1130                 continue;
1131             }
1133             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1134         }
1136         $db_id = sqlInsert($sql);
1137     } else {
1138         $db_id = $new['id'];
1139         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1140         // Check for brain damage:
1141         if ($pid != $rez['pid']) {
1142             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1143             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1144             die($errmsg);
1145         }
1147         $sql = "UPDATE patient_data SET date = NOW()";
1148         foreach ($new as $key => $value) {
1149             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1150         }
1152         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1153         sqlStatement($sql);
1154     }
1156     return $db_id;
1159 function newEmployerData(
1160     $pid,
1161     $name = "",
1162     $street = "",
1163     $postal_code = "",
1164     $city = "",
1165     $state = "",
1166     $country = ""
1167 ) {
1169     return sqlInsert("insert into employer_data set
1170         name='$name',
1171         street='$street',
1172         postal_code='$postal_code',
1173         city='$city',
1174         state='$state',
1175         country='$country',
1176         pid='$pid',
1177         date=NOW()
1178         ");
1181 // Create or update employer data from an array.
1183 function updateEmployerData($pid, $new, $create = false)
1185     $colnames = array('name','street','city','state','postal_code','country');
1187     if ($create) {
1188         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1189         foreach ($colnames as $key) {
1190             $value = isset($new[$key]) ? $new[$key] : '';
1191             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1192         }
1194         return sqlInsert("INSERT INTO employer_data SET $set");
1195     } else {
1196         $set = '';
1197         $old = getEmployerData($pid);
1198         $modified = false;
1199         foreach ($colnames as $key) {
1200             $value = empty($old[$key]) ? '' : $old[$key];
1201             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1202                 $value = $new[$key];
1203                 $modified = true;
1204             }
1206             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1207         }
1209         if ($modified) {
1210             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1211             return sqlInsert("INSERT INTO employer_data SET $set");
1212         }
1214         return $old['id'];
1215     }
1218 // This updates or adds the given insurance data info, while retaining any
1219 // previously added insurance_data rows that should be preserved.
1220 // This does not directly support the maintenance of non-current insurance.
1222 function newInsuranceData(
1223     $pid,
1224     $type = "",
1225     $provider = "",
1226     $policy_number = "",
1227     $group_number = "",
1228     $plan_name = "",
1229     $subscriber_lname = "",
1230     $subscriber_mname = "",
1231     $subscriber_fname = "",
1232     $subscriber_relationship = "",
1233     $subscriber_ss = "",
1234     $subscriber_DOB = "",
1235     $subscriber_street = "",
1236     $subscriber_postal_code = "",
1237     $subscriber_city = "",
1238     $subscriber_state = "",
1239     $subscriber_country = "",
1240     $subscriber_phone = "",
1241     $subscriber_employer = "",
1242     $subscriber_employer_street = "",
1243     $subscriber_employer_city = "",
1244     $subscriber_employer_postal_code = "",
1245     $subscriber_employer_state = "",
1246     $subscriber_employer_country = "",
1247     $copay = "",
1248     $subscriber_sex = "",
1249     $effective_date = "0000-00-00",
1250     $accept_assignment = "TRUE",
1251     $policy_type = ""
1252 ) {
1254     if (strlen($type) <= 0) {
1255         return false;
1256     }
1258     // If empty dates were passed, then zero them.
1259     if (empty($effective_date)) {
1260         $effective_date = '0000-00-00';
1261     }
1262     if (empty($subscriber_DOB)) {
1263         $subscriber_DOB = '0000-00-00';
1264     }
1266     $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1267     "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1268     $idrow = sqlFetchArray($idres);
1270   // Replace the most recent entry in any of the following cases:
1271   // * Its effective date is >= this effective date.
1272   // * It is the first entry and it has no (insurance) provider.
1273   // * There is no encounter that is earlier than the new effective date but
1274   //   on or after the old effective date.
1275   // Otherwise insert a new entry.
1277     $replace = false;
1278     if ($idrow) {
1279         if (strcmp($idrow['date'], $effective_date) > 0) {
1280             $replace = true;
1281         } else {
1282             if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1283                 $replace = true;
1284             } else {
1285                 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1286                 "WHERE pid = ? AND date < ? AND " .
1287                 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1288                 if ($ferow['count'] == 0) {
1289                     $replace = true;
1290                 }
1291             }
1292         }
1293     }
1295     if ($replace) {
1296         // TBD: This is a bit dangerous in that a typo in entering the effective
1297         // date can wipe out previous insurance history.  So we want some data
1298         // entry validation somewhere.
1299         sqlStatement("DELETE FROM insurance_data WHERE " .
1300         "pid = ? AND type = ? AND date >= ? AND " .
1301         "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1303         $data = array();
1304         $data['type'] = $type;
1305         $data['provider'] = $provider;
1306         $data['policy_number'] = $policy_number;
1307         $data['group_number'] = $group_number;
1308         $data['plan_name'] = $plan_name;
1309         $data['subscriber_lname'] = $subscriber_lname;
1310         $data['subscriber_mname'] = $subscriber_mname;
1311         $data['subscriber_fname'] = $subscriber_fname;
1312         $data['subscriber_relationship'] = $subscriber_relationship;
1313         $data['subscriber_ss'] = $subscriber_ss;
1314         $data['subscriber_DOB'] = $subscriber_DOB;
1315         $data['subscriber_street'] = $subscriber_street;
1316         $data['subscriber_postal_code'] = $subscriber_postal_code;
1317         $data['subscriber_city'] = $subscriber_city;
1318         $data['subscriber_state'] = $subscriber_state;
1319         $data['subscriber_country'] = $subscriber_country;
1320         $data['subscriber_phone'] = $subscriber_phone;
1321         $data['subscriber_employer'] = $subscriber_employer;
1322         $data['subscriber_employer_city'] = $subscriber_employer_city;
1323         $data['subscriber_employer_street'] = $subscriber_employer_street;
1324         $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1325         $data['subscriber_employer_state'] = $subscriber_employer_state;
1326         $data['subscriber_employer_country'] = $subscriber_employer_country;
1327         $data['copay'] = $copay;
1328         $data['subscriber_sex'] = $subscriber_sex;
1329         $data['pid'] = $pid;
1330         $data['date'] = $effective_date;
1331         $data['accept_assignment'] = $accept_assignment;
1332         $data['policy_type'] = $policy_type;
1333         updateInsuranceData($idrow['id'], $data);
1334         return $idrow['id'];
1335     } else {
1336         return sqlInsert("INSERT INTO insurance_data SET
1337       type = '" . add_escape_custom($type) . "',
1338       provider = '" . add_escape_custom($provider) . "',
1339       policy_number = '" . add_escape_custom($policy_number) . "',
1340       group_number = '" . add_escape_custom($group_number) . "',
1341       plan_name = '" . add_escape_custom($plan_name) . "',
1342       subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1343       subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1344       subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1345       subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1346       subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1347       subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1348       subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1349       subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1350       subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1351       subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1352       subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1353       subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1354       subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1355       subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1356       subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1357       subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1358       subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1359       subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1360       copay = '" . add_escape_custom($copay) . "',
1361       subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1362       pid = '" . add_escape_custom($pid) . "',
1363       date = '" . add_escape_custom($effective_date) . "',
1364       accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1365       policy_type = '" . add_escape_custom($policy_type) . "'
1366     ");
1367     }
1370 // This is used internally only.
1371 function updateInsuranceData($id, $new)
1373     $fields = sqlListFields("insurance_data");
1374     $use = array();
1376     foreach ($new as $key => $value) {
1377         if (in_array($key, $fields)) {
1378             $use[$key] = $value;
1379         }
1380     }
1382     $sql = "UPDATE insurance_data SET ";
1383     foreach ($use as $key => $value) {
1384         $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1385     }
1387     $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1389     sqlStatement($sql);
1392 function newHistoryData($pid, $new = false)
1394     $arraySqlBind = array();
1395     $sql = "insert into history_data set pid = ?, date = NOW()";
1396     array_push($arraySqlBind, $pid);
1397     if ($new) {
1398         foreach ($new as $key => $value) {
1399             array_push($arraySqlBind, $value);
1400             $sql .= ", `$key` = ?";
1401         }
1402     }
1404     return sqlInsert($sql, $arraySqlBind);
1407 function updateHistoryData($pid, $new)
1409     $real = getHistoryData($pid);
1410     foreach ($new as $key => $value) {
1411         $real[$key] = $value;
1412     }
1414     $real['id'] = "";
1415     // need to unset date, so can reset it below
1416     unset($real['date']);
1418     $arraySqlBind = array();
1419     $sql = "insert into history_data set `date` = NOW(), ";
1420     foreach ($real as $key => $value) {
1421         array_push($arraySqlBind, $value);
1422         $sql .= "`$key` = ?, ";
1423     }
1425     $sql = substr($sql, 0, -2);
1427     return sqlInsert($sql, $arraySqlBind);
1430 // Returns Age
1431 //   in months if < 2 years old
1432 //   in years  if > 2 years old
1433 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1434 // (optional) nowYMD is a date in YYYYMMDD format
1435 function getPatientAge($dobYMD, $nowYMD = null)
1437     // strip any dashes from the DOB
1438     $dobYMD = preg_replace("/-/", "", $dobYMD);
1439     $dobDay = substr($dobYMD, 6, 2);
1440     $dobMonth = substr($dobYMD, 4, 2);
1441     $dobYear = substr($dobYMD, 0, 4);
1443     // set the 'now' date values
1444     if ($nowYMD == null) {
1445         $nowDay = date("d");
1446         $nowMonth = date("m");
1447         $nowYear = date("Y");
1448     } else {
1449         $nowDay = substr($nowYMD, 6, 2);
1450         $nowMonth = substr($nowYMD, 4, 2);
1451         $nowYear = substr($nowYMD, 0, 4);
1452     }
1454     $dayDiff = $nowDay - $dobDay;
1455     $monthDiff = $nowMonth - $dobMonth;
1456     $yearDiff = $nowYear - $dobYear;
1458     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1460     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1461     if ($dayDiff<0) {
1462         $ageInMonths-=1;
1463     }
1465     if ($ageInMonths > 24) {
1466         $age = $yearDiff;
1467         if (($monthDiff == 0) && ($dayDiff < 0)) {
1468             $age -= 1;
1469         } else if ($monthDiff < 0) {
1470             $age -= 1;
1471         }
1472     } else {
1473         $age = "$ageInMonths " . xl('month');
1474     }
1476     return $age;
1480  * Wrapper to make sure the clinical rules dates formats corresponds to the
1481  * format expected by getPatientAgeYMD
1483  * @param  string  $dob     date of birth
1484  * @param  string  $target  date to calculate age on
1485  * @return array containing
1486  *      age - decimal age in years
1487  *      age_in_months - decimal age in months
1488  *      ageinYMD - formatted string #y #m #d */
1489 function parseAgeInfo($dob, $target)
1491     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1492     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1493     ;
1494     // Prepare target (Y-M-D H:M:S)
1495     $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1497     return getPatientAgeYMD($dateDOB, $dateTarget);
1502  * @param type $dob
1503  * @param type $date
1504  * @return array containing
1505  *      age - decimal age in years
1506  *      age_in_months - decimal age in months
1507  *      ageinYMD - formatted string #y #m #d
1508  */
1509 function getPatientAgeYMD($dob, $date = null)
1512     if ($date == null) {
1513         $daynow = date("d");
1514         $monthnow = date("m");
1515         $yearnow = date("Y");
1516         $datenow=$yearnow.$monthnow.$daynow;
1517     } else {
1518         $datenow=preg_replace("/-/", "", $date);
1519         $yearnow=substr($datenow, 0, 4);
1520         $monthnow=substr($datenow, 4, 2);
1521         $daynow=substr($datenow, 6, 2);
1522         $datenow=$yearnow.$monthnow.$daynow;
1523     }
1525     $dob=preg_replace("/-/", "", $dob);
1526     $dobyear=substr($dob, 0, 4);
1527     $dobmonth=substr($dob, 4, 2);
1528     $dobday=substr($dob, 6, 2);
1529     $dob=$dobyear.$dobmonth.$dobday;
1531     //to compensate for 30, 31, 28, 29 days/month
1532     $mo=$monthnow; //to avoid confusion with later calculation
1534     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1
1535         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1536     } // look at April, June, September, November for calculation.  These months only have 30 days.
1537     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1538         $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1539         if (is_int($check_leap_Y)) {
1540             $nd=29;
1541         } //If it true then this is the leap year
1542         else {
1543             $nd=28;
1544         } //otherwise, it is not a leap year.
1545     } else {
1546         $nd=31;
1547     } // other months have 31 days
1549     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1550     if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1551         $age_year = $yearnow - $dobyear - 1;
1552         if ($daynow < $dobday) {
1553             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1554             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1555         } else {
1556             $months_since_birthday=12 - $dobmonth + $monthnow;
1557             $days_since_dobday=$daynow - $dobday;
1558         }
1559     } else // if patient has had birthday this calandar year
1560     {
1561         $age_year = $yearnow - $dobyear;
1562         if ($daynow < $dobday) {
1563             $months_since_birthday=$monthnow - $dobmonth -1;
1564             $days_since_dobday=$nd - $dobday + $daynow;
1565         } else {
1566             $months_since_birthday=$monthnow - $dobmonth;
1567             $days_since_dobday=$daynow - $dobday;
1568         }
1569     }
1571     $day_as_month_decimal = $days_since_dobday / 30;
1572     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1573     $month_as_year_decimal = $months_since_birthday_float / 12;
1574     $age_float = $age_year + $month_as_year_decimal;
1576     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1577     $age_in_months = round($age_in_months, 2);  //round the months to xx.xx 2 floating points
1578     $age = round($age_float, 2);
1580     // round the years to 2 floating points
1581     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1582     return compact('age', 'age_in_months', 'ageinYMD');
1585 // Returns Age in days
1586 //   in months if < 2 years old
1587 //   in years  if > 2 years old
1588 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1589 // (optional) nowYMD is a date in YYYYMMDD format
1590 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1592     $age = -1;
1594     // strip any dashes from the DOB
1595     $dobYMD = preg_replace("/-/", "", $dobYMD);
1596     $dobDay = substr($dobYMD, 6, 2);
1597     $dobMonth = substr($dobYMD, 4, 2);
1598     $dobYear = substr($dobYMD, 0, 4);
1600     // set the 'now' date values
1601     if ($nowYMD == null) {
1602         $nowDay = date("d");
1603         $nowMonth = date("m");
1604         $nowYear = date("Y");
1605     } else {
1606         $nowDay = substr($nowYMD, 6, 2);
1607         $nowMonth = substr($nowYMD, 4, 2);
1608         $nowYear = substr($nowYMD, 0, 4);
1609     }
1611     // do the date math
1612     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1613     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1614     $timediff = $nowtime - $dobtime;
1615     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1617     return $age;
1620  * Returns a string to be used to display a patient's age
1622  * @param type $dobYMD
1623  * @param type $asOfYMD
1624  * @return string suitable for displaying patient's age based on preferences
1625  */
1626 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1628     if ($GLOBALS['age_display_format']=='1') {
1629         $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1630         if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1631             return $ageYMD['ageinYMD'];
1632         } else {
1633             return getPatientAge($dobYMD, $asOfYMD);
1634         }
1635     } else {
1636         return getPatientAge($dobYMD, $asOfYMD);
1637     }
1639 function dateToDB($date)
1641     $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1642     return $date;
1646 // ----------------------------------------------------------------------------
1648  * DROPDOWN FOR COUNTRIES
1650  * build a dropdown with all countries from geo_country_reference
1652  * @param int $selected - id for selected record
1653  * @param string $name - the name/id for select form
1654  * @return void - just echo the html encoded string
1655  */
1656 function dropdown_countries($selected = 0, $name = 'country_code')
1658     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1660     $string = "<select name='$name' id='$name'>";
1661     while ($row = sqlFetchArray($r)) {
1662         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1663         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1664     }
1666     $string .= '</select>';
1667     echo $string;
1671 // ----------------------------------------------------------------------------
1673  * DROPDOWN FOR YES/NO
1675  * build a dropdown with two options (yes - 1, no - 0)
1677  * @param int $selected - id for selected record
1678  * @param string $name - the name/id for select form
1679  * @return void - just echo the html encoded string
1680  */
1681 function dropdown_yesno($selected = 0, $name = 'yesno')
1683     $string = "<select name='$name' id='$name'>";
1685     $selected = (int)$selected;
1686     if ($selected == 0) {
1687         $sel1 = 'selected="selected"';
1688         $sel2 = '';
1689     } else {
1690         $sel2 = 'selected="selected"';
1691         $sel1 = '';
1692     }
1694         $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1695         $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1696         $string .= '</select>';
1698         echo $string;
1701 // ----------------------------------------------------------------------------
1703  * DROPDOWN FOR MALE/FEMALE options
1705  * build a dropdown with three options (unselected/male/female)
1707  * @param int $selected - id for selected record
1708  * @param string $name - the name/id for select form
1709  * @return void - just echo the html encoded string
1710  */
1711 function dropdown_sex($selected = 0, $name = 'sex')
1713     $string = "<select name='$name' id='$name'>";
1715     if ($selected == 1) {
1716         $sel1 = 'selected="selected"';
1717         $sel2 = '';
1718         $sel0 = '';
1719     } else if ($selected == 2) {
1720         $sel2 = 'selected="selected"';
1721         $sel1 = '';
1722         $sel0 = '';
1723     } else {
1724             $sel0 = 'selected="selected"';
1725             $sel1 = '';
1726             $sel2 = '';
1727     }
1729         $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1730         $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1731         $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1732         $string .= '</select>';
1734         echo $string;
1737 // ----------------------------------------------------------------------------
1739  * DROPDOWN FOR MARITAL STATUS
1741  * build a dropdown with marital status
1743  * @param int $selected - id for selected record
1744  * @param string $name - the name/id for select form
1745  * @return void - just echo the html encoded string
1746  */
1747 function dropdown_marital($selected = 0, $name = 'status')
1749     $string = "<select name='$name' id='$name'>";
1751     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1753     foreach ($statii as $st) {
1754         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1755         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1756     }
1758     $string .= '</select>';
1760     echo $string;
1763 // ----------------------------------------------------------------------------
1765  * DROPDOWN FOR PROVIDERS
1767  * build a dropdown with all providers
1769  * @param int $selected - id for selected record
1770  * @param string $name - the name/id for select form
1771  * @return void - just echo the html encoded string
1772  */
1773 function dropdown_providers($selected = 0, $name = 'status')
1775     $provideri = getProviderInfo();
1777     $string = "<select name='$name' id='$name'>";
1778     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1779     foreach ($provideri as $s) {
1780         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1781         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1782     }
1784     $string .= '</select>';
1786     echo $string;
1789 // ----------------------------------------------------------------------------
1791  * DROPDOWN FOR INSURANCE COMPANIES
1793  * build a dropdown with all insurers
1795  * @param int $selected - id for selected record
1796  * @param string $name - the name/id for select form
1797  * @return void - just echo the html encoded string
1798  */
1799 function dropdown_insurance($selected = 0, $name = 'iprovider')
1801     $insurancei = getInsuranceProviders();
1803     $string = "<select name='$name' id='$name'>";
1804     $string .= '<option value="0">Onbekend</option>';
1805     foreach ($insurancei as $iid => $iname) {
1806         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1807         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1808     }
1810     $string .= '</select>';
1812     echo $string;
1816 // ----------------------------------------------------------------------------
1818  * COUNTRY CODE
1820  * return the name or the country code, function of arguments
1822  * @param int $country_code
1823  * @param string $country_name
1824  * @return string | int - name or code
1825  */
1826 function country_code($country_code = 0, $country_name = '')
1828     $strint = '';
1829     if ($country_code) {
1830         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1831     } else {
1832         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1833     }
1835     $db = $GLOBALS['adodb']['db'];
1836     $result = $db->Execute($sql);
1837     if ($result && !$result->EOF) {
1838         $strint = $result->fields['res'];
1839     }
1841     return $strint;
1844 function DBToDate($date)
1846     $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1847     return $date;
1851  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1852  * for the given patient on the given date.
1854  * @param int     The PID of the patient.
1855  * @param string  Date in yyyy-mm-dd format.
1856  * @return array  Array of 0-3 insurance_data rows.
1857  */
1858 function getEffectiveInsurances($patient_id, $encdate)
1860     $insarr = array();
1861     foreach (array('primary','secondary','tertiary') as $instype) {
1862         $tmp = sqlQuery(
1863             "SELECT * FROM insurance_data " .
1864             "WHERE pid = ? AND type = ? " .
1865             "AND date <= ? ORDER BY date DESC LIMIT 1",
1866             array($patient_id, $instype, $encdate)
1867         );
1868         if (empty($tmp['provider'])) {
1869             break;
1870         }
1872         $insarr[] = $tmp;
1873     }
1875     return $insarr;
1879  * Get the patient's balance due. Normally this excludes amounts that are out
1880  * to insurance.  If you want to include what insurance owes, set the second
1881  * parameter to true.
1883  * @param int     The PID of the patient.
1884  * @param boolean Indicates if amounts owed by insurance are to be included.
1885  * @param int     Optional encounter id. If value is passed, will fetch only bills from specified encounter.
1886  * @return number The balance.
1887  */
1888 function get_patient_balance($pid, $with_insurance = false, $eid = false)
1890     $balance = 0;
1891     $bindarray = array($pid);
1892     $sqlstatement = "SELECT date, encounter, last_level_billed, " .
1893       "last_level_closed, stmt_count " .
1894       "FROM form_encounter WHERE pid = ?";
1895     if ($eid) {
1896         $sqlstatement .= " AND encounter = ?";
1897         array_push($bindarray, $eid);
1898     }
1899     $feres = sqlStatement($sqlstatement, $bindarray);
1900     while ($ferow = sqlFetchArray($feres)) {
1901         $encounter = $ferow['encounter'];
1902         $dos = substr($ferow['date'], 0, 10);
1903         $insarr = getEffectiveInsurances($pid, $dos);
1904         $inscount = count($insarr);
1905         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1906             // It's out to insurance so only the co-pay might be due.
1907             $brow = sqlQuery(
1908                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1909                 "pid = ? AND encounter = ? AND " .
1910                 "code_type = 'copay' AND activity = 1",
1911                 array($pid, $encounter)
1912             );
1913             $drow = sqlQuery(
1914                 "SELECT SUM(pay_amount) AS payments " .
1915                 "FROM ar_activity WHERE " .
1916                 "pid = ? AND encounter = ? AND payer_type = 0",
1917                 array($pid, $encounter)
1918             );
1919             $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1920             if ($ptbal > 0) {
1921                 $balance += $ptbal;
1922             }
1923         } else {
1924             // Including insurance or not out to insurance, everything is due.
1925             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1926             "pid = ? AND encounter = ? AND " .
1927             "activity = 1", array($pid, $encounter));
1928             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1929               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1930               "pid = ? AND encounter = ?", array($pid, $encounter));
1931             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1932               "pid = ? AND encounter = ?", array($pid, $encounter));
1933             $balance += $brow['amount'] + $srow['amount']
1934               - $drow['payments'] - $drow['adjustments'];
1935         }
1936     }
1938     return sprintf('%01.2f', $balance);
1941 // Function to check if patient is deceased.
1942 //  Param:
1943 //    $pid  - patient id
1944 //    $date - date checking if deceased (will default to current date if blank)
1945 //  Return:
1946 //    If deceased, then will return the number of
1947 //      days that patient has been deceased.
1948 //    If not deceased, then will return false.
1949 function is_patient_deceased($pid, $date = '')
1952   // Set date to current if not set
1953     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1955   // Query for deceased status (gets days deceased if patient is deceased)
1956     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1957                       "FROM `patient_data` " .
1958                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1960     if (empty($results)) {
1961         // Patient is alive, so return false
1962         return false;
1963     } else {
1964         // Patient is dead, so return the number of days patient has been deceased.
1965         //  Don't let it be zero days or else will confuse calls to this function.
1966         if ($results['days_deceased'] === 0) {
1967             $results['days_deceased'] = 1;
1968         }
1970         return $results['days_deceased'];
1971     }