Multiple improvements from IPPF related to layouts. (#1081)
[openemr.git] / library / patient.inc
blob420bbd9336b2b0ab8c4cea5c848ca39cd80bb81e
1 <?php
2 /**
3  * patient.inc includes functions for manipulating patient information.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  */
11 use OpenEMR\Services\FacilityService;
13 $facilityService = new FacilityService();
15 // These are for sports team use:
16 $PLAYER_FITNESSES = array(
17   xl('Full Play'),
18   xl('Full Training'),
19   xl('Restricted Training'),
20   xl('Injured Out'),
21   xl('Rehabilitation'),
22   xl('Illness'),
23   xl('International Duty')
25 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
27 // Hard-coding this array because its values and meanings are fixed by the 837p
28 // standard and we don't want people messing with them.
29 $policy_types = array(
30   ''   => xl('N/A'),
31   '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
32   '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
33   '14' => xl('No-fault Insurance including Auto is Primary'),
34   '15' => xl('Worker`s Compensation'),
35   '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
36   '41' => xl('Black Lung'),
37   '42' => xl('Veteran`s Administration'),
38   '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
39   '47' => xl('Other Liability Insurance is Primary'),
42 /**
43  * Get a patient's demographic data.
44  *
45  * @param int    $pid   The PID of the patient
46  * @param string $given an optional subsection of the patient's demographic
47  *                      data to retrieve.
48  * @return array The requested subsection of a patient's demographic data.
49  *               If no subsection was given, returns everything, with the
50  *               date of birth as the last field.
51  */
52 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
54     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
55     return sqlQuery($sql, array($pid));
58 function getLanguages()
60     $returnval = array('','english');
61     $sql = "select distinct lower(language) as language from patient_data";
62     $rez = sqlStatement($sql);
63     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
64         if (($row["language"] != "english") && ($row["language"] != "")) {
65             array_push($returnval, $row["language"]);
66         }
67     }
69     return $returnval;
72 function getInsuranceProvider($ins_id)
75     $sql = "select name from insurance_companies where id=?";
76     $row = sqlQuery($sql, array($ins_id));
77     return $row['name'];
80 function getInsuranceProviders()
82     $returnval = array();
84     if (true) {
85         $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
86         $rez = sqlStatement($sql);
87         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
88             $returnval[$row['id']] = $row['name'];
89         }
90     } // Please leave this here. I have a user who wants to see zip codes and PO
91     // box numbers listed along with the insurance company names, as many companies
92     // have different billing addresses for different plans.  -- Rod Roark
93     //
94     else {
95         $sql = "select insurance_companies.name, insurance_companies.id, " .
96           "addresses.zip, addresses.line1 " .
97           "from insurance_companies, addresses " .
98           "where addresses.foreign_id = insurance_companies.id " .
99           "order by insurance_companies.name, addresses.zip";
101         $rez = sqlStatement($sql);
103         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
104             preg_match("/\d+/", $row['line1'], $matches);
105             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
106               "," . $matches[0] . ")";
107         }
108     }
110     return $returnval;
113 function getInsuranceProvidersExtra()
115     $returnval = array();
116     // add a global and if for where to allow inactive inscompanies
118     $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
119             addresses.state, addresses.zip
120             FROM insurance_companies, addresses
121             WHERE addresses.foreign_id = insurance_companies.id
122             AND insurance_companies.inactive != 1
123             ORDER BY insurance_companies.name, addresses.zip";
125     $rez = sqlStatement($sql);
127     for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
128         switch ($GLOBALS['insurance_information']) {
129             case $GLOBALS['insurance_information'] = '0':
130                 $returnval[$row['id']] = $row['name'];
131                 break;
132             case $GLOBALS['insurance_information'] = '1':
133                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
134                 break;
135             case $GLOBALS['insurance_information'] = '2':
136                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
137                 break;
138             case $GLOBALS['insurance_information'] = '3':
139                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
140                 break;
141             case $GLOBALS['insurance_information'] = '4':
142                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
143                     ", " . $row['zip'] . ")";
144                 break;
145             case $GLOBALS['insurance_information'] = '5':
146                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
147                     ", " . $row['state'] . ", " . $row['zip'] . ")";
148                 break;
149             case $GLOBALS['insurance_information'] = '6':
150                 preg_match("/\d+/", $row['line1'], $matches);
151                 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
152                     "," . $matches[0] . ")";
153                 break;
154         }
155     }
157     return $returnval;
160 function getProviders()
162     $returnval = array("");
163     $sql = "select fname, lname, suffix from users where authorized = 1 and " .
164         "active = 1 and username != ''";
165     $rez = sqlStatement($sql);
166     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
167         if (($row["fname"] != "") && ($row["lname"] != "")) {
168             if ($row["suffix"] != "") {
169                 $row["lname"] .= ", ".$row["suffix"];
170             }
172             array_push($returnval, $row["fname"] . " " . $row["lname"]);
173         }
174     }
176     return $returnval;
179 // ----------------------------------------------------------------------------
180 // Get one facility row.  If the ID is not specified, then get either the
181 // "main" (billing) facility, or the default facility of the currently
182 // logged-in user.  This was created to support genFacilityTitle() but
183 // may find additional uses.
185 function getFacility($facid = 0)
187     global $facilityService;
189     $facility = null;
191     if ($facid > 0) {
192         $facility = $facilityService->getById($facid);
193     } else if ($facid == 0) {
194         $facility = $facilityService->getPrimaryBillingLocation();
195     } else {
196         $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
197     }
199     return $facility;
202 // Generate a report title including report name and facility name, address
203 // and phone.
205 function genFacilityTitle($repname = '', $facid = 0)
207     $s = '';
208     $s .= "<table class='ftitletable'>\n";
209     $s .= " <tr>\n";
210     if (empty($logo)) {
211         $s .= "  <td class='ftitlecell1'>$repname</td>\n";
212     } else {
213         $s .= "  <td class='ftitlecell1'>$logo</td>\n";
214         $s .= "  <td class='ftitlecellm'>$repname</td>\n";
215     }
216     $s .= "  <td class='ftitlecell2'>\n";
217     $r = getFacility($facid);
218     if (!empty($r)) {
219         $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
220         if ($r['street']) {
221             $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
222         }
224         if ($r['city'] || $r['state'] || $r['postal_code']) {
225             $s .= "<br />";
226             if ($r['city']) {
227                 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
228             }
230             if ($r['state']) {
231                 if ($r['city']) {
232                     $s .= ", \n";
233                 }
235                 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
236             }
238             if ($r['postal_code']) {
239                 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
240             }
242             $s .= "\n";
243         }
245         if ($r['country_code']) {
246             $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
247         }
249         if (preg_match('/[1-9]/', $r['phone'])) {
250             $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
251         }
252     }
254     $s .= "  </td>\n";
255     $s .= " </tr>\n";
256     $s .= "</table>\n";
257     return $s;
261 GET FACILITIES
263 returns all facilities or just the id for the first one
264 (FACILITY FILTERING (lemonsoftware))
266 @param string - if 'first' return first facility ordered by id
267 @return array | int for 'first' case
269 function getFacilities($first = '')
271     global $facilityService;
273     $fres = $facilityService->getAll();
275     if ($first == 'first') {
276         return $fres[0]['id'];
277     } else {
278         return $fres;
279     }
283 GET SERVICE FACILITIES
285 returns all service_location facilities or just the id for the first one
286 (FACILITY FILTERING (CHEMED))
288 @param string - if 'first' return first facility ordered by id
289 @return array | int for 'first' case
291 function getServiceFacilities($first = '')
293     global $facilityService;
295     $fres = $facilityService->getAllServiceLocations();
297     if ($first == 'first') {
298         return $fres[0]['id'];
299     } else {
300         return $fres;
301     }
304 //(CHEMED) facility filter
305 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
307     $param1 = "";
308     if ($providers_only === 'any') {
309         $param1 = " AND authorized = 1 AND active = 1 ";
310     } else if ($providers_only) {
311         $param1 = " AND authorized = 1 AND calendar = 1 ";
312     }
314     //--------------------------------
315     //(CHEMED) facility filter
316     $param2 = "";
317     if ($facility) {
318         if ($GLOBALS['restrict_user_facility']) {
319             $param2 = " AND (facility_id = $facility
320           OR  $facility IN
321                 (select facility_id
322                 from users_facility
323                 where tablename = 'users'
324                 and table_id = id)
325                 )
326           ";
327         } else {
328             $param2 = " AND facility_id = $facility ";
329         }
330     }
332     //--------------------------------
334     $command = "=";
335     if ($providerID == "%") {
336         $command = "like";
337     }
339     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
340         "from users where username != '' and active = 1 and id $command '" .
341         add_escape_custom($providerID) . "' " . $param1 . $param2;
342     // sort by last name -- JRM June 2008
343     $query .= " ORDER BY lname, fname ";
344     $rez = sqlStatement($query);
345     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
346         $returnval[$iter]=$row;
347     }
349     //if only one result returned take the key/value pairs in array [0] and merge them down into
350     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
352     if ($iter==1) {
353         $akeys = array_keys($returnval[0]);
354         foreach ($akeys as $key) {
355             $returnval[0][$key] = $returnval[0][$key];
356         }
357     }
359     return $returnval;
362 //same as above but does not reduce if only 1 row returned
363 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
365     $param1 = "";
366     if ($providers_only) {
367         $param1 = "AND authorized=1";
368     }
370     $command = "=";
371     if ($providerID == "%") {
372         $command = "like";
373     }
375     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
376         "from users where active = 1 and username != '' and id $command '" .
377         add_escape_custom($providerID) . "' " . $param1;
379     $rez = sqlStatement($query);
380     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
381         $returnval[$iter]=$row;
382     }
384     return $returnval;
387 function getProviderName($providerID)
389     $pi = getProviderInfo($providerID, 'any');
390     if (strlen($pi[0]["lname"]) > 0) {
391         if (strlen($pi[0]["suffix"]) > 0) {
392             $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
393         }
395         return $pi[0]['fname'] . " " . $pi[0]['lname'];
396     }
398     return "";
401 function getProviderId($providerName)
403     $query = "select id from users where username = ?";
404     $rez = sqlStatement($query, array($providerName));
405     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
406         $returnval[$iter]=$row;
407     }
409     return $returnval;
412 function getEthnoRacials()
414     $returnval = array("");
415     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
416     $rez = sqlStatement($sql);
417     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
418         if (($row["ethnoracial"] != "")) {
419             array_push($returnval, $row["ethnoracial"]);
420         }
421     }
423     return $returnval;
426 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
429     if ($dateStart && $dateEnd) {
430         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
431     } else if ($dateStart && !$dateEnd) {
432         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
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,$dateEnd));
435     } else {
436         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
437     }
439     if ($given == 'tobacco') {
440         $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));
441     }
443     return $res;
446 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
447 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
449     $sql = "select $given from insurance_data as insd " .
450     "left join insurance_companies as ic on ic.id = insd.provider " .
451     "where pid = ? and type = ? order by date DESC limit 1";
452     return sqlQuery($sql, array($pid, $type));
455 function getInsuranceDataByDate(
456     $pid,
457     $date,
458     $type,
459     $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
460 ) {
461  // this must take the date in the following manner: YYYY-MM-DD
462   // this function recalls the insurance value that was most recently enterred from the
463   // given date. it will call up most recent records up to and on the date given,
464   // but not records enterred after the given date
465     $sql = "select $given from insurance_data as insd " .
466     "left join insurance_companies as ic on ic.id = provider " .
467     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
468     "type=? order by date DESC limit 1";
469     return sqlQuery($sql, array($pid,$date,$type));
472 function getEmployerData($pid, $given = "*")
474     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
475     return sqlQuery($sql, array($pid));
478 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
480   // When the limit is exceeded, find out what the unlimited count would be.
481     $GLOBALS['PATIENT_INC_COUNT'] = $count;
482   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
483     if ($limit != "all") {
484         $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
485         $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
486     }
490  * Allow the last name to be followed by a comma and some part of a first name(can
491  *   also place middle name after the first name with a space separating them)
492  * Allows comma alone followed by some part of a first name(can also place middle name
493  *   after the first name with a space separating them).
494  * Allows comma alone preceded by some part of a last name.
495  * If no comma or space, then will search both last name and first name.
496  * If the first letter of either name is capital, searches for name starting
497  *   with given substring (the expected behavior). If it is lower case, it
498  *   searches for the substring anywhere in the name. This applies to either
499  *   last name, first name, and middle name.
500  * Also allows first name followed by middle and/or last name when separated by spaces.
501  * @param string $term
502  * @param string $given
503  * @param string $orderby
504  * @param string $limit
505  * @param string $start
506  * @return array
507  */
508 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")
510     $names = getPatientNameSplit($term);
512     foreach ($names as $key => $val) {
513         if (!empty($val)) {
514             if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
515                 $names[$key] = '%' . $val . '%';
516             } else {
517                 $names[$key] = $val . '%';
518             }
519         }
520     }
522     // Debugging section below
523     //if(array_key_exists('first',$names)) {
524     //    error_log("first name search term :".$names['first']);
525     //}
526     //if(array_key_exists('middle',$names)) {
527     //    error_log("middle name search term :".$names['middle']);
528     //}
529     //if(array_key_exists('last',$names)) {
530     //    error_log("last name search term :".$names['last']);
531     //}
532     // Debugging section above
534     $sqlBindArray = array();
535     if (array_key_exists('last', $names) && $names['last'] == '') {
536         // Do not search last name
537         $where = "fname LIKE ? ";
538         array_push($sqlBindArray, $names['first']);
539         if ($names['middle'] != '') {
540             $where .= "AND mname LIKE ? ";
541             array_push($sqlBindArray, $names['middle']);
542         }
543     } elseif (array_key_exists('first', $names) && $names['first'] == '') {
544         // Do not search first name or middle name
545         $where = "lname LIKE ? ";
546         array_push($sqlBindArray, $names['last']);
547     } elseif ($names['first'] == '' && $names['last'] != '') {
548         // Search both first name and last name with same term
549         $names['first'] = $names['last'];
550         $where = "lname LIKE ? OR fname LIKE ? ";
551         array_push($sqlBindArray, $names['last'], $names['first']);
552     } elseif ($names['middle'] != '') {
553         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
554         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
555     } else {
556         $where = "lname LIKE ? AND fname LIKE ? ";
557         array_push($sqlBindArray, $names['last'], $names['first']);
558     }
560     if (!empty($GLOBALS['pt_restrict_field'])) {
561         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
562             $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
563                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
564                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
565             array_push($sqlBindArray, $_SESSION{"authUser"});
566         }
567     }
569     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
570     if ($limit != "all") {
571         $sql .= " LIMIT $start, $limit";
572     }
574     $rez = sqlStatement($sql, $sqlBindArray);
576     $returnval=array();
577     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
578         $returnval[$iter] = $row;
579     }
581     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
582     return $returnval;
585  * Accept a string used by a search function expected to find a patient name,
586  * then split up the string if a comma or space exists. Return an array having
587  * from 1 to 3 elements, named first, middle, and last.
588  * See above getPatientLnames() function for details on how the splitting occurs.
589  * @param string $term
590  * @return array
591  */
592 function getPatientNameSplit($term)
594     $term = trim($term);
595     if (strpos($term, ',') !== false) {
596         $names = explode(',', $term);
597         $n['last'] = $names[0];
598         if (strpos(trim($names[1]), ' ') !== false) {
599             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
600         } else {
601             $n['first'] = $names[1];
602         }
603     } elseif (strpos($term, ' ') !== false) {
604         $names = explode(' ', $term);
605         if (count($names) == 1) {
606             $n['last'] = $names[0];
607         } elseif (count($names) == 3) {
608             $n['first'] = $names[0];
609             $n['middle'] = $names[1];
610             $n['last'] = $names[2];
611         } else {
612             // This will handle first and last name or first followed by
613             // multiple names only using just the last of the names in the list.
614             $n['first'] = $names[0];
615             $n['last'] = end($names);
616         }
617     } else {
618         $n['last'] = $term;
619         if (empty($n['last'])) {
620             $n['last'] = '%';
621         }
622     }
624     // Trim whitespace off the names before returning
625     foreach ($n as $key => $val) {
626         $n[$key] = trim($val);
627     }
629     return $n; // associative array containing names
632 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")
635     $sqlBindArray = array();
636     $where = "pubpid LIKE ? ";
637     array_push($sqlBindArray, $pid."%");
638     if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
639         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
640             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
641                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
642                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
643             array_push($sqlBindArray, $_SESSION{"authUser"});
644         }
645     }
647     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
648     if ($limit != "all") {
649         $sql .= " limit $start, $limit";
650     }
652     $rez = sqlStatement($sql, $sqlBindArray);
653     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
654         $returnval[$iter]=$row;
655     }
657     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
658     return $returnval;
661 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")
663     $layoutCols = sqlStatement(
664         "SELECT field_id FROM layout_options WHERE form_id = 'DEM' AND field_id not like ? AND uor !=0",
665         array('em\_%')
666     );
668     $sqlBindArray = array();
669     $where = "";
670     for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
671         if ($iter > 0) {
672             $where .= " or ";
673         }
675         $where .= " ".add_escape_custom($row["field_id"])." like ? ";
676         array_push($sqlBindArray, "%".$searchTerm."%");
677     }
679     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
680     if ($limit != "all") {
681         $sql .= " limit $start, $limit";
682     }
684     $rez = sqlStatement($sql, $sqlBindArray);
685     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
686         $returnval[$iter]=$row;
687     }
689     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
690     return $returnval;
693 function getByPatientDemographicsFilter(
694     $searchFields,
695     $searchTerm = "%",
696     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
697     $orderby = "lname ASC, fname ASC",
698     $limit = "all",
699     $start = "0",
700     $search_service_code = ''
701 ) {
703     $layoutCols = explode('~', $searchFields);
704     $sqlBindArray = array();
705     $where = "";
706     $i = 0;
707     foreach ($layoutCols as $val) {
708         if (empty($val)) {
709             continue;
710         }
712         if ($i > 0) {
713             $where .= " or ";
714         }
716         if ($val == 'pid') {
717             $where .= " ".add_escape_custom($val)." = ? ";
718                 array_push($sqlBindArray, $searchTerm);
719         } else {
720             $where .= " ".add_escape_custom($val)." like ? ";
721                 array_push($sqlBindArray, $searchTerm."%");
722         }
724         $i++;
725     }
727   // If no search terms, ensure valid syntax.
728     if ($i == 0) {
729         $where = "1 = 1";
730     }
732   // If a non-empty service code was given, then restrict to patients who
733   // have been provided that service.  Since the code is used in a LIKE
734   // clause, % and _ wildcards are supported.
735     if ($search_service_code) {
736         $where = "( $where ) AND " .
737         "( SELECT COUNT(*) FROM billing AS b WHERE " .
738         "b.pid = patient_data.pid AND " .
739         "b.activity = 1 AND " .
740         "b.code_type != 'COPAY' AND " .
741         "b.code LIKE ? " .
742         ") > 0";
743         array_push($sqlBindArray, $search_service_code);
744     }
746     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
747     if ($limit != "all") {
748         $sql .= " limit $start, $limit";
749     }
751     $rez = sqlStatement($sql, $sqlBindArray);
752     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
753         $returnval[$iter]=$row;
754     }
756     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
757     return $returnval;
760 // return a collection of Patient PIDs
761 // new arg style by JRM March 2008
762 // 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")
763 function getPatientPID($args)
765     $pid = "%";
766     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
767     $orderby = "lname ASC, fname ASC";
768     $limit="all";
769     $start="0";
771     // alter default values if defined in the passed in args
772     if (isset($args['pid'])) {
773         $pid = $args['pid'];
774     }
776     if (isset($args['given'])) {
777         $given = $args['given'];
778     }
780     if (isset($args['orderby'])) {
781         $orderby = $args['orderby'];
782     }
784     if (isset($args['limit'])) {
785         $limit = $args['limit'];
786     }
788     if (isset($args['start'])) {
789         $start = $args['start'];
790     }
792     $command = "=";
793     if ($pid == -1) {
794         $pid = "%";
795     } elseif (empty($pid)) {
796         $pid = "NULL";
797     }
799     if (strstr($pid, "%")) {
800         $command = "like";
801     }
803     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
804     if ($limit != "all") {
805         $sql .= " limit $start, $limit";
806     }
808     $rez = sqlStatement($sql);
809     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
810         $returnval[$iter]=$row;
811     }
813     return $returnval;
816 /* return a patient's name in the format LAST, FIRST */
817 function getPatientName($pid)
819     if (empty($pid)) {
820         return "";
821     }
823     $patientData = getPatientPID(array("pid"=>$pid));
824     if (empty($patientData[0]['lname'])) {
825         return "";
826     }
828     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
829     return $patientName;
832 /* find patient data by DOB */
833 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
835     $DOB = fixDate($DOB, $DOB);
836     $sqlBindArray = array();
837     $where = "DOB like ? ";
838     array_push($sqlBindArray, $DOB."%");
839     if (!empty($GLOBALS['pt_restrict_field'])) {
840         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
841             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
842                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
843                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
844             array_push($sqlBindArray, $_SESSION{"authUser"});
845         }
846     }
848     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
850     if ($limit != "all") {
851         $sql .= " LIMIT $start, $limit";
852     }
854     $rez = sqlStatement($sql, $sqlBindArray);
855     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
856         $returnval[$iter]=$row;
857     }
859     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
860     return $returnval;
863 /* find patient data by SSN */
864 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
866     $sqlBindArray = array();
867     $where = "ss LIKE ?";
868     array_push($sqlBindArray, $ss."%");
869     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
870     if ($limit != "all") {
871         $sql .= " LIMIT $start, $limit";
872     }
874     $rez = sqlStatement($sql, $sqlBindArray);
875     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
876         $returnval[$iter]=$row;
877     }
879     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
880     return $returnval;
883 //(CHEMED) Search by phone number
884 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
886     $phone = preg_replace("/[[:punct:]]/", "", $phone);
887     $sqlBindArray = array();
888     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
889     array_push($sqlBindArray, $phone);
890     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
891     if ($limit != "all") {
892         $sql .= " LIMIT $start, $limit";
893     }
895     $rez = sqlStatement($sql, $sqlBindArray);
896     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
897         $returnval[$iter]=$row;
898     }
900     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
901     return $returnval;
904 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
906     $sql="select $given from patient_data order by $orderby";
908     if ($limit != "all") {
909         $sql .= " limit $start, $limit";
910     }
912     $rez = sqlStatement($sql);
913     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
914         $returnval[$iter]=$row;
915     }
917     return $returnval;
920 //----------------------input functions
921 function newPatientData(
922     $db_id = "",
923     $title = "",
924     $fname = "",
925     $lname = "",
926     $mname = "",
927     $sex = "",
928     $DOB = "",
929     $street = "",
930     $postal_code = "",
931     $city = "",
932     $state = "",
933     $country_code = "",
934     $ss = "",
935     $occupation = "",
936     $phone_home = "",
937     $phone_biz = "",
938     $phone_contact = "",
939     $status = "",
940     $contact_relationship = "",
941     $referrer = "",
942     $referrerID = "",
943     $email = "",
944     $language = "",
945     $ethnoracial = "",
946     $interpretter = "",
947     $migrantseasonal = "",
948     $family_size = "",
949     $monthly_income = "",
950     $homeless = "",
951     $financial_review = "",
952     $pubpid = "",
953     $pid = "MAX(pid)+1",
954     $providerID = "",
955     $genericname1 = "",
956     $genericval1 = "",
957     $genericname2 = "",
958     $genericval2 = "",
959     $billing_note = "",
960     $phone_cell = "",
961     $hipaa_mail = "",
962     $hipaa_voice = "",
963     $squad = 0,
964     $pharmacy_id = 0,
965     $drivers_license = "",
966     $hipaa_notice = "",
967     $hipaa_message = "",
968     $regdate = ""
969 ) {
971     $DOB = fixDate($DOB);
972     $regdate = fixDate($regdate);
974     $fitness = 0;
975     $referral_source = '';
976     if ($pid) {
977         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
978         // Check for brain damage:
979         if ($db_id != $rez['id']) {
980             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
981               $rez['id'] . "' to '$db_id' for pid '$pid'";
982             die($errmsg);
983         }
985         $fitness = $rez['fitness'];
986         $referral_source = $rez['referral_source'];
987     }
989     // Get the default price level.
990     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
991       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
992     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
994     $query = ("replace into patient_data set
995         id='$db_id',
996         title='$title',
997         fname='$fname',
998         lname='$lname',
999         mname='$mname',
1000         sex='$sex',
1001         DOB='$DOB',
1002         street='$street',
1003         postal_code='$postal_code',
1004         city='$city',
1005         state='$state',
1006         country_code='$country_code',
1007         drivers_license='$drivers_license',
1008         ss='$ss',
1009         occupation='$occupation',
1010         phone_home='$phone_home',
1011         phone_biz='$phone_biz',
1012         phone_contact='$phone_contact',
1013         status='$status',
1014         contact_relationship='$contact_relationship',
1015         referrer='$referrer',
1016         referrerID='$referrerID',
1017         email='$email',
1018         language='$language',
1019         ethnoracial='$ethnoracial',
1020         interpretter='$interpretter',
1021         migrantseasonal='$migrantseasonal',
1022         family_size='$family_size',
1023         monthly_income='$monthly_income',
1024         homeless='$homeless',
1025         financial_review='$financial_review',
1026         pubpid='$pubpid',
1027         pid = $pid,
1028         providerID = '$providerID',
1029         genericname1 = '$genericname1',
1030         genericval1 = '$genericval1',
1031         genericname2 = '$genericname2',
1032         genericval2 = '$genericval2',
1033         billing_note= '$billing_note',
1034         phone_cell = '$phone_cell',
1035         pharmacy_id = '$pharmacy_id',
1036         hipaa_mail = '$hipaa_mail',
1037         hipaa_voice = '$hipaa_voice',
1038         hipaa_notice = '$hipaa_notice',
1039         hipaa_message = '$hipaa_message',
1040         squad = '$squad',
1041         fitness='$fitness',
1042         referral_source='$referral_source',
1043         regdate='$regdate',
1044         pricelevel='$pricelevel',
1045         date=NOW()");
1047     $id = sqlInsert($query);
1049     if (!$db_id) {
1050       // find the last inserted id for new patient case
1051         $db_id = getSqlLastID();
1052     }
1054     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1056     return $foo['pid'];
1059 // Supported input date formats are:
1060 //   mm/dd/yyyy
1061 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1062 //   yyyy/mm/dd
1063 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1065 function fixDate($date, $default = "0000-00-00")
1067     $fixed_date = $default;
1068     $date = trim($date);
1069     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1070         $dmy = preg_split("'[/.-]'", $date);
1071         if ($dmy[0] > 99) {
1072             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1073         } else {
1074             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1075                 if ($dmy[2] < 1000) {
1076                     $dmy[2] += 1900;
1077                 }
1079                 if ($dmy[2] < 1910) {
1080                     $dmy[2] += 100;
1081                 }
1082             }
1084             // phone_country_code indicates format of ambiguous input dates.
1085             if ($GLOBALS['phone_country_code'] == 1) {
1086                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1087             } else {
1088                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1089             }
1090         }
1091     }
1093     return $fixed_date;
1096 function pdValueOrNull($key, $value)
1098     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1099     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1100     (empty($value) || $value == '0000-00-00')) {
1101         return "NULL";
1102     } else {
1103         return "'" . add_escape_custom($value) . "'";
1104     }
1107 // Create or update patient data from an array.
1109 function updatePatientData($pid, $new, $create = false)
1111   /*******************************************************************
1112     $real = getPatientData($pid);
1113     $new['DOB'] = fixDate($new['DOB']);
1114     while(list($key, $value) = each ($new))
1115         $real[$key] = $value;
1116     $real['date'] = "'+NOW()+'";
1117     $real['id'] = "";
1118     $sql = "insert into patient_data set ";
1119     while(list($key, $value) = each($real))
1120         $sql .= $key." = '$value', ";
1121     $sql = substr($sql, 0, -2);
1122     return sqlInsert($sql);
1123   *******************************************************************/
1125   // The above was broken, though seems intent to insert a new patient_data
1126   // row for each update.  A good idea, but nothing is doing that yet so
1127   // the code below does not yet attempt it.
1129     $new['DOB'] = fixDate($new['DOB']);
1131     if ($create) {
1132         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1133         foreach ($new as $key => $value) {
1134             if ($key == 'id') {
1135                 continue;
1136             }
1138             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1139         }
1141         $db_id = sqlInsert($sql);
1142     } else {
1143         $db_id = $new['id'];
1144         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1145         // Check for brain damage:
1146         if ($pid != $rez['pid']) {
1147             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1148             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1149             die($errmsg);
1150         }
1152         $sql = "UPDATE patient_data SET date = NOW()";
1153         foreach ($new as $key => $value) {
1154             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1155         }
1157         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1158         sqlStatement($sql);
1159     }
1161     return $db_id;
1164 function newEmployerData(
1165     $pid,
1166     $name = "",
1167     $street = "",
1168     $postal_code = "",
1169     $city = "",
1170     $state = "",
1171     $country = ""
1172 ) {
1174     return sqlInsert("insert into employer_data set
1175         name='$name',
1176         street='$street',
1177         postal_code='$postal_code',
1178         city='$city',
1179         state='$state',
1180         country='$country',
1181         pid='$pid',
1182         date=NOW()
1183         ");
1186 // Create or update employer data from an array.
1188 function updateEmployerData($pid, $new, $create = false)
1190     $colnames = array('name','street','city','state','postal_code','country');
1192     if ($create) {
1193         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1194         foreach ($colnames as $key) {
1195             $value = isset($new[$key]) ? $new[$key] : '';
1196             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1197         }
1199         return sqlInsert("INSERT INTO employer_data SET $set");
1200     } else {
1201         $set = '';
1202         $old = getEmployerData($pid);
1203         $modified = false;
1204         foreach ($colnames as $key) {
1205             $value = empty($old[$key]) ? '' : $old[$key];
1206             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1207                 $value = $new[$key];
1208                 $modified = true;
1209             }
1211             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1212         }
1214         if ($modified) {
1215             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1216             return sqlInsert("INSERT INTO employer_data SET $set");
1217         }
1219         return $old['id'];
1220     }
1223 // This updates or adds the given insurance data info, while retaining any
1224 // previously added insurance_data rows that should be preserved.
1225 // This does not directly support the maintenance of non-current insurance.
1227 function newInsuranceData(
1228     $pid,
1229     $type = "",
1230     $provider = "",
1231     $policy_number = "",
1232     $group_number = "",
1233     $plan_name = "",
1234     $subscriber_lname = "",
1235     $subscriber_mname = "",
1236     $subscriber_fname = "",
1237     $subscriber_relationship = "",
1238     $subscriber_ss = "",
1239     $subscriber_DOB = "",
1240     $subscriber_street = "",
1241     $subscriber_postal_code = "",
1242     $subscriber_city = "",
1243     $subscriber_state = "",
1244     $subscriber_country = "",
1245     $subscriber_phone = "",
1246     $subscriber_employer = "",
1247     $subscriber_employer_street = "",
1248     $subscriber_employer_city = "",
1249     $subscriber_employer_postal_code = "",
1250     $subscriber_employer_state = "",
1251     $subscriber_employer_country = "",
1252     $copay = "",
1253     $subscriber_sex = "",
1254     $effective_date = "0000-00-00",
1255     $accept_assignment = "TRUE",
1256     $policy_type = ""
1257 ) {
1259     if (strlen($type) <= 0) {
1260         return false;
1261     }
1263   // If a bad date was passed, err on the side of caution.
1264     $effective_date = fixDate($effective_date, date('Y-m-d'));
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     while (list($key, $value) = each($new)) {
1377         if (in_array($key, $fields)) {
1378             $use[$key] = $value;
1379         }
1380     }
1382     $sql = "UPDATE insurance_data SET ";
1383     while (list($key, $value) = each($use)) {
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         while (list($key, $value) = each($new)) {
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     while (list($key, $value) = each($new)) {
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     while (list($key, $value) = each($real)) {
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  * @return number The balance.
1886  */
1887 function get_patient_balance($pid, $with_insurance = false)
1889     $balance = 0;
1890     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1891       "last_level_closed, stmt_count " .
1892       "FROM form_encounter WHERE pid = ?", array($pid));
1893     while ($ferow = sqlFetchArray($feres)) {
1894         $encounter = $ferow['encounter'];
1895         $dos = substr($ferow['date'], 0, 10);
1896         $insarr = getEffectiveInsurances($pid, $dos);
1897         $inscount = count($insarr);
1898         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1899             // It's out to insurance so only the co-pay might be due.
1900             $brow = sqlQuery(
1901                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1902                 "pid = ? AND encounter = ? AND " .
1903                 "code_type = 'copay' AND activity = 1",
1904                 array($pid, $encounter)
1905             );
1906             $drow = sqlQuery(
1907                 "SELECT SUM(pay_amount) AS payments " .
1908                 "FROM ar_activity WHERE " .
1909                 "pid = ? AND encounter = ? AND payer_type = 0",
1910                 array($pid, $encounter)
1911             );
1912             $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1913             if ($ptbal > 0) {
1914                 $balance += $ptbal;
1915             }
1916         } else {
1917             // Including insurance or not out to insurance, everything is due.
1918             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1919             "pid = ? AND encounter = ? AND " .
1920             "activity = 1", array($pid, $encounter));
1921             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1922               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1923               "pid = ? AND encounter = ?", array($pid, $encounter));
1924             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1925               "pid = ? AND encounter = ?", array($pid, $encounter));
1926             $balance += $brow['amount'] + $srow['amount']
1927               - $drow['payments'] - $drow['adjustments'];
1928         }
1929     }
1931     return sprintf('%01.2f', $balance);
1934 // Function to check if patient is deceased.
1935 //  Param:
1936 //    $pid  - patient id
1937 //    $date - date checking if deceased (will default to current date if blank)
1938 //  Return:
1939 //    If deceased, then will return the number of
1940 //      days that patient has been deceased.
1941 //    If not deceased, then will return false.
1942 function is_patient_deceased($pid, $date = '')
1945   // Set date to current if not set
1946     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1948   // Query for deceased status (gets days deceased if patient is deceased)
1949     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1950                       "FROM `patient_data` " .
1951                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1953     if (empty($results)) {
1954         // Patient is alive, so return false
1955         return false;
1956     } else {
1957         // Patient is dead, so return the number of days patient has been deceased.
1958         //  Don't let it be zero days or else will confuse calls to this function.
1959         if ($results['days_deceased'] === 0) {
1960             $results['days_deceased'] = 1;
1961         }
1963         return $results['days_deceased'];
1964     }