Highway to PSR2
[openemr.git] / library / patient.inc
blobacade658ecb7a6a3228faee47f6224cb92ab5d4e
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 $facilityService = new \services\FacilityService();
13 // These are for sports team use:
14 $PLAYER_FITNESSES = array(
15   xl('Full Play'),
16   xl('Full Training'),
17   xl('Restricted Training'),
18   xl('Injured Out'),
19   xl('Rehabilitation'),
20   xl('Illness'),
21   xl('International Duty')
23 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
25 // Hard-coding this array because its values and meanings are fixed by the 837p
26 // standard and we don't want people messing with them.
27 $policy_types = array(
28   ''   => xl('N/A'),
29   '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
30   '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
31   '14' => xl('No-fault Insurance including Auto is Primary'),
32   '15' => xl('Worker`s Compensation'),
33   '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
34   '41' => xl('Black Lung'),
35   '42' => xl('Veteran`s Administration'),
36   '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
37   '47' => xl('Other Liability Insurance is Primary'),
40 /**
41  * Get a patient's demographic data.
42  *
43  * @param int    $pid   The PID of the patient
44  * @param string $given an optional subsection of the patient's demographic
45  *                      data to retrieve.
46  * @return array The requested subsection of a patient's demographic data.
47  *               If no subsection was given, returns everything, with the
48  *               date of birth as the last field.
49  */
50 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
52     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
53     return sqlQuery($sql, array($pid));
56 function getLanguages()
58     $returnval = array('','english');
59     $sql = "select distinct lower(language) as language from patient_data";
60     $rez = sqlStatement($sql);
61     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
62         if (($row["language"] != "english") && ($row["language"] != "")) {
63             array_push($returnval, $row["language"]);
64         }
65     }
67     return $returnval;
70 function getInsuranceProvider($ins_id)
73     $sql = "select name from insurance_companies where id=?";
74     $row = sqlQuery($sql, array($ins_id));
75     return $row['name'];
78 function getInsuranceProviders()
80     $returnval = array();
82     if (true) {
83         $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
84         $rez = sqlStatement($sql);
85         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
86             $returnval[$row['id']] = $row['name'];
87         }
88     } // Please leave this here. I have a user who wants to see zip codes and PO
89     // box numbers listed along with the insurance company names, as many companies
90     // have different billing addresses for different plans.  -- Rod Roark
91     //
92     else {
93         $sql = "select insurance_companies.name, insurance_companies.id, " .
94           "addresses.zip, addresses.line1 " .
95           "from insurance_companies, addresses " .
96           "where addresses.foreign_id = insurance_companies.id " .
97           "order by insurance_companies.name, addresses.zip";
99         $rez = sqlStatement($sql);
101         for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
102             preg_match("/\d+/", $row['line1'], $matches);
103             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
104               "," . $matches[0] . ")";
105         }
106     }
108     return $returnval;
111 function getInsuranceProvidersExtra()
113     $returnval = array();
114     // add a global and if for where to allow inactive inscompanies
116     $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
117             addresses.state, addresses.zip
118             FROM insurance_companies, addresses
119             WHERE addresses.foreign_id = insurance_companies.id
120             AND insurance_companies.inactive != 1
121             ORDER BY insurance_companies.name, addresses.zip";
123     $rez = sqlStatement($sql);
125     for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
126         switch ($GLOBALS['insurance_information']) {
127             case $GLOBALS['insurance_information'] = '0':
128                 $returnval[$row['id']] = $row['name'];
129                 break;
130             case $GLOBALS['insurance_information'] = '1':
131                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
132                 break;
133             case $GLOBALS['insurance_information'] = '2':
134                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
135                 break;
136             case $GLOBALS['insurance_information'] = '3':
137                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
138                 break;
139             case $GLOBALS['insurance_information'] = '4':
140                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
141                     ", " . $row['zip'] . ")";
142                 break;
143             case $GLOBALS['insurance_information'] = '5':
144                 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
145                     ", " . $row['state'] . ", " . $row['zip'] . ")";
146                 break;
147             case $GLOBALS['insurance_information'] = '6':
148                 preg_match("/\d+/", $row['line1'], $matches);
149                 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
150                     "," . $matches[0] . ")";
151                 break;
152         }
153     }
155     return $returnval;
158 function getProviders()
160     $returnval = array("");
161     $sql = "select fname, lname, suffix from users where authorized = 1 and " .
162         "active = 1 and username != ''";
163     $rez = sqlStatement($sql);
164     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
165         if (($row["fname"] != "") && ($row["lname"] != "")) {
166             if ($row["suffix"] != "") {
167                 $row["lname"] .= ", ".$row["suffix"];
168             }
170             array_push($returnval, $row["fname"] . " " . $row["lname"]);
171         }
172     }
174     return $returnval;
177 // ----------------------------------------------------------------------------
178 // Get one facility row.  If the ID is not specified, then get either the
179 // "main" (billing) facility, or the default facility of the currently
180 // logged-in user.  This was created to support genFacilityTitle() but
181 // may find additional uses.
183 function getFacility($facid = 0)
185     global $facilityService;
187     $facility = null;
189     if ($facid > 0) {
190         $facility = $facilityService->getById($facid);
191     } else if ($facid == 0) {
192         $facility = $facilityService->getPrimaryBillingLocation();
193     } else {
194         $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
195     }
197     return $facility;
200 // Generate a report title including report name and facility name, address
201 // and phone.
203 function genFacilityTitle($repname = '', $facid = 0)
205     $s = '';
206     $s .= "<table class='ftitletable'>\n";
207     $s .= " <tr>\n";
208     $s .= "  <td class='ftitlecell1'>$repname</td>\n";
209     $s .= "  <td class='ftitlecell2'>\n";
210     $r = getFacility($facid);
211     if (!empty($r)) {
212         $s .= "<b>" . htmlspecialchars($r['name'], ENT_NOQUOTES) . "</b>\n";
213         if ($r['street']) {
214             $s .= "<br />" . htmlspecialchars($r['street'], ENT_NOQUOTES) . "\n";
215         }
217         if ($r['city'] || $r['state'] || $r['postal_code']) {
218             $s .= "<br />";
219             if ($r['city']) {
220                 $s .= htmlspecialchars($r['city'], ENT_NOQUOTES);
221             }
223             if ($r['state']) {
224                 if ($r['city']) {
225                     $s .= ", \n";
226                 }
228                 $s .= htmlspecialchars($r['state'], ENT_NOQUOTES);
229             }
231             if ($r['postal_code']) {
232                 $s .= " " . htmlspecialchars($r['postal_code'], ENT_NOQUOTES);
233             }
235             $s .= "\n";
236         }
238         if ($r['country_code']) {
239             $s .= "<br />" . htmlspecialchars($r['country_code'], ENT_NOQUOTES) . "\n";
240         }
242         if (preg_match('/[1-9]/', $r['phone'])) {
243             $s .= "<br />" . htmlspecialchars($r['phone'], ENT_NOQUOTES) . "\n";
244         }
245     }
247     $s .= "  </td>\n";
248     $s .= " </tr>\n";
249     $s .= "</table>\n";
250     return $s;
254 GET FACILITIES
256 returns all facilities or just the id for the first one
257 (FACILITY FILTERING (lemonsoftware))
259 @param string - if 'first' return first facility ordered by id
260 @return array | int for 'first' case
262 function getFacilities($first = '')
264     global $facilityService;
266     $fres = $facilityService->getAll();
268     if ($first == 'first') {
269         return $fres[0]['id'];
270     } else {
271         return $fres;
272     }
276 GET SERVICE FACILITIES
278 returns all service_location facilities or just the id for the first one
279 (FACILITY FILTERING (CHEMED))
281 @param string - if 'first' return first facility ordered by id
282 @return array | int for 'first' case
284 function getServiceFacilities($first = '')
286     global $facilityService;
288     $fres = $facilityService->getAllServiceLocations();
290     if ($first == 'first') {
291         return $fres[0]['id'];
292     } else {
293         return $fres;
294     }
297 //(CHEMED) facility filter
298 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '')
300     $param1 = "";
301     if ($providers_only === 'any') {
302         $param1 = " AND authorized = 1 AND active = 1 ";
303     } else if ($providers_only) {
304         $param1 = " AND authorized = 1 AND calendar = 1 ";
305     }
307     //--------------------------------
308     //(CHEMED) facility filter
309     $param2 = "";
310     if ($facility) {
311         if ($GLOBALS['restrict_user_facility']) {
312             $param2 = " AND (facility_id = $facility
313           OR  $facility IN
314                 (select facility_id
315                 from users_facility
316                 where tablename = 'users'
317                 and table_id = id)
318                 )
319           ";
320         } else {
321             $param2 = " AND facility_id = $facility ";
322         }
323     }
325     //--------------------------------
327     $command = "=";
328     if ($providerID == "%") {
329         $command = "like";
330     }
332     $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
333         "from users where username != '' and active = 1 and id $command '" .
334         add_escape_custom($providerID) . "' " . $param1 . $param2;
335     // sort by last name -- JRM June 2008
336     $query .= " ORDER BY lname, fname ";
337     $rez = sqlStatement($query);
338     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
339         $returnval[$iter]=$row;
340     }
342     //if only one result returned take the key/value pairs in array [0] and merge them down into
343     // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
345     if ($iter==1) {
346         $akeys = array_keys($returnval[0]);
347         foreach ($akeys as $key) {
348             $returnval[0][$key] = $returnval[0][$key];
349         }
350     }
352     return $returnval;
355 //same as above but does not reduce if only 1 row returned
356 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
358     $param1 = "";
359     if ($providers_only) {
360         $param1 = "AND authorized=1";
361     }
363     $command = "=";
364     if ($providerID == "%") {
365         $command = "like";
366     }
368     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
369         "from users where active = 1 and username != '' and id $command '" .
370         add_escape_custom($providerID) . "' " . $param1;
372     $rez = sqlStatement($query);
373     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
374         $returnval[$iter]=$row;
375     }
377     return $returnval;
380 function getProviderName($providerID)
382     $pi = getProviderInfo($providerID, 'any');
383     if (strlen($pi[0]["lname"]) > 0) {
384         if (strlen($pi[0]["suffix"]) > 0) {
385             $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
386         }
388         return $pi[0]['fname'] . " " . $pi[0]['lname'];
389     }
391     return "";
394 function getProviderId($providerName)
396     $query = "select id from users where username = ?";
397     $rez = sqlStatement($query, array($providerName));
398     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
399         $returnval[$iter]=$row;
400     }
402     return $returnval;
405 function getEthnoRacials()
407     $returnval = array("");
408     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
409     $rez = sqlStatement($sql);
410     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
411         if (($row["ethnoracial"] != "")) {
412             array_push($returnval, $row["ethnoracial"]);
413         }
414     }
416     return $returnval;
419 function getHistoryData($pid, $given = "*", $dateStart = '', $dateEnd = '')
422     if ($dateStart && $dateEnd) {
423         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
424     } else if ($dateStart && !$dateEnd) {
425         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart));
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,$dateEnd));
428     } else {
429         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid));
430     }
432     if ($given == 'tobacco') {
433         $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));
434     }
436     return $res;
439 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
440 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
442     $sql = "select $given from insurance_data as insd " .
443     "left join insurance_companies as ic on ic.id = insd.provider " .
444     "where pid = ? and type = ? order by date DESC limit 1";
445     return sqlQuery($sql, array($pid, $type));
448 function getInsuranceDataByDate(
449     $pid,
450     $date,
451     $type,
452     $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
453 ) {
454  // this must take the date in the following manner: YYYY-MM-DD
455   // this function recalls the insurance value that was most recently enterred from the
456   // given date. it will call up most recent records up to and on the date given,
457   // but not records enterred after the given date
458     $sql = "select $given from insurance_data as insd " .
459     "left join insurance_companies as ic on ic.id = provider " .
460     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
461     "type=? order by date DESC limit 1";
462     return sqlQuery($sql, array($pid,$date,$type));
465 function getEmployerData($pid, $given = "*")
467     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
468     return sqlQuery($sql, array($pid));
471 function _set_patient_inc_count($limit, $count, $where, $whereBindArray = array())
473   // When the limit is exceeded, find out what the unlimited count would be.
474     $GLOBALS['PATIENT_INC_COUNT'] = $count;
475   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
476     if ($limit != "all") {
477         $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
478         $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
479     }
483  * Allow the last name to be followed by a comma and some part of a first name(can
484  *   also place middle name after the first name with a space separating them)
485  * Allows comma alone followed by some part of a first name(can also place middle name
486  *   after the first name with a space separating them).
487  * Allows comma alone preceded by some part of a last name.
488  * If no comma or space, then will search both last name and first name.
489  * If the first letter of either name is capital, searches for name starting
490  *   with given substring (the expected behavior). If it is lower case, it
491  *   searches for the substring anywhere in the name. This applies to either
492  *   last name, first name, and middle name.
493  * Also allows first name followed by middle and/or last name when separated by spaces.
494  * @param string $term
495  * @param string $given
496  * @param string $orderby
497  * @param string $limit
498  * @param string $start
499  * @return array
500  */
501 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")
503     $names = getPatientNameSplit($term);
505     foreach ($names as $key => $val) {
506         if (!empty($val)) {
507             if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
508                 $names[$key] = '%' . $val . '%';
509             } else {
510                 $names[$key] = $val . '%';
511             }
512         }
513     }
515     // Debugging section below
516     //if(array_key_exists('first',$names)) {
517     //    error_log("first name search term :".$names['first']);
518     //}
519     //if(array_key_exists('middle',$names)) {
520     //    error_log("middle name search term :".$names['middle']);
521     //}
522     //if(array_key_exists('last',$names)) {
523     //    error_log("last name search term :".$names['last']);
524     //}
525     // Debugging section above
527     $sqlBindArray = array();
528     if (array_key_exists('last', $names) && $names['last'] == '') {
529         // Do not search last name
530         $where = "fname LIKE ? ";
531         array_push($sqlBindArray, $names['first']);
532         if ($names['middle'] != '') {
533             $where .= "AND mname LIKE ? ";
534             array_push($sqlBindArray, $names['middle']);
535         }
536     } elseif (array_key_exists('first', $names) && $names['first'] == '') {
537         // Do not search first name or middle name
538         $where = "lname LIKE ? ";
539         array_push($sqlBindArray, $names['last']);
540     } elseif ($names['first'] == '' && $names['last'] != '') {
541         // Search both first name and last name with same term
542         $names['first'] = $names['last'];
543         $where = "lname LIKE ? OR fname LIKE ? ";
544         array_push($sqlBindArray, $names['last'], $names['first']);
545     } elseif ($names['middle'] != '') {
546         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
547         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
548     } else {
549         $where = "lname LIKE ? AND fname LIKE ? ";
550         array_push($sqlBindArray, $names['last'], $names['first']);
551     }
553     if (!empty($GLOBALS['pt_restrict_field'])) {
554         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
555             $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
556                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
557                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
558             array_push($sqlBindArray, $_SESSION{"authUser"});
559         }
560     }
562     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
563     if ($limit != "all") {
564         $sql .= " LIMIT $start, $limit";
565     }
567     $rez = sqlStatement($sql, $sqlBindArray);
569     $returnval=array();
570     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
571         $returnval[$iter] = $row;
572     }
574     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
575     return $returnval;
578  * Accept a string used by a search function expected to find a patient name,
579  * then split up the string if a comma or space exists. Return an array having
580  * from 1 to 3 elements, named first, middle, and last.
581  * See above getPatientLnames() function for details on how the splitting occurs.
582  * @param string $term
583  * @return array
584  */
585 function getPatientNameSplit($term)
587     $term = trim($term);
588     if (strpos($term, ',') !== false) {
589         $names = explode(',', $term);
590         $n['last'] = $names[0];
591         if (strpos(trim($names[1]), ' ') !== false) {
592             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
593         } else {
594             $n['first'] = $names[1];
595         }
596     } elseif (strpos($term, ' ') !== false) {
597         $names = explode(' ', $term);
598         if (count($names) == 1) {
599             $n['last'] = $names[0];
600         } elseif (count($names) == 3) {
601             $n['first'] = $names[0];
602             $n['middle'] = $names[1];
603             $n['last'] = $names[2];
604         } else {
605             // This will handle first and last name or first followed by
606             // multiple names only using just the last of the names in the list.
607             $n['first'] = $names[0];
608             $n['last'] = end($names);
609         }
610     } else {
611         $n['last'] = $term;
612         if (empty($n['last'])) {
613             $n['last'] = '%';
614         }
615     }
617     // Trim whitespace off the names before returning
618     foreach ($n as $key => $val) {
619         $n[$key] = trim($val);
620     }
622     return $n; // associative array containing names
625 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")
628     $sqlBindArray = array();
629     $where = "pubpid LIKE ? ";
630     array_push($sqlBindArray, $pid."%");
631     if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id']) {
632         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
633             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
634                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
635                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
636             array_push($sqlBindArray, $_SESSION{"authUser"});
637         }
638     }
640     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
641     if ($limit != "all") {
642         $sql .= " limit $start, $limit";
643     }
645     $rez = sqlStatement($sql, $sqlBindArray);
646     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
647         $returnval[$iter]=$row;
648     }
650     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
651     return $returnval;
654 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")
656     $layoutCols = sqlStatement("SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%"));
658     $sqlBindArray = array();
659     $where = "";
660     for ($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
661         if ($iter > 0) {
662             $where .= " or ";
663         }
665         $where .= " ".add_escape_custom($row["field_id"])." like ? ";
666         array_push($sqlBindArray, "%".$searchTerm."%");
667     }
669     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
670     if ($limit != "all") {
671         $sql .= " limit $start, $limit";
672     }
674     $rez = sqlStatement($sql, $sqlBindArray);
675     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
676         $returnval[$iter]=$row;
677     }
679     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
680     return $returnval;
683 function getByPatientDemographicsFilter(
684     $searchFields,
685     $searchTerm = "%",
686     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
687     $orderby = "lname ASC, fname ASC",
688     $limit = "all",
689     $start = "0",
690     $search_service_code = ''
691 ) {
693     $layoutCols = explode('~', $searchFields);
694     $sqlBindArray = array();
695     $where = "";
696     $i = 0;
697     foreach ($layoutCols as $val) {
698         if (empty($val)) {
699             continue;
700         }
702         if ($i > 0) {
703             $where .= " or ";
704         }
706         if ($val == 'pid') {
707             $where .= " ".add_escape_custom($val)." = ? ";
708                 array_push($sqlBindArray, $searchTerm);
709         } else {
710             $where .= " ".add_escape_custom($val)." like ? ";
711                 array_push($sqlBindArray, $searchTerm."%");
712         }
714         $i++;
715     }
717   // If no search terms, ensure valid syntax.
718     if ($i == 0) {
719         $where = "1 = 1";
720     }
722   // If a non-empty service code was given, then restrict to patients who
723   // have been provided that service.  Since the code is used in a LIKE
724   // clause, % and _ wildcards are supported.
725     if ($search_service_code) {
726         $where = "( $where ) AND " .
727         "( SELECT COUNT(*) FROM billing AS b WHERE " .
728         "b.pid = patient_data.pid AND " .
729         "b.activity = 1 AND " .
730         "b.code_type != 'COPAY' AND " .
731         "b.code LIKE ? " .
732         ") > 0";
733         array_push($sqlBindArray, $search_service_code);
734     }
736     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
737     if ($limit != "all") {
738         $sql .= " limit $start, $limit";
739     }
741     $rez = sqlStatement($sql, $sqlBindArray);
742     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
743         $returnval[$iter]=$row;
744     }
746     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
747     return $returnval;
750 // return a collection of Patient PIDs
751 // new arg style by JRM March 2008
752 // 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")
753 function getPatientPID($args)
755     $pid = "%";
756     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
757     $orderby = "lname ASC, fname ASC";
758     $limit="all";
759     $start="0";
761     // alter default values if defined in the passed in args
762     if (isset($args['pid'])) {
763         $pid = $args['pid'];
764     }
766     if (isset($args['given'])) {
767         $given = $args['given'];
768     }
770     if (isset($args['orderby'])) {
771         $orderby = $args['orderby'];
772     }
774     if (isset($args['limit'])) {
775         $limit = $args['limit'];
776     }
778     if (isset($args['start'])) {
779         $start = $args['start'];
780     }
782     $command = "=";
783     if ($pid == -1) {
784         $pid = "%";
785     } elseif (empty($pid)) {
786         $pid = "NULL";
787     }
789     if (strstr($pid, "%")) {
790         $command = "like";
791     }
793     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
794     if ($limit != "all") {
795         $sql .= " limit $start, $limit";
796     }
798     $rez = sqlStatement($sql);
799     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
800         $returnval[$iter]=$row;
801     }
803     return $returnval;
806 /* return a patient's name in the format LAST, FIRST */
807 function getPatientName($pid)
809     if (empty($pid)) {
810         return "";
811     }
813     $patientData = getPatientPID(array("pid"=>$pid));
814     if (empty($patientData[0]['lname'])) {
815         return "";
816     }
818     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
819     return $patientName;
822 /* find patient data by DOB */
823 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
825     $DOB = fixDate($DOB, $DOB);
826     $sqlBindArray = array();
827     $where = "DOB like ? ";
828     array_push($sqlBindArray, $DOB."%");
829     if (!empty($GLOBALS['pt_restrict_field'])) {
830         if ($_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin']) {
831             $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
832                     " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
833                     add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
834             array_push($sqlBindArray, $_SESSION{"authUser"});
835         }
836     }
838     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
840     if ($limit != "all") {
841         $sql .= " LIMIT $start, $limit";
842     }
844     $rez = sqlStatement($sql, $sqlBindArray);
845     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
846         $returnval[$iter]=$row;
847     }
849     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
850     return $returnval;
853 /* find patient data by SSN */
854 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
856     $sqlBindArray = array();
857     $where = "ss LIKE ?";
858     array_push($sqlBindArray, $ss."%");
859     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
860     if ($limit != "all") {
861         $sql .= " LIMIT $start, $limit";
862     }
864     $rez = sqlStatement($sql, $sqlBindArray);
865     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
866         $returnval[$iter]=$row;
867     }
869     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
870     return $returnval;
873 //(CHEMED) Search by phone number
874 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit = "all", $start = "0")
876     $phone = preg_replace("/[[:punct:]]/", "", $phone);
877     $sqlBindArray = array();
878     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
879     array_push($sqlBindArray, $phone);
880     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
881     if ($limit != "all") {
882         $sql .= " LIMIT $start, $limit";
883     }
885     $rez = sqlStatement($sql, $sqlBindArray);
886     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
887         $returnval[$iter]=$row;
888     }
890     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
891     return $returnval;
894 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit = "all", $start = "0")
896     $sql="select $given from patient_data order by $orderby";
898     if ($limit != "all") {
899         $sql .= " limit $start, $limit";
900     }
902     $rez = sqlStatement($sql);
903     for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
904         $returnval[$iter]=$row;
905     }
907     return $returnval;
910 //----------------------input functions
911 function newPatientData(
912     $db_id = "",
913     $title = "",
914     $fname = "",
915     $lname = "",
916     $mname = "",
917     $sex = "",
918     $DOB = "",
919     $street = "",
920     $postal_code = "",
921     $city = "",
922     $state = "",
923     $country_code = "",
924     $ss = "",
925     $occupation = "",
926     $phone_home = "",
927     $phone_biz = "",
928     $phone_contact = "",
929     $status = "",
930     $contact_relationship = "",
931     $referrer = "",
932     $referrerID = "",
933     $email = "",
934     $language = "",
935     $ethnoracial = "",
936     $interpretter = "",
937     $migrantseasonal = "",
938     $family_size = "",
939     $monthly_income = "",
940     $homeless = "",
941     $financial_review = "",
942     $pubpid = "",
943     $pid = "MAX(pid)+1",
944     $providerID = "",
945     $genericname1 = "",
946     $genericval1 = "",
947     $genericname2 = "",
948     $genericval2 = "",
949     $billing_note = "",
950     $phone_cell = "",
951     $hipaa_mail = "",
952     $hipaa_voice = "",
953     $squad = 0,
954     $pharmacy_id = 0,
955     $drivers_license = "",
956     $hipaa_notice = "",
957     $hipaa_message = "",
958     $regdate = ""
959 ) {
961     $DOB = fixDate($DOB);
962     $regdate = fixDate($regdate);
964     $fitness = 0;
965     $referral_source = '';
966     if ($pid) {
967         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
968         // Check for brain damage:
969         if ($db_id != $rez['id']) {
970             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
971               $rez['id'] . "' to '$db_id' for pid '$pid'";
972             die($errmsg);
973         }
975         $fitness = $rez['fitness'];
976         $referral_source = $rez['referral_source'];
977     }
979     // Get the default price level.
980     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
981       "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
982     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
984     $query = ("replace into patient_data set
985         id='$db_id',
986         title='$title',
987         fname='$fname',
988         lname='$lname',
989         mname='$mname',
990         sex='$sex',
991         DOB='$DOB',
992         street='$street',
993         postal_code='$postal_code',
994         city='$city',
995         state='$state',
996         country_code='$country_code',
997         drivers_license='$drivers_license',
998         ss='$ss',
999         occupation='$occupation',
1000         phone_home='$phone_home',
1001         phone_biz='$phone_biz',
1002         phone_contact='$phone_contact',
1003         status='$status',
1004         contact_relationship='$contact_relationship',
1005         referrer='$referrer',
1006         referrerID='$referrerID',
1007         email='$email',
1008         language='$language',
1009         ethnoracial='$ethnoracial',
1010         interpretter='$interpretter',
1011         migrantseasonal='$migrantseasonal',
1012         family_size='$family_size',
1013         monthly_income='$monthly_income',
1014         homeless='$homeless',
1015         financial_review='$financial_review',
1016         pubpid='$pubpid',
1017         pid = $pid,
1018         providerID = '$providerID',
1019         genericname1 = '$genericname1',
1020         genericval1 = '$genericval1',
1021         genericname2 = '$genericname2',
1022         genericval2 = '$genericval2',
1023         billing_note= '$billing_note',
1024         phone_cell = '$phone_cell',
1025         pharmacy_id = '$pharmacy_id',
1026         hipaa_mail = '$hipaa_mail',
1027         hipaa_voice = '$hipaa_voice',
1028         hipaa_notice = '$hipaa_notice',
1029         hipaa_message = '$hipaa_message',
1030         squad = '$squad',
1031         fitness='$fitness',
1032         referral_source='$referral_source',
1033         regdate='$regdate',
1034         pricelevel='$pricelevel',
1035         date=NOW()");
1037     $id = sqlInsert($query);
1039     if (!$db_id) {
1040       // find the last inserted id for new patient case
1041         $db_id = getSqlLastID();
1042     }
1044     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
1046     return $foo['pid'];
1049 // Supported input date formats are:
1050 //   mm/dd/yyyy
1051 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
1052 //   yyyy/mm/dd
1053 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
1055 function fixDate($date, $default = "0000-00-00")
1057     $fixed_date = $default;
1058     $date = trim($date);
1059     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
1060         $dmy = preg_split("'[/.-]'", $date);
1061         if ($dmy[0] > 99) {
1062             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
1063         } else {
1064             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
1065                 if ($dmy[2] < 1000) {
1066                     $dmy[2] += 1900;
1067                 }
1069                 if ($dmy[2] < 1910) {
1070                     $dmy[2] += 100;
1071                 }
1072             }
1074             // phone_country_code indicates format of ambiguous input dates.
1075             if ($GLOBALS['phone_country_code'] == 1) {
1076                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
1077             } else {
1078                 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
1079             }
1080         }
1081     }
1083     return $fixed_date;
1086 function pdValueOrNull($key, $value)
1088     if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
1089     substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
1090     (empty($value) || $value == '0000-00-00')) {
1091         return "NULL";
1092     } else {
1093         return "'" . add_escape_custom($value) . "'";
1094     }
1097 // Create or update patient data from an array.
1099 function updatePatientData($pid, $new, $create = false)
1101   /*******************************************************************
1102     $real = getPatientData($pid);
1103     $new['DOB'] = fixDate($new['DOB']);
1104     while(list($key, $value) = each ($new))
1105         $real[$key] = $value;
1106     $real['date'] = "'+NOW()+'";
1107     $real['id'] = "";
1108     $sql = "insert into patient_data set ";
1109     while(list($key, $value) = each($real))
1110         $sql .= $key." = '$value', ";
1111     $sql = substr($sql, 0, -2);
1112     return sqlInsert($sql);
1113   *******************************************************************/
1115   // The above was broken, though seems intent to insert a new patient_data
1116   // row for each update.  A good idea, but nothing is doing that yet so
1117   // the code below does not yet attempt it.
1119     $new['DOB'] = fixDate($new['DOB']);
1121     if ($create) {
1122         $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1123         foreach ($new as $key => $value) {
1124             if ($key == 'id') {
1125                 continue;
1126             }
1128             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1129         }
1131         $db_id = sqlInsert($sql);
1132     } else {
1133         $db_id = $new['id'];
1134         $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1135         // Check for brain damage:
1136         if ($pid != $rez['pid']) {
1137             $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1138             text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1139             die($errmsg);
1140         }
1142         $sql = "UPDATE patient_data SET date = NOW()";
1143         foreach ($new as $key => $value) {
1144             $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1145         }
1147         $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1148         sqlStatement($sql);
1149     }
1151     return $db_id;
1154 function newEmployerData(
1155     $pid,
1156     $name = "",
1157     $street = "",
1158     $postal_code = "",
1159     $city = "",
1160     $state = "",
1161     $country = ""
1162 ) {
1164     return sqlInsert("insert into employer_data set
1165         name='$name',
1166         street='$street',
1167         postal_code='$postal_code',
1168         city='$city',
1169         state='$state',
1170         country='$country',
1171         pid='$pid',
1172         date=NOW()
1173         ");
1176 // Create or update employer data from an array.
1178 function updateEmployerData($pid, $new, $create = false)
1180     $colnames = array('name','street','city','state','postal_code','country');
1182     if ($create) {
1183         $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1184         foreach ($colnames as $key) {
1185             $value = isset($new[$key]) ? $new[$key] : '';
1186             $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1187         }
1189         return sqlInsert("INSERT INTO employer_data SET $set");
1190     } else {
1191         $set = '';
1192         $old = getEmployerData($pid);
1193         $modified = false;
1194         foreach ($colnames as $key) {
1195             $value = empty($old[$key]) ? '' : $old[$key];
1196             if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1197                 $value = $new[$key];
1198                 $modified = true;
1199             }
1201             $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1202         }
1204         if ($modified) {
1205             $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1206             return sqlInsert("INSERT INTO employer_data SET $set");
1207         }
1209         return $old['id'];
1210     }
1213 // This updates or adds the given insurance data info, while retaining any
1214 // previously added insurance_data rows that should be preserved.
1215 // This does not directly support the maintenance of non-current insurance.
1217 function newInsuranceData(
1218     $pid,
1219     $type = "",
1220     $provider = "",
1221     $policy_number = "",
1222     $group_number = "",
1223     $plan_name = "",
1224     $subscriber_lname = "",
1225     $subscriber_mname = "",
1226     $subscriber_fname = "",
1227     $subscriber_relationship = "",
1228     $subscriber_ss = "",
1229     $subscriber_DOB = "",
1230     $subscriber_street = "",
1231     $subscriber_postal_code = "",
1232     $subscriber_city = "",
1233     $subscriber_state = "",
1234     $subscriber_country = "",
1235     $subscriber_phone = "",
1236     $subscriber_employer = "",
1237     $subscriber_employer_street = "",
1238     $subscriber_employer_city = "",
1239     $subscriber_employer_postal_code = "",
1240     $subscriber_employer_state = "",
1241     $subscriber_employer_country = "",
1242     $copay = "",
1243     $subscriber_sex = "",
1244     $effective_date = "0000-00-00",
1245     $accept_assignment = "TRUE",
1246     $policy_type = ""
1247 ) {
1249     if (strlen($type) <= 0) {
1250         return false;
1251     }
1253   // If a bad date was passed, err on the side of caution.
1254     $effective_date = fixDate($effective_date, date('Y-m-d'));
1256     $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1257     "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1258     $idrow = sqlFetchArray($idres);
1260   // Replace the most recent entry in any of the following cases:
1261   // * Its effective date is >= this effective date.
1262   // * It is the first entry and it has no (insurance) provider.
1263   // * There is no encounter that is earlier than the new effective date but
1264   //   on or after the old effective date.
1265   // Otherwise insert a new entry.
1267     $replace = false;
1268     if ($idrow) {
1269         if (strcmp($idrow['date'], $effective_date) > 0) {
1270             $replace = true;
1271         } else {
1272             if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1273                 $replace = true;
1274             } else {
1275                 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1276                 "WHERE pid = ? AND date < ? AND " .
1277                 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1278                 if ($ferow['count'] == 0) {
1279                     $replace = true;
1280                 }
1281             }
1282         }
1283     }
1285     if ($replace) {
1286         // TBD: This is a bit dangerous in that a typo in entering the effective
1287         // date can wipe out previous insurance history.  So we want some data
1288         // entry validation somewhere.
1289         sqlStatement("DELETE FROM insurance_data WHERE " .
1290         "pid = ? AND type = ? AND date >= ? AND " .
1291         "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1293         $data = array();
1294         $data['type'] = $type;
1295         $data['provider'] = $provider;
1296         $data['policy_number'] = $policy_number;
1297         $data['group_number'] = $group_number;
1298         $data['plan_name'] = $plan_name;
1299         $data['subscriber_lname'] = $subscriber_lname;
1300         $data['subscriber_mname'] = $subscriber_mname;
1301         $data['subscriber_fname'] = $subscriber_fname;
1302         $data['subscriber_relationship'] = $subscriber_relationship;
1303         $data['subscriber_ss'] = $subscriber_ss;
1304         $data['subscriber_DOB'] = $subscriber_DOB;
1305         $data['subscriber_street'] = $subscriber_street;
1306         $data['subscriber_postal_code'] = $subscriber_postal_code;
1307         $data['subscriber_city'] = $subscriber_city;
1308         $data['subscriber_state'] = $subscriber_state;
1309         $data['subscriber_country'] = $subscriber_country;
1310         $data['subscriber_phone'] = $subscriber_phone;
1311         $data['subscriber_employer'] = $subscriber_employer;
1312         $data['subscriber_employer_city'] = $subscriber_employer_city;
1313         $data['subscriber_employer_street'] = $subscriber_employer_street;
1314         $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1315         $data['subscriber_employer_state'] = $subscriber_employer_state;
1316         $data['subscriber_employer_country'] = $subscriber_employer_country;
1317         $data['copay'] = $copay;
1318         $data['subscriber_sex'] = $subscriber_sex;
1319         $data['pid'] = $pid;
1320         $data['date'] = $effective_date;
1321         $data['accept_assignment'] = $accept_assignment;
1322         $data['policy_type'] = $policy_type;
1323         updateInsuranceData($idrow['id'], $data);
1324         return $idrow['id'];
1325     } else {
1326         return sqlInsert("INSERT INTO insurance_data SET
1327       type = '" . add_escape_custom($type) . "',
1328       provider = '" . add_escape_custom($provider) . "',
1329       policy_number = '" . add_escape_custom($policy_number) . "',
1330       group_number = '" . add_escape_custom($group_number) . "',
1331       plan_name = '" . add_escape_custom($plan_name) . "',
1332       subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1333       subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1334       subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1335       subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1336       subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1337       subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1338       subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1339       subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1340       subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1341       subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1342       subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1343       subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1344       subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1345       subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1346       subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1347       subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1348       subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1349       subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1350       copay = '" . add_escape_custom($copay) . "',
1351       subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1352       pid = '" . add_escape_custom($pid) . "',
1353       date = '" . add_escape_custom($effective_date) . "',
1354       accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1355       policy_type = '" . add_escape_custom($policy_type) . "'
1356     ");
1357     }
1360 // This is used internally only.
1361 function updateInsuranceData($id, $new)
1363     $fields = sqlListFields("insurance_data");
1364     $use = array();
1366     while (list($key, $value) = each($new)) {
1367         if (in_array($key, $fields)) {
1368             $use[$key] = $value;
1369         }
1370     }
1372     $sql = "UPDATE insurance_data SET ";
1373     while (list($key, $value) = each($use)) {
1374         $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1375     }
1377     $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1379     sqlStatement($sql);
1382 function newHistoryData($pid, $new = false)
1384     $arraySqlBind = array();
1385     $sql = "insert into history_data set pid = ?, date = NOW()";
1386     array_push($arraySqlBind, $pid);
1387     if ($new) {
1388         while (list($key, $value) = each($new)) {
1389             array_push($arraySqlBind, $value);
1390             $sql .= ", `$key` = ?";
1391         }
1392     }
1394     return sqlInsert($sql, $arraySqlBind);
1397 function updateHistoryData($pid, $new)
1399         $real = getHistoryData($pid);
1400     while (list($key, $value) = each($new)) {
1401         $real[$key] = $value;
1402     }
1404         $real['id'] = "";
1405     // need to unset date, so can reset it below
1406     unset($real['date']);
1408         $arraySqlBind = array();
1409         $sql = "insert into history_data set `date` = NOW(), ";
1410     while (list($key, $value) = each($real)) {
1411         array_push($arraySqlBind, $value);
1412         $sql .= "`$key` = ?, ";
1413     }
1415         $sql = substr($sql, 0, -2);
1417         return sqlInsert($sql, $arraySqlBind);
1420 // Returns Age
1421 //   in months if < 2 years old
1422 //   in years  if > 2 years old
1423 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1424 // (optional) nowYMD is a date in YYYYMMDD format
1425 function getPatientAge($dobYMD, $nowYMD = null)
1427     // strip any dashes from the DOB
1428     $dobYMD = preg_replace("/-/", "", $dobYMD);
1429     $dobDay = substr($dobYMD, 6, 2);
1430     $dobMonth = substr($dobYMD, 4, 2);
1431     $dobYear = substr($dobYMD, 0, 4);
1433     // set the 'now' date values
1434     if ($nowYMD == null) {
1435         $nowDay = date("d");
1436         $nowMonth = date("m");
1437         $nowYear = date("Y");
1438     } else {
1439         $nowDay = substr($nowYMD, 6, 2);
1440         $nowMonth = substr($nowYMD, 4, 2);
1441         $nowYear = substr($nowYMD, 0, 4);
1442     }
1444     $dayDiff = $nowDay - $dobDay;
1445     $monthDiff = $nowMonth - $dobMonth;
1446     $yearDiff = $nowYear - $dobYear;
1448     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1450     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1451     if ($dayDiff<0) {
1452         $ageInMonths-=1;
1453     }
1455     if ($ageInMonths > 24) {
1456         $age = $yearDiff;
1457         if (($monthDiff == 0) && ($dayDiff < 0)) {
1458             $age -= 1;
1459         } else if ($monthDiff < 0) {
1460             $age -= 1;
1461         }
1462     } else {
1463         $age = "$ageInMonths " . xl('month');
1464     }
1466     return $age;
1470  * Wrapper to make sure the clinical rules dates formats corresponds to the
1471  * format expected by getPatientAgeYMD
1473  * @param  string  $dob     date of birth
1474  * @param  string  $target  date to calculate age on
1475  * @return array containing
1476  *      age - decimal age in years
1477  *      age_in_months - decimal age in months
1478  *      ageinYMD - formatted string #y #m #d */
1479 function parseAgeInfo($dob, $target)
1481     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1482     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1483     ;
1484     // Prepare target (Y-M-D H:M:S)
1485     $dateTarget = preg_replace("/[-\s\/]/", "", $target);
1487     return getPatientAgeYMD($dateDOB, $dateTarget);
1492  * @param type $dob
1493  * @param type $date
1494  * @return array containing
1495  *      age - decimal age in years
1496  *      age_in_months - decimal age in months
1497  *      ageinYMD - formatted string #y #m #d
1498  */
1499 function getPatientAgeYMD($dob, $date = null)
1502     if ($date == null) {
1503         $daynow = date("d");
1504         $monthnow = date("m");
1505         $yearnow = date("Y");
1506         $datenow=$yearnow.$monthnow.$daynow;
1507     } else {
1508         $datenow=preg_replace("/-/", "", $date);
1509         $yearnow=substr($datenow, 0, 4);
1510         $monthnow=substr($datenow, 4, 2);
1511         $daynow=substr($datenow, 6, 2);
1512         $datenow=$yearnow.$monthnow.$daynow;
1513     }
1515     $dob=preg_replace("/-/", "", $dob);
1516     $dobyear=substr($dob, 0, 4);
1517     $dobmonth=substr($dob, 4, 2);
1518     $dobday=substr($dob, 6, 2);
1519     $dob=$dobyear.$dobmonth.$dobday;
1521     //to compensate for 30, 31, 28, 29 days/month
1522     $mo=$monthnow; //to avoid confusion with later calculation
1524     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1
1525         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1526     } // look at April, June, September, November for calculation.  These months only have 30 days.
1527     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1528         $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1529         if (is_int($check_leap_Y)) {
1530             $nd=29;
1531         } //If it true then this is the leap year
1532         else {
1533             $nd=28;
1534         } //otherwise, it is not a leap year.
1535     } else {
1536         $nd=31;
1537     } // other months have 31 days
1539     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1540     if ($datenow < $bdthisyear) { // if patient hasn't had birthday yet this year
1541         $age_year = $yearnow - $dobyear - 1;
1542         if ($daynow < $dobday) {
1543             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1544             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1545         } else {
1546             $months_since_birthday=12 - $dobmonth + $monthnow;
1547             $days_since_dobday=$daynow - $dobday;
1548         }
1549     } else // if patient has had birthday this calandar year
1550     {
1551         $age_year = $yearnow - $dobyear;
1552         if ($daynow < $dobday) {
1553             $months_since_birthday=$monthnow - $dobmonth -1;
1554             $days_since_dobday=$nd - $dobday + $daynow;
1555         } else {
1556             $months_since_birthday=$monthnow - $dobmonth;
1557             $days_since_dobday=$daynow - $dobday;
1558         }
1559     }
1561     $day_as_month_decimal = $days_since_dobday / 30;
1562     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1563     $month_as_year_decimal = $months_since_birthday_float / 12;
1564     $age_float = $age_year + $month_as_year_decimal;
1566     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1567     $age_in_months = round($age_in_months, 2);  //round the months to xx.xx 2 floating points
1568     $age = round($age_float, 2);
1570     // round the years to 2 floating points
1571     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1572     return compact('age', 'age_in_months', 'ageinYMD');
1575 // Returns Age in days
1576 //   in months if < 2 years old
1577 //   in years  if > 2 years old
1578 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1579 // (optional) nowYMD is a date in YYYYMMDD format
1580 function getPatientAgeInDays($dobYMD, $nowYMD = null)
1582     $age = -1;
1584     // strip any dashes from the DOB
1585     $dobYMD = preg_replace("/-/", "", $dobYMD);
1586     $dobDay = substr($dobYMD, 6, 2);
1587     $dobMonth = substr($dobYMD, 4, 2);
1588     $dobYear = substr($dobYMD, 0, 4);
1590     // set the 'now' date values
1591     if ($nowYMD == null) {
1592         $nowDay = date("d");
1593         $nowMonth = date("m");
1594         $nowYear = date("Y");
1595     } else {
1596         $nowDay = substr($nowYMD, 6, 2);
1597         $nowMonth = substr($nowYMD, 4, 2);
1598         $nowYear = substr($nowYMD, 0, 4);
1599     }
1601     // do the date math
1602     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1603     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1604     $timediff = $nowtime - $dobtime;
1605     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1607     return $age;
1610  * Returns a string to be used to display a patient's age
1612  * @param type $dobYMD
1613  * @param type $asOfYMD
1614  * @return string suitable for displaying patient's age based on preferences
1615  */
1616 function getPatientAgeDisplay($dobYMD, $asOfYMD = null)
1618     if ($GLOBALS['age_display_format']=='1') {
1619         $ageYMD=getPatientAgeYMD($dobYMD, $asOfYMD);
1620         if (isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit']) {
1621             return $ageYMD['ageinYMD'];
1622         } else {
1623             return getPatientAge($dobYMD, $asOfYMD);
1624         }
1625     } else {
1626         return getPatientAge($dobYMD, $asOfYMD);
1627     }
1629 function dateToDB($date)
1631     $date=substr($date, 6, 4)."-".substr($date, 3, 2)."-".substr($date, 0, 2);
1632     return $date;
1636 // ----------------------------------------------------------------------------
1638  * DROPDOWN FOR COUNTRIES
1640  * build a dropdown with all countries from geo_country_reference
1642  * @param int $selected - id for selected record
1643  * @param string $name - the name/id for select form
1644  * @return void - just echo the html encoded string
1645  */
1646 function dropdown_countries($selected = 0, $name = 'country_code')
1648     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1650     $string = "<select name='$name' id='$name'>";
1651     while ($row = sqlFetchArray($r)) {
1652         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1653         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1654     }
1656     $string .= '</select>';
1657     echo $string;
1661 // ----------------------------------------------------------------------------
1663  * DROPDOWN FOR YES/NO
1665  * build a dropdown with two options (yes - 1, no - 0)
1667  * @param int $selected - id for selected record
1668  * @param string $name - the name/id for select form
1669  * @return void - just echo the html encoded string
1670  */
1671 function dropdown_yesno($selected = 0, $name = 'yesno')
1673     $string = "<select name='$name' id='$name'>";
1675     $selected = (int)$selected;
1676     if ($selected == 0) {
1677         $sel1 = 'selected="selected"';
1678         $sel2 = '';
1679     } else {
1680         $sel2 = 'selected="selected"';
1681         $sel1 = '';
1682     }
1684         $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1685         $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1686         $string .= '</select>';
1688         echo $string;
1691 // ----------------------------------------------------------------------------
1693  * DROPDOWN FOR MALE/FEMALE options
1695  * build a dropdown with three options (unselected/male/female)
1697  * @param int $selected - id for selected record
1698  * @param string $name - the name/id for select form
1699  * @return void - just echo the html encoded string
1700  */
1701 function dropdown_sex($selected = 0, $name = 'sex')
1703     $string = "<select name='$name' id='$name'>";
1705     if ($selected == 1) {
1706         $sel1 = 'selected="selected"';
1707         $sel2 = '';
1708         $sel0 = '';
1709     } else if ($selected == 2) {
1710         $sel2 = 'selected="selected"';
1711         $sel1 = '';
1712         $sel0 = '';
1713     } else {
1714             $sel0 = 'selected="selected"';
1715             $sel1 = '';
1716             $sel2 = '';
1717     }
1719         $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1720         $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1721         $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1722         $string .= '</select>';
1724         echo $string;
1727 // ----------------------------------------------------------------------------
1729  * DROPDOWN FOR MARITAL STATUS
1731  * build a dropdown with marital status
1733  * @param int $selected - id for selected record
1734  * @param string $name - the name/id for select form
1735  * @return void - just echo the html encoded string
1736  */
1737 function dropdown_marital($selected = 0, $name = 'status')
1739     $string = "<select name='$name' id='$name'>";
1741     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1743     foreach ($statii as $st) {
1744         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1745         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1746     }
1748     $string .= '</select>';
1750     echo $string;
1753 // ----------------------------------------------------------------------------
1755  * DROPDOWN FOR PROVIDERS
1757  * build a dropdown with all providers
1759  * @param int $selected - id for selected record
1760  * @param string $name - the name/id for select form
1761  * @return void - just echo the html encoded string
1762  */
1763 function dropdown_providers($selected = 0, $name = 'status')
1765     $provideri = getProviderInfo();
1767     $string = "<select name='$name' id='$name'>";
1768     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1769     foreach ($provideri as $s) {
1770         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1771         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1772     }
1774     $string .= '</select>';
1776     echo $string;
1779 // ----------------------------------------------------------------------------
1781  * DROPDOWN FOR INSURANCE COMPANIES
1783  * build a dropdown with all insurers
1785  * @param int $selected - id for selected record
1786  * @param string $name - the name/id for select form
1787  * @return void - just echo the html encoded string
1788  */
1789 function dropdown_insurance($selected = 0, $name = 'iprovider')
1791     $insurancei = getInsuranceProviders();
1793     $string = "<select name='$name' id='$name'>";
1794     $string .= '<option value="0">Onbekend</option>';
1795     foreach ($insurancei as $iid => $iname) {
1796         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1797         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1798     }
1800     $string .= '</select>';
1802     echo $string;
1806 // ----------------------------------------------------------------------------
1808  * COUNTRY CODE
1810  * return the name or the country code, function of arguments
1812  * @param int $country_code
1813  * @param string $country_name
1814  * @return string | int - name or code
1815  */
1816 function country_code($country_code = 0, $country_name = '')
1818     $strint = '';
1819     if ($country_code) {
1820         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1821     } else {
1822         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1823     }
1825     $db = $GLOBALS['adodb']['db'];
1826     $result = $db->Execute($sql);
1827     if ($result && !$result->EOF) {
1828         $strint = $result->fields['res'];
1829     }
1831     return $strint;
1834 function DBToDate($date)
1836     $date=substr($date, 5, 2)."/".substr($date, 8, 2)."/".substr($date, 0, 4);
1837     return $date;
1841  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1842  * for the given patient on the given date.
1844  * @param int     The PID of the patient.
1845  * @param string  Date in yyyy-mm-dd format.
1846  * @return array  Array of 0-3 insurance_data rows.
1847  */
1848 function getEffectiveInsurances($patient_id, $encdate)
1850     $insarr = array();
1851     foreach (array('primary','secondary','tertiary') as $instype) {
1852         $tmp = sqlQuery(
1853             "SELECT * FROM insurance_data " .
1854             "WHERE pid = ? AND type = ? " .
1855             "AND date <= ? ORDER BY date DESC LIMIT 1",
1856             array($patient_id, $instype, $encdate)
1857         );
1858         if (empty($tmp['provider'])) {
1859             break;
1860         }
1862         $insarr[] = $tmp;
1863     }
1865     return $insarr;
1869  * Get the patient's balance due. Normally this excludes amounts that are out
1870  * to insurance.  If you want to include what insurance owes, set the second
1871  * parameter to true.
1873  * @param int     The PID of the patient.
1874  * @param boolean Indicates if amounts owed by insurance are to be included.
1875  * @return number The balance.
1876  */
1877 function get_patient_balance($pid, $with_insurance = false)
1879     $balance = 0;
1880     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1881       "last_level_closed, stmt_count " .
1882       "FROM form_encounter WHERE pid = ?", array($pid));
1883     while ($ferow = sqlFetchArray($feres)) {
1884         $encounter = $ferow['encounter'];
1885         $dos = substr($ferow['date'], 0, 10);
1886         $insarr = getEffectiveInsurances($pid, $dos);
1887         $inscount = count($insarr);
1888         if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1889             // It's out to insurance so only the co-pay might be due.
1890             $brow = sqlQuery(
1891                 "SELECT SUM(fee) AS amount FROM billing WHERE " .
1892                 "pid = ? AND encounter = ? AND " .
1893                 "code_type = 'copay' AND activity = 1",
1894                 array($pid, $encounter)
1895             );
1896             $drow = sqlQuery(
1897                 "SELECT SUM(pay_amount) AS payments " .
1898                 "FROM ar_activity WHERE " .
1899                 "pid = ? AND encounter = ? AND payer_type = 0",
1900                 array($pid, $encounter)
1901             );
1902             $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1903             if ($ptbal > 0) {
1904                 $balance += $ptbal;
1905             }
1906         } else {
1907             // Including insurance or not out to insurance, everything is due.
1908             $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1909             "pid = ? AND encounter = ? AND " .
1910             "activity = 1", array($pid, $encounter));
1911             $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1912               "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1913               "pid = ? AND encounter = ?", array($pid, $encounter));
1914             $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1915               "pid = ? AND encounter = ?", array($pid, $encounter));
1916             $balance += $brow['amount'] + $srow['amount']
1917               - $drow['payments'] - $drow['adjustments'];
1918         }
1919     }
1921     return sprintf('%01.2f', $balance);
1924 // Function to check if patient is deceased.
1925 //  Param:
1926 //    $pid  - patient id
1927 //    $date - date checking if deceased (will default to current date if blank)
1928 //  Return:
1929 //    If deceased, then will return the number of
1930 //      days that patient has been deceased.
1931 //    If not deceased, then will return false.
1932 function is_patient_deceased($pid, $date = '')
1935   // Set date to current if not set
1936     $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1938   // Query for deceased status (gets days deceased if patient is deceased)
1939     $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1940                       "FROM `patient_data` " .
1941                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date));
1943     if (empty($results)) {
1944         // Patient is alive, so return false
1945         return false;
1946     } else {
1947         // Patient is dead, so return the number of days patient has been deceased.
1948         //  Don't let it be zero days or else will confuse calls to this function.
1949         if ($results['days_deceased'] === 0) {
1950             $results['days_deceased'] = 1;
1951         }
1953         return $results['days_deceased'];
1954     }