Proposed launch commit for new themes and bootstrap conversion.
[openemr.git] / library / patient.inc
blobfdc9c23d1a6d68e1bd80f614880011b2396216a2
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     $s .= "  <td class='ftitlecell1'>$repname</td>\n";
211     $s .= "  <td class='ftitlecell2'>\n";
212     $r = getFacility($facid);
213     if (!empty($r)) {
214         $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
215         if ($r['street']) {
216             $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
217         }
219         if ($r['city'] || $r['state'] || $r['postal_code']) {
220             $s .= "<br />";
221             if ($r['city']) {
222                 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
223             }
225             if ($r['state']) {
226                 if ($r['city']) {
227                     $s .= ", \n";
228                 }
230                 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
231             }
233             if ($r['postal_code']) {
234                 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
235             }
237             $s .= "\n";
238         }
240         if ($r['country_code']) {
241             $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
242         }
244         if (preg_match('/[1-9]/', $r['phone'])) {
245             $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
246         }
247     }
249     $s .= "  </td>\n";
250     $s .= " </tr>\n";
251     $s .= "</table>\n";
252     return $s;
256 GET FACILITIES
258 returns all facilities or just the id for the first one
259 (FACILITY FILTERING (lemonsoftware))
261 @param string - if 'first' return first facility ordered by id
262 @return array | int for 'first' case
264 function getFacilities($first = '')
266     global $facilityService;
268     $fres = $facilityService->getAll();
270     if ($first == 'first') {
271         return $fres[0]['id'];
272     } else {
273         return $fres;
274     }
278 GET SERVICE FACILITIES
280 returns all service_location facilities or just the id for the first one
281 (FACILITY FILTERING (CHEMED))
283 @param string - if 'first' return first facility ordered by id
284 @return array | int for 'first' case
286 function getServiceFacilities($first = '')
288     global $facilityService;
290     $fres = $facilityService->getAllServiceLocations();
292     if ($first == 'first') {
293         return $fres[0]['id'];
294     } else {
295         return $fres;
296     }
299 //(CHEMED) facility filter
300 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
302     $param1 = "";
303     if ($providers_only === 'any') {
304         $param1 = " AND authorized = 1 AND active = 1 ";
305     } else if ($providers_only) {
306         $param1 = " AND authorized = 1 AND calendar = 1 ";
307     }
309     //--------------------------------
310     //(CHEMED) facility filter
311     $param2 = "";
312     if ($facility) {
313         if ($GLOBALS['restrict_user_facility']) {
314             $param2 = " AND (facility_id = $facility
315           OR  $facility IN
316                 (select facility_id
317                 from users_facility
318                 where tablename = 'users'
319                 and table_id = id)
320                 )
321           ";
322         } else {
323             $param2 = " AND facility_id = $facility ";
324         }
325     }
327     //--------------------------------
329     $command = "=";
330     if ($providerID == "%") {
331         $command = "like";
332     }
334     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
335         "from users where username != '' and active = 1 and id $command '" .
336         add_escape_custom($providerID) . "' " . $param1 . $param2;
337     // sort by last name -- JRM June 2008
338     $query .= " ORDER BY lname, fname ";
339     $rez = sqlStatement($query);
340     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
341         $returnval[$iter]=$row;
342     }
344     //if only one result returned take the key/value pairs in array [0] and merge them down into
345     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
347     if ($iter==1) {
348         $akeys = array_keys($returnval[0]);
349         foreach ($akeys as $key) {
350             $returnval[0][$key] = $returnval[0][$key];
351         }
352     }
354     return $returnval;
357 //same as above but does not reduce if only 1 row returned
358 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
360     $param1 = "";
361     if ($providers_only) {
362         $param1 = "AND authorized=1";
363     }
365     $command = "=";
366     if ($providerID == "%") {
367         $command = "like";
368     }
370     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
371         "from users where active = 1 and username != '' and id $command '" .
372         add_escape_custom($providerID) . "' " . $param1;
374     $rez = sqlStatement($query);
375     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
376         $returnval[$iter]=$row;
377     }
379     return $returnval;
382 function getProviderName($providerID)
384     $pi = getProviderInfo($providerID, 'any');
385     if (strlen($pi[0]["lname"]) > 0) {
386         if (strlen($pi[0]["suffix"]) > 0) {
387             $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
388         }
390         return $pi[0]['fname'] . " " . $pi[0]['lname'];
391     }
393     return "";
396 function getProviderId($providerName)
398     $query = "select id from users where username = ?";
399     $rez = sqlStatement($query, array($providerName));
400     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
401         $returnval[$iter]=$row;
402     }
404     return $returnval;
407 function getEthnoRacials()
409     $returnval = array("");
410     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
411     $rez = sqlStatement($sql);
412     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
413         if (($row["ethnoracial"] != "")) {
414             array_push($returnval, $row["ethnoracial"]);
415         }
416     }
418     return $returnval;
421 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
424     if ($dateStart && $dateEnd) {
425         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
426     } else if ($dateStart && !$dateEnd) {
427         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
428     } else if (!$dateStart && $dateEnd) {
429         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd));
430     } else {
431         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
432     }
434     if ($given == 'tobacco') {
435         $res = sqlQuery("select $given from history_data where pid = ? and tobacco is not null and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
436     }
438     return $res;
441 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
442 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
444     $sql = "select $given from insurance_data as insd " .
445     "left join insurance_companies as ic on ic.id = insd.provider " .
446     "where pid = ? and type = ? order by date DESC limit 1";
447     return sqlQuery($sql, array($pid, $type));
450 function getInsuranceDataByDate(
451     $pid,
452     $date,
453     $type,
454     $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
455 ) {
456  // this must take the date in the following manner: YYYY-MM-DD
457   // this function recalls the insurance value that was most recently enterred from the
458   // given date. it will call up most recent records up to and on the date given,
459   // but not records enterred after the given date
460     $sql = "select $given from insurance_data as insd " .
461     "left join insurance_companies as ic on ic.id = provider " .
462     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
463     "type=? order by date DESC limit 1";
464     return sqlQuery($sql, array($pid,$date,$type));
467 function getEmployerData($pid, $given = "*")
469     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
470     return sqlQuery($sql, array($pid));
473 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
475   // When the limit is exceeded, find out what the unlimited count would be.
476     $GLOBALS['PATIENT_INC_COUNT'] = $count;
477   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
478     if ($limit != "all") {
479         $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
480         $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
481     }
485  * Allow the last name to be followed by a comma and some part of a first name(can
486  *   also place middle name after the first name with a space separating them)
487  * Allows comma alone followed by some part of a first name(can also place middle name
488  *   after the first name with a space separating them).
489  * Allows comma alone preceded by some part of a last name.
490  * If no comma or space, then will search both last name and first name.
491  * If the first letter of either name is capital, searches for name starting
492  *   with given substring (the expected behavior). If it is lower case, it
493  *   searches for the substring anywhere in the name. This applies to either
494  *   last name, first name, and middle name.
495  * Also allows first name followed by middle and/or last name when separated by spaces.
496  * @param string $term
497  * @param string $given
498  * @param string $orderby
499  * @param string $limit
500  * @param string $start
501  * @return array
502  */
503 function getPatientLnames($term = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
505     $names = getPatientNameSplit($term);
507     foreach ($names as $key => $val) {
508         if (!empty($val)) {
509             if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
510                 $names[$key] = '%' . $val . '%';
511             } else {
512                 $names[$key] = $val . '%';
513             }
514         }
515     }
517     // Debugging section below
518     //if(array_key_exists('first',$names)) {
519     //    error_log("first name search term :".$names['first']);
520     //}
521     //if(array_key_exists('middle',$names)) {
522     //    error_log("middle name search term :".$names['middle']);
523     //}
524     //if(array_key_exists('last',$names)) {
525     //    error_log("last name search term :".$names['last']);
526     //}
527     // Debugging section above
529     $sqlBindArray = array();
530     if (array_key_exists('last', $names) && $names['last'] == '') {
531         // Do not search last name
532         $where = "fname LIKE ? ";
533         array_push($sqlBindArray, $names['first']);
534         if ($names['middle'] != '') {
535             $where .= "AND mname LIKE ? ";
536             array_push($sqlBindArray, $names['middle']);
537         }
538     } elseif (array_key_exists('first', $names) && $names['first'] == '') {
539         // Do not search first name or middle name
540         $where = "lname LIKE ? ";
541         array_push($sqlBindArray, $names['last']);
542     } elseif ($names['first'] == '' && $names['last'] != '') {
543         // Search both first name and last name with same term
544         $names['first'] = $names['last'];
545         $where = "lname LIKE ? OR fname LIKE ? ";
546         array_push($sqlBindArray, $names['last'], $names['first']);
547     } elseif ($names['middle'] != '') {
548         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
549         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
550     } else {
551         $where = "lname LIKE ? AND fname LIKE ? ";
552         array_push($sqlBindArray, $names['last'], $names['first']);
553     }
555     if (!empty($GLOBALS['pt_restrict_field'])) {
556         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
557             $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
558                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
559                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
560             array_push($sqlBindArray, $_SESSION{"authUser"});
561         }
562     }
564     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
565     if ($limit != "all") {
566         $sql .= " LIMIT $start, $limit";
567     }
569     $rez = sqlStatement($sql, $sqlBindArray);
571     $returnval=array();
572     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
573         $returnval[$iter] = $row;
574     }
576     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
577     return $returnval;
580  * Accept a string used by a search function expected to find a patient name,
581  * then split up the string if a comma or space exists. Return an array having
582  * from 1 to 3 elements, named first, middle, and last.
583  * See above getPatientLnames() function for details on how the splitting occurs.
584  * @param string $term
585  * @return array
586  */
587 function getPatientNameSplit($term)
589     $term = trim($term);
590     if (strpos($term, ',') !== false) {
591         $names = explode(',', $term);
592         $n['last'] = $names[0];
593         if (strpos(trim($names[1]), ' ') !== false) {
594             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
595         } else {
596             $n['first'] = $names[1];
597         }
598     } elseif (strpos($term, ' ') !== false) {
599         $names = explode(' ', $term);
600         if (count($names) == 1) {
601             $n['last'] = $names[0];
602         } elseif (count($names) == 3) {
603             $n['first'] = $names[0];
604             $n['middle'] = $names[1];
605             $n['last'] = $names[2];
606         } else {
607             // This will handle first and last name or first followed by
608             // multiple names only using just the last of the names in the list.
609             $n['first'] = $names[0];
610             $n['last'] = end($names);
611         }
612     } else {
613         $n['last'] = $term;
614         if (empty($n['last'])) {
615             $n['last'] = '%';
616         }
617     }
619     // Trim whitespace off the names before returning
620     foreach ($n as $key => $val) {
621         $n[$key] = trim($val);
622     }
624     return $n; // associative array containing names
627 function getPatientId($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
630     $sqlBindArray = array();
631     $where = "pubpid LIKE ? ";
632     array_push($sqlBindArray, $pid."%");
633     if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
634         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
635             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
636                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
637                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
638             array_push($sqlBindArray, $_SESSION{"authUser"});
639         }
640     }
642     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
643     if ($limit != "all") {
644         $sql .= " limit $start, $limit";
645     }
647     $rez = sqlStatement($sql, $sqlBindArray);
648     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
649         $returnval[$iter]=$row;
650     }
652     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
653     return $returnval;
656 function getByPatientDemographics($searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
658     $layoutCols = sqlStatement("SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%"));
660     $sqlBindArray = array();
661     $where = "";
662     for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
663         if ($iter > 0) {
664             $where .= " or ";
665         }
667         $where .= " ".add_escape_custom($row["field_id"])." like ? ";
668         array_push($sqlBindArray, "%".$searchTerm."%");
669     }
671     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
672     if ($limit != "all") {
673         $sql .= " limit $start, $limit";
674     }
676     $rez = sqlStatement($sql, $sqlBindArray);
677     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
678         $returnval[$iter]=$row;
679     }
681     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
682     return $returnval;
685 function getByPatientDemographicsFilter(
686     $searchFields,
687     $searchTerm = "%",
688     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
689     $orderby = "lname ASC, fname ASC",
690     $limit = "all",
691     $start = "0",
692     $search_service_code = ''
693 ) {
695     $layoutCols = explode('~', $searchFields);
696     $sqlBindArray = array();
697     $where = "";
698     $i = 0;
699     foreach ($layoutCols as $val) {
700         if (empty($val)) {
701             continue;
702         }
704         if ($i > 0) {
705             $where .= " or ";
706         }
708         if ($val == 'pid') {
709             $where .= " ".add_escape_custom($val)." = ? ";
710                 array_push($sqlBindArray, $searchTerm);
711         } else {
712             $where .= " ".add_escape_custom($val)." like ? ";
713                 array_push($sqlBindArray, $searchTerm."%");
714         }
716         $i++;
717     }
719   // If no search terms, ensure valid syntax.
720     if ($i == 0) {
721         $where = "1 = 1";
722     }
724   // If a non-empty service code was given, then restrict to patients who
725   // have been provided that service.  Since the code is used in a LIKE
726   // clause, % and _ wildcards are supported.
727     if ($search_service_code) {
728         $where = "( $where ) AND " .
729         "( SELECT COUNT(*) FROM billing AS b WHERE " .
730         "b.pid = patient_data.pid AND " .
731         "b.activity = 1 AND " .
732         "b.code_type != 'COPAY' AND " .
733         "b.code LIKE ? " .
734         ") > 0";
735         array_push($sqlBindArray, $search_service_code);
736     }
738     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
739     if ($limit != "all") {
740         $sql .= " limit $start, $limit";
741     }
743     $rez = sqlStatement($sql, $sqlBindArray);
744     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
745         $returnval[$iter]=$row;
746     }
748     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
749     return $returnval;
752 // return a collection of Patient PIDs
753 // new arg style by JRM March 2008
754 // 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")
755 function getPatientPID($args)
757     $pid = "%";
758     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
759     $orderby = "lname ASC, fname ASC";
760     $limit="all";
761     $start="0";
763     // alter default values if defined in the passed in args
764     if (isset($args['pid'])) {
765         $pid = $args['pid'];
766     }
768     if (isset($args['given'])) {
769         $given = $args['given'];
770     }
772     if (isset($args['orderby'])) {
773         $orderby = $args['orderby'];
774     }
776     if (isset($args['limit'])) {
777         $limit = $args['limit'];
778     }
780     if (isset($args['start'])) {
781         $start = $args['start'];
782     }
784     $command = "=";
785     if ($pid == -1) {
786         $pid = "%";
787     } elseif (empty($pid)) {
788         $pid = "NULL";
789     }
791     if (strstr($pid, "%")) {
792         $command = "like";
793     }
795     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
796     if ($limit != "all") {
797         $sql .= " limit $start, $limit";
798     }
800     $rez = sqlStatement($sql);
801     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
802         $returnval[$iter]=$row;
803     }
805     return $returnval;
808 /* return a patient's name in the format LAST, FIRST */
809 function getPatientName($pid)
811     if (empty($pid)) {
812         return "";
813     }
815     $patientData = getPatientPID(array("pid"=>$pid));
816     if (empty($patientData[0]['lname'])) {
817         return "";
818     }
820     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
821     return $patientName;
824 /* find patient data by DOB */
825 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
827     $DOB = fixDate($DOB, $DOB);
828     $sqlBindArray = array();
829     $where = "DOB like ? ";
830     array_push($sqlBindArray, $DOB."%");
831     if (!empty($GLOBALS['pt_restrict_field'])) {
832         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
833             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
834                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
835                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
836             array_push($sqlBindArray, $_SESSION{"authUser"});
837         }
838     }
840     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
842     if ($limit != "all") {
843         $sql .= " LIMIT $start, $limit";
844     }
846     $rez = sqlStatement($sql, $sqlBindArray);
847     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
848         $returnval[$iter]=$row;
849     }
851     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
852     return $returnval;
855 /* find patient data by SSN */
856 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
858     $sqlBindArray = array();
859     $where = "ss LIKE ?";
860     array_push($sqlBindArray, $ss."%");
861     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
862     if ($limit != "all") {
863         $sql .= " LIMIT $start, $limit";
864     }
866     $rez = sqlStatement($sql, $sqlBindArray);
867     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
868         $returnval[$iter]=$row;
869     }
871     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
872     return $returnval;
875 //(CHEMED) Search by phone number
876 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
878     $phone = preg_replace("/[[:punct:]]/", "", $phone);
879     $sqlBindArray = array();
880     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
881     array_push($sqlBindArray, $phone);
882     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
883     if ($limit != "all") {
884         $sql .= " LIMIT $start, $limit";
885     }
887     $rez = sqlStatement($sql, $sqlBindArray);
888     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
889         $returnval[$iter]=$row;
890     }
892     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
893     return $returnval;
896 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
898     $sql="select $given from patient_data order by $orderby";
900     if ($limit != "all") {
901         $sql .= " limit $start, $limit";
902     }
904     $rez = sqlStatement($sql);
905     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
906         $returnval[$iter]=$row;
907     }
909     return $returnval;
912 //----------------------input functions
913 function newPatientData(
914     $db_id = "",
915     $title = "",
916     $fname = "",
917     $lname = "",
918     $mname = "",
919     $sex = "",
920     $DOB = "",
921     $street = "",
922     $postal_code = "",
923     $city = "",
924     $state = "",
925     $country_code = "",
926     $ss = "",
927     $occupation = "",
928     $phone_home = "",
929     $phone_biz = "",
930     $phone_contact = "",
931     $status = "",
932     $contact_relationship = "",
933     $referrer = "",
934     $referrerID = "",
935     $email = "",
936     $language = "",
937     $ethnoracial = "",
938     $interpretter = "",
939     $migrantseasonal = "",
940     $family_size = "",
941     $monthly_income = "",
942     $homeless = "",
943     $financial_review = "",
944     $pubpid = "",
945     $pid = "MAX(pid)+1",
946     $providerID = "",
947     $genericname1 = "",
948     $genericval1 = "",
949     $genericname2 = "",
950     $genericval2 = "",
951     $billing_note = "",
952     $phone_cell = "",
953     $hipaa_mail = "",
954     $hipaa_voice = "",
955     $squad = 0,
956     $pharmacy_id = 0,
957     $drivers_license = "",
958     $hipaa_notice = "",
959     $hipaa_message = "",
960     $regdate = ""
961 ) {
963     $DOB = fixDate($DOB);
964     $regdate = fixDate($regdate);
966     $fitness = 0;
967     $referral_source = '';
968     if ($pid) {
969         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
970         // Check for brain damage:
971         if ($db_id != $rez['id']) {
972             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
973               $rez['id'] . "' to '$db_id' for pid '$pid'";
974             die($errmsg);
975         }
977         $fitness = $rez['fitness'];
978         $referral_source = $rez['referral_source'];
979     }
981     // Get the default price level.
982     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
983       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
984     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
986     $query = ("replace into patient_data set
987         id='$db_id',
988         title='$title',
989         fname='$fname',
990         lname='$lname',
991         mname='$mname',
992         sex='$sex',
993         DOB='$DOB',
994         street='$street',
995         postal_code='$postal_code',
996         city='$city',
997         state='$state',
998         country_code='$country_code',
999         drivers_license='$drivers_license',
1000         ss='$ss',
1001         occupation='$occupation',
1002         phone_home='$phone_home',
1003         phone_biz='$phone_biz',
1004         phone_contact='$phone_contact',
1005         status='$status',
1006         contact_relationship='$contact_relationship',
1007         referrer='$referrer',
1008         referrerID='$referrerID',
1009         email='$email',
1010         language='$language',
1011         ethnoracial='$ethnoracial',
1012         interpretter='$interpretter',
1013         migrantseasonal='$migrantseasonal',
1014         family_size='$family_size',
1015         monthly_income='$monthly_income',
1016         homeless='$homeless',
1017         financial_review='$financial_review',
1018         pubpid='$pubpid',
1019         pid = $pid,
1020         providerID = '$providerID',
1021         genericname1 = '$genericname1',
1022         genericval1 = '$genericval1',
1023         genericname2 = '$genericname2',
1024         genericval2 = '$genericval2',
1025         billing_note= '$billing_note',
1026         phone_cell = '$phone_cell',
1027         pharmacy_id = '$pharmacy_id',
1028         hipaa_mail = '$hipaa_mail',
1029         hipaa_voice = '$hipaa_voice',
1030         hipaa_notice = '$hipaa_notice',
1031         hipaa_message = '$hipaa_message',
1032         squad = '$squad',
1033         fitness='$fitness',
1034         referral_source='$referral_source',
1035         regdate='$regdate',
1036         pricelevel='$pricelevel',
1037         date=NOW()");
1039     $id = sqlInsert($query);
1041     if (!$db_id) {
1042       // find the last inserted id for new patient case
1043         $db_id = getSqlLastID();
1044     }
1046     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1048     return $foo['pid'];
1051 // Supported input date formats are:
1052 //   mm/dd/yyyy
1053 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1054 //   yyyy/mm/dd
1055 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1057 function fixDate($date, $default = "0000-00-00")
1059     $fixed_date = $default;
1060     $date = trim($date);
1061     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1062         $dmy = preg_split("'[/.-]'", $date);
1063         if ($dmy[0] > 99) {
1064             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1065         } else {
1066             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1067                 if ($dmy[2] < 1000) {
1068                     $dmy[2] += 1900;
1069                 }
1071                 if ($dmy[2] < 1910) {
1072                     $dmy[2] += 100;
1073                 }
1074             }
1076             // phone_country_code indicates format of ambiguous input dates.
1077             if ($GLOBALS['phone_country_code'] == 1) {
1078                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1079             } else {
1080                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1081             }
1082         }
1083     }
1085     return $fixed_date;
1088 function pdValueOrNull($key, $value)
1090     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1091     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1092     (empty($value) || $value == '0000-00-00')) {
1093         return "NULL";
1094     } else {
1095         return "'" . add_escape_custom($value) . "'";
1096     }
1099 // Create or update patient data from an array.
1101 function updatePatientData($pid, $new, $create = false)
1103   /*******************************************************************
1104     $real = getPatientData($pid);
1105     $new['DOB'] = fixDate($new['DOB']);
1106     while(list($key, $value) = each ($new))
1107         $real[$key] = $value;
1108     $real['date'] = "'+NOW()+'";
1109     $real['id'] = "";
1110     $sql = "insert into patient_data set ";
1111     while(list($key, $value) = each($real))
1112         $sql .= $key." = '$value', ";
1113     $sql = substr($sql, 0, -2);
1114     return sqlInsert($sql);
1115   *******************************************************************/
1117   // The above was broken, though seems intent to insert a new patient_data
1118   // row for each update.  A good idea, but nothing is doing that yet so
1119   // the code below does not yet attempt it.
1121     $new['DOB'] = fixDate($new['DOB']);
1123     if ($create) {
1124         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1125         foreach ($new as $key => $value) {
1126             if ($key == 'id') {
1127                 continue;
1128             }
1130             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1131         }
1133         $db_id = sqlInsert($sql);
1134     } else {
1135         $db_id = $new['id'];
1136         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1137         // Check for brain damage:
1138         if ($pid != $rez['pid']) {
1139             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1140             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1141             die($errmsg);
1142         }
1144         $sql = "UPDATE patient_data SET date = NOW()";
1145         foreach ($new as $key => $value) {
1146             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1147         }
1149         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1150         sqlStatement($sql);
1151     }
1153     return $db_id;
1156 function newEmployerData(
1157     $pid,
1158     $name = "",
1159     $street = "",
1160     $postal_code = "",
1161     $city = "",
1162     $state = "",
1163     $country = ""
1164 ) {
1166     return sqlInsert("insert into employer_data set
1167         name='$name',
1168         street='$street',
1169         postal_code='$postal_code',
1170         city='$city',
1171         state='$state',
1172         country='$country',
1173         pid='$pid',
1174         date=NOW()
1175         ");
1178 // Create or update employer data from an array.
1180 function updateEmployerData($pid, $new, $create = false)
1182     $colnames = array('name','street','city','state','postal_code','country');
1184     if ($create) {
1185         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1186         foreach ($colnames as $key) {
1187             $value = isset($new[$key]) ? $new[$key] : '';
1188             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1189         }
1191         return sqlInsert("INSERT INTO employer_data SET $set");
1192     } else {
1193         $set = '';
1194         $old = getEmployerData($pid);
1195         $modified = false;
1196         foreach ($colnames as $key) {
1197             $value = empty($old[$key]) ? '' : $old[$key];
1198             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1199                 $value = $new[$key];
1200                 $modified = true;
1201             }
1203             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1204         }
1206         if ($modified) {
1207             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1208             return sqlInsert("INSERT INTO employer_data SET $set");
1209         }
1211         return $old['id'];
1212     }
1215 // This updates or adds the given insurance data info, while retaining any
1216 // previously added insurance_data rows that should be preserved.
1217 // This does not directly support the maintenance of non-current insurance.
1219 function newInsuranceData(
1220     $pid,
1221     $type = "",
1222     $provider = "",
1223     $policy_number = "",
1224     $group_number = "",
1225     $plan_name = "",
1226     $subscriber_lname = "",
1227     $subscriber_mname = "",
1228     $subscriber_fname = "",
1229     $subscriber_relationship = "",
1230     $subscriber_ss = "",
1231     $subscriber_DOB = "",
1232     $subscriber_street = "",
1233     $subscriber_postal_code = "",
1234     $subscriber_city = "",
1235     $subscriber_state = "",
1236     $subscriber_country = "",
1237     $subscriber_phone = "",
1238     $subscriber_employer = "",
1239     $subscriber_employer_street = "",
1240     $subscriber_employer_city = "",
1241     $subscriber_employer_postal_code = "",
1242     $subscriber_employer_state = "",
1243     $subscriber_employer_country = "",
1244     $copay = "",
1245     $subscriber_sex = "",
1246     $effective_date = "0000-00-00",
1247     $accept_assignment = "TRUE",
1248     $policy_type = ""
1249 ) {
1251     if (strlen($type) <= 0) {
1252         return false;
1253     }
1255   // If a bad date was passed, err on the side of caution.
1256     $effective_date = fixDate($effective_date, date('Y-m-d'));
1258     $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1259     "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1260     $idrow = sqlFetchArray($idres);
1262   // Replace the most recent entry in any of the following cases:
1263   // * Its effective date is >= this effective date.
1264   // * It is the first entry and it has no (insurance) provider.
1265   // * There is no encounter that is earlier than the new effective date but
1266   //   on or after the old effective date.
1267   // Otherwise insert a new entry.
1269     $replace = false;
1270     if ($idrow) {
1271         if (strcmp($idrow['date'], $effective_date) > 0) {
1272             $replace = true;
1273         } else {
1274             if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1275                 $replace = true;
1276             } else {
1277                 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1278                 "WHERE pid = ? AND date < ? AND " .
1279                 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1280                 if ($ferow['count'] == 0) {
1281                     $replace = true;
1282                 }
1283             }
1284         }
1285     }
1287     if ($replace) {
1288         // TBD: This is a bit dangerous in that a typo in entering the effective
1289         // date can wipe out previous insurance history.  So we want some data
1290         // entry validation somewhere.
1291         sqlStatement("DELETE FROM insurance_data WHERE " .
1292         "pid = ? AND type = ? AND date >= ? AND " .
1293         "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1295         $data = array();
1296         $data['type'] = $type;
1297         $data['provider'] = $provider;
1298         $data['policy_number'] = $policy_number;
1299         $data['group_number'] = $group_number;
1300         $data['plan_name'] = $plan_name;
1301         $data['subscriber_lname'] = $subscriber_lname;
1302         $data['subscriber_mname'] = $subscriber_mname;
1303         $data['subscriber_fname'] = $subscriber_fname;
1304         $data['subscriber_relationship'] = $subscriber_relationship;
1305         $data['subscriber_ss'] = $subscriber_ss;
1306         $data['subscriber_DOB'] = $subscriber_DOB;
1307         $data['subscriber_street'] = $subscriber_street;
1308         $data['subscriber_postal_code'] = $subscriber_postal_code;
1309         $data['subscriber_city'] = $subscriber_city;
1310         $data['subscriber_state'] = $subscriber_state;
1311         $data['subscriber_country'] = $subscriber_country;
1312         $data['subscriber_phone'] = $subscriber_phone;
1313         $data['subscriber_employer'] = $subscriber_employer;
1314         $data['subscriber_employer_city'] = $subscriber_employer_city;
1315         $data['subscriber_employer_street'] = $subscriber_employer_street;
1316         $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1317         $data['subscriber_employer_state'] = $subscriber_employer_state;
1318         $data['subscriber_employer_country'] = $subscriber_employer_country;
1319         $data['copay'] = $copay;
1320         $data['subscriber_sex'] = $subscriber_sex;
1321         $data['pid'] = $pid;
1322         $data['date'] = $effective_date;
1323         $data['accept_assignment'] = $accept_assignment;
1324         $data['policy_type'] = $policy_type;
1325         updateInsuranceData($idrow['id'], $data);
1326         return $idrow['id'];
1327     } else {
1328         return sqlInsert("INSERT INTO insurance_data SET
1329       type = '" . add_escape_custom($type) . "',
1330       provider = '" . add_escape_custom($provider) . "',
1331       policy_number = '" . add_escape_custom($policy_number) . "',
1332       group_number = '" . add_escape_custom($group_number) . "',
1333       plan_name = '" . add_escape_custom($plan_name) . "',
1334       subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1335       subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1336       subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1337       subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1338       subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1339       subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1340       subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1341       subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1342       subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1343       subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1344       subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1345       subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1346       subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1347       subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1348       subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1349       subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1350       subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1351       subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1352       copay = '" . add_escape_custom($copay) . "',
1353       subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1354       pid = '" . add_escape_custom($pid) . "',
1355       date = '" . add_escape_custom($effective_date) . "',
1356       accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1357       policy_type = '" . add_escape_custom($policy_type) . "'
1358     ");
1359     }
1362 // This is used internally only.
1363 function updateInsuranceData($id, $new)
1365     $fields = sqlListFields("insurance_data");
1366     $use = array();
1368     while (list($key, $value) = each($new)) {
1369         if (in_array($key, $fields)) {
1370             $use[$key] = $value;
1371         }
1372     }
1374     $sql = "UPDATE insurance_data SET ";
1375     while (list($key, $value) = each($use)) {
1376         $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1377     }
1379     $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1381     sqlStatement($sql);
1384 function newHistoryData($pid, $new = false)
1386     $arraySqlBind = array();
1387     $sql = "insert into history_data set pid = ?, date = NOW()";
1388     array_push($arraySqlBind, $pid);
1389     if ($new) {
1390         while (list($key, $value) = each($new)) {
1391             array_push($arraySqlBind, $value);
1392             $sql .= ", `$key` = ?";
1393         }
1394     }
1396     return sqlInsert($sql, $arraySqlBind);
1399 function updateHistoryData($pid, $new)
1401         $real = getHistoryData($pid);
1402     while (list($key, $value) = each($new)) {
1403         $real[$key] = $value;
1404     }
1406         $real['id'] = "";
1407     // need to unset date, so can reset it below
1408     unset($real['date']);
1410         $arraySqlBind = array();
1411         $sql = "insert into history_data set `date` = NOW(), ";
1412     while (list($key, $value) = each($real)) {
1413         array_push($arraySqlBind, $value);
1414         $sql .= "`$key` = ?, ";
1415     }
1417         $sql = substr($sql, 0, -2);
1419         return sqlInsert($sql, $arraySqlBind);
1422 // Returns Age
1423 //   in months if < 2 years old
1424 //   in years  if > 2 years old
1425 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1426 // (optional) nowYMD is a date in YYYYMMDD format
1427 function getPatientAge($dobYMD, $nowYMD = null)
1429     // strip any dashes from the DOB
1430     $dobYMD = preg_replace("/-/", "", $dobYMD);
1431     $dobDay = substr($dobYMD, 6, 2);
1432     $dobMonth = substr($dobYMD, 4, 2);
1433     $dobYear = substr($dobYMD, 0, 4);
1435     // set the 'now' date values
1436     if ($nowYMD == null) {
1437         $nowDay = date("d");
1438         $nowMonth = date("m");
1439         $nowYear = date("Y");
1440     } else {
1441         $nowDay = substr($nowYMD, 6, 2);
1442         $nowMonth = substr($nowYMD, 4, 2);
1443         $nowYear = substr($nowYMD, 0, 4);
1444     }
1446     $dayDiff = $nowDay - $dobDay;
1447     $monthDiff = $nowMonth - $dobMonth;
1448     $yearDiff = $nowYear - $dobYear;
1450     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1452     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1453     if ($dayDiff<0) {
1454         $ageInMonths-=1;
1455     }
1457     if ($ageInMonths > 24) {
1458         $age = $yearDiff;
1459         if (($monthDiff == 0) && ($dayDiff < 0)) {
1460             $age -= 1;
1461         } else if ($monthDiff < 0) {
1462             $age -= 1;
1463         }
1464     } else {
1465         $age = "$ageInMonths " . xl('month');
1466     }
1468     return $age;
1472  * Wrapper to make sure the clinical rules dates formats corresponds to the
1473  * format expected by getPatientAgeYMD
1475  * @param  string  $dob     date of birth
1476  * @param  string  $target  date to calculate age on
1477  * @return array containing
1478  *      age - decimal age in years
1479  *      age_in_months - decimal age in months
1480  *      ageinYMD - formatted string #y #m #d */
1481 function parseAgeInfo($dob, $target)
1483     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1484     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1485     ;
1486     // Prepare target (Y-M-D H:M:S)
1487     $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1489     return getPatientAgeYMD($dateDOB, $dateTarget);
1494  * @param type $dob
1495  * @param type $date
1496  * @return array containing
1497  *      age - decimal age in years
1498  *      age_in_months - decimal age in months
1499  *      ageinYMD - formatted string #y #m #d
1500  */
1501 function getPatientAgeYMD($dob, $date = null)
1504     if ($date == null) {
1505         $daynow = date("d");
1506         $monthnow = date("m");
1507         $yearnow = date("Y");
1508         $datenow=$yearnow.$monthnow.$daynow;
1509     } else {
1510         $datenow=preg_replace("/-/", "", $date);
1511         $yearnow=substr($datenow, 0, 4);
1512         $monthnow=substr($datenow, 4, 2);
1513         $daynow=substr($datenow, 6, 2);
1514         $datenow=$yearnow.$monthnow.$daynow;
1515     }
1517     $dob=preg_replace("/-/", "", $dob);
1518     $dobyear=substr($dob, 0, 4);
1519     $dobmonth=substr($dob, 4, 2);
1520     $dobday=substr($dob, 6, 2);
1521     $dob=$dobyear.$dobmonth.$dobday;
1523     //to compensate for 30, 31, 28, 29 days/month
1524     $mo=$monthnow; //to avoid confusion with later calculation
1526     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1
1527         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1528     } // look at April, June, September, November for calculation.  These months only have 30 days.
1529     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1530         $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1531         if (is_int($check_leap_Y)) {
1532             $nd=29;
1533         } //If it true then this is the leap year
1534         else {
1535             $nd=28;
1536         } //otherwise, it is not a leap year.
1537     } else {
1538         $nd=31;
1539     } // other months have 31 days
1541     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1542     if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1543         $age_year = $yearnow - $dobyear - 1;
1544         if ($daynow < $dobday) {
1545             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1546             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1547         } else {
1548             $months_since_birthday=12 - $dobmonth + $monthnow;
1549             $days_since_dobday=$daynow - $dobday;
1550         }
1551     } else // if patient has had birthday this calandar year
1552     {
1553         $age_year = $yearnow - $dobyear;
1554         if ($daynow < $dobday) {
1555             $months_since_birthday=$monthnow - $dobmonth -1;
1556             $days_since_dobday=$nd - $dobday + $daynow;
1557         } else {
1558             $months_since_birthday=$monthnow - $dobmonth;
1559             $days_since_dobday=$daynow - $dobday;
1560         }
1561     }
1563     $day_as_month_decimal = $days_since_dobday / 30;
1564     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1565     $month_as_year_decimal = $months_since_birthday_float / 12;
1566     $age_float = $age_year + $month_as_year_decimal;
1568     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1569     $age_in_months = round($age_in_months, 2);  //round the months to xx.xx 2 floating points
1570     $age = round($age_float, 2);
1572     // round the years to 2 floating points
1573     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1574     return compact('age', 'age_in_months', 'ageinYMD');
1577 // Returns Age in days
1578 //   in months if < 2 years old
1579 //   in years  if > 2 years old
1580 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1581 // (optional) nowYMD is a date in YYYYMMDD format
1582 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1584     $age = -1;
1586     // strip any dashes from the DOB
1587     $dobYMD = preg_replace("/-/", "", $dobYMD);
1588     $dobDay = substr($dobYMD, 6, 2);
1589     $dobMonth = substr($dobYMD, 4, 2);
1590     $dobYear = substr($dobYMD, 0, 4);
1592     // set the 'now' date values
1593     if ($nowYMD == null) {
1594         $nowDay = date("d");
1595         $nowMonth = date("m");
1596         $nowYear = date("Y");
1597     } else {
1598         $nowDay = substr($nowYMD, 6, 2);
1599         $nowMonth = substr($nowYMD, 4, 2);
1600         $nowYear = substr($nowYMD, 0, 4);
1601     }
1603     // do the date math
1604     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1605     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1606     $timediff = $nowtime - $dobtime;
1607     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1609     return $age;
1612  * Returns a string to be used to display a patient's age
1614  * @param type $dobYMD
1615  * @param type $asOfYMD
1616  * @return string suitable for displaying patient's age based on preferences
1617  */
1618 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1620     if ($GLOBALS['age_display_format']=='1') {
1621         $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1622         if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1623             return $ageYMD['ageinYMD'];
1624         } else {
1625             return getPatientAge($dobYMD, $asOfYMD);
1626         }
1627     } else {
1628         return getPatientAge($dobYMD, $asOfYMD);
1629     }
1631 function dateToDB($date)
1633     $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1634     return $date;
1638 // ----------------------------------------------------------------------------
1640  * DROPDOWN FOR COUNTRIES
1642  * build a dropdown with all countries from geo_country_reference
1644  * @param int $selected - id for selected record
1645  * @param string $name - the name/id for select form
1646  * @return void - just echo the html encoded string
1647  */
1648 function dropdown_countries($selected = 0, $name = 'country_code')
1650     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1652     $string = "<select name='$name' id='$name'>";
1653     while ($row = sqlFetchArray($r)) {
1654         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1655         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1656     }
1658     $string .= '</select>';
1659     echo $string;
1663 // ----------------------------------------------------------------------------
1665  * DROPDOWN FOR YES/NO
1667  * build a dropdown with two options (yes - 1, no - 0)
1669  * @param int $selected - id for selected record
1670  * @param string $name - the name/id for select form
1671  * @return void - just echo the html encoded string
1672  */
1673 function dropdown_yesno($selected = 0, $name = 'yesno')
1675     $string = "<select name='$name' id='$name'>";
1677     $selected = (int)$selected;
1678     if ($selected == 0) {
1679         $sel1 = 'selected="selected"';
1680         $sel2 = '';
1681     } else {
1682         $sel2 = 'selected="selected"';
1683         $sel1 = '';
1684     }
1686         $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1687         $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1688         $string .= '</select>';
1690         echo $string;
1693 // ----------------------------------------------------------------------------
1695  * DROPDOWN FOR MALE/FEMALE options
1697  * build a dropdown with three options (unselected/male/female)
1699  * @param int $selected - id for selected record
1700  * @param string $name - the name/id for select form
1701  * @return void - just echo the html encoded string
1702  */
1703 function dropdown_sex($selected = 0, $name = 'sex')
1705     $string = "<select name='$name' id='$name'>";
1707     if ($selected == 1) {
1708         $sel1 = 'selected="selected"';
1709         $sel2 = '';
1710         $sel0 = '';
1711     } else if ($selected == 2) {
1712         $sel2 = 'selected="selected"';
1713         $sel1 = '';
1714         $sel0 = '';
1715     } else {
1716             $sel0 = 'selected="selected"';
1717             $sel1 = '';
1718             $sel2 = '';
1719     }
1721         $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1722         $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1723         $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1724         $string .= '</select>';
1726         echo $string;
1729 // ----------------------------------------------------------------------------
1731  * DROPDOWN FOR MARITAL STATUS
1733  * build a dropdown with marital status
1735  * @param int $selected - id for selected record
1736  * @param string $name - the name/id for select form
1737  * @return void - just echo the html encoded string
1738  */
1739 function dropdown_marital($selected = 0, $name = 'status')
1741     $string = "<select name='$name' id='$name'>";
1743     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1745     foreach ($statii as $st) {
1746         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1747         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1748     }
1750     $string .= '</select>';
1752     echo $string;
1755 // ----------------------------------------------------------------------------
1757  * DROPDOWN FOR PROVIDERS
1759  * build a dropdown with all providers
1761  * @param int $selected - id for selected record
1762  * @param string $name - the name/id for select form
1763  * @return void - just echo the html encoded string
1764  */
1765 function dropdown_providers($selected = 0, $name = 'status')
1767     $provideri = getProviderInfo();
1769     $string = "<select name='$name' id='$name'>";
1770     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1771     foreach ($provideri as $s) {
1772         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1773         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1774     }
1776     $string .= '</select>';
1778     echo $string;
1781 // ----------------------------------------------------------------------------
1783  * DROPDOWN FOR INSURANCE COMPANIES
1785  * build a dropdown with all insurers
1787  * @param int $selected - id for selected record
1788  * @param string $name - the name/id for select form
1789  * @return void - just echo the html encoded string
1790  */
1791 function dropdown_insurance($selected = 0, $name = 'iprovider')
1793     $insurancei = getInsuranceProviders();
1795     $string = "<select name='$name' id='$name'>";
1796     $string .= '<option value="0">Onbekend</option>';
1797     foreach ($insurancei as $iid => $iname) {
1798         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1799         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1800     }
1802     $string .= '</select>';
1804     echo $string;
1808 // ----------------------------------------------------------------------------
1810  * COUNTRY CODE
1812  * return the name or the country code, function of arguments
1814  * @param int $country_code
1815  * @param string $country_name
1816  * @return string | int - name or code
1817  */
1818 function country_code($country_code = 0, $country_name = '')
1820     $strint = '';
1821     if ($country_code) {
1822         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1823     } else {
1824         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1825     }
1827     $db = $GLOBALS['adodb']['db'];
1828     $result = $db->Execute($sql);
1829     if ($result && !$result->EOF) {
1830         $strint = $result->fields['res'];
1831     }
1833     return $strint;
1836 function DBToDate($date)
1838     $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1839     return $date;
1843  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1844  * for the given patient on the given date.
1846  * @param int     The PID of the patient.
1847  * @param string  Date in yyyy-mm-dd format.
1848  * @return array  Array of 0-3 insurance_data rows.
1849  */
1850 function getEffectiveInsurances($patient_id, $encdate)
1852     $insarr = array();
1853     foreach (array('primary','secondary','tertiary') as $instype) {
1854         $tmp = sqlQuery(
1855             "SELECT * FROM insurance_data " .
1856             "WHERE pid = ? AND type = ? " .
1857             "AND date <= ? ORDER BY date DESC LIMIT 1",
1858             array($patient_id, $instype, $encdate)
1859         );
1860         if (empty($tmp['provider'])) {
1861             break;
1862         }
1864         $insarr[] = $tmp;
1865     }
1867     return $insarr;
1871  * Get the patient's balance due. Normally this excludes amounts that are out
1872  * to insurance.  If you want to include what insurance owes, set the second
1873  * parameter to true.
1875  * @param int     The PID of the patient.
1876  * @param boolean Indicates if amounts owed by insurance are to be included.
1877  * @return number The balance.
1878  */
1879 function get_patient_balance($pid, $with_insurance = false)
1881     $balance = 0;
1882     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1883       "last_level_closed, stmt_count " .
1884       "FROM form_encounter WHERE pid = ?", array($pid));
1885     while ($ferow = sqlFetchArray($feres)) {
1886         $encounter = $ferow['encounter'];
1887         $dos = substr($ferow['date'], 0, 10);
1888         $insarr = getEffectiveInsurances($pid, $dos);
1889         $inscount = count($insarr);
1890         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1891             // It's out to insurance so only the co-pay might be due.
1892             $brow = sqlQuery(
1893                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1894                 "pid = ? AND encounter = ? AND " .
1895                 "code_type = 'copay' AND activity = 1",
1896                 array($pid, $encounter)
1897             );
1898             $drow = sqlQuery(
1899                 "SELECT SUM(pay_amount) AS payments " .
1900                 "FROM ar_activity WHERE " .
1901                 "pid = ? AND encounter = ? AND payer_type = 0",
1902                 array($pid, $encounter)
1903             );
1904             $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1905             if ($ptbal > 0) {
1906                 $balance += $ptbal;
1907             }
1908         } else {
1909             // Including insurance or not out to insurance, everything is due.
1910             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1911             "pid = ? AND encounter = ? AND " .
1912             "activity = 1", array($pid, $encounter));
1913             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1914               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1915               "pid = ? AND encounter = ?", array($pid, $encounter));
1916             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1917               "pid = ? AND encounter = ?", array($pid, $encounter));
1918             $balance += $brow['amount'] + $srow['amount']
1919               - $drow['payments'] - $drow['adjustments'];
1920         }
1921     }
1923     return sprintf('%01.2f', $balance);
1926 // Function to check if patient is deceased.
1927 //  Param:
1928 //    $pid  - patient id
1929 //    $date - date checking if deceased (will default to current date if blank)
1930 //  Return:
1931 //    If deceased, then will return the number of
1932 //      days that patient has been deceased.
1933 //    If not deceased, then will return false.
1934 function is_patient_deceased($pid, $date = '')
1937   // Set date to current if not set
1938     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1940   // Query for deceased status (gets days deceased if patient is deceased)
1941     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1942                       "FROM `patient_data` " .
1943                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1945     if (empty($results)) {
1946         // Patient is alive, so return false
1947         return false;
1948     } else {
1949         // Patient is dead, so return the number of days patient has been deceased.
1950         //  Don't let it be zero days or else will confuse calls to this function.
1951         if ($results['days_deceased'] === 0) {
1952             $results['days_deceased'] = 1;
1953         }
1955         return $results['days_deceased'];
1956     }