AMC changes for summary of care and CPOE, see note below:
[openemr.git] / library / patient.inc
blob6f8ca1dfa3ec0003367d8d17057895e9a99212e1
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 require_once("{$GLOBALS['srcdir']}/sql.inc");
12 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
13 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
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") {
53     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
54     return sqlQuery($sql, array($pid) );
57 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     }
66     return $returnval;
69 function getInsuranceProvider($ins_id) {
70     
71     $sql = "select name from insurance_companies where id=?";
72     $row = sqlQuery($sql,array($ins_id));
73     return $row['name'];
74     
77 function getInsuranceProviders() {
78     $returnval = array();
80     if (true) {
81         $sql = "select name, id from insurance_companies order by name, id";
82         $rez = sqlStatement($sql);
83         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
84             $returnval[$row['id']] = $row['name'];
85         }
86     }
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() {
112     $returnval = array();
113 // add a global and if for where to allow inactive inscompanies
115         $sql = "select insurance_companies.name, insurance_companies.id, " .
116           "addresses.zip, addresses.line1, addresses.state " .
117           "from insurance_companies, addresses " .
118           "where addresses.foreign_id = insurance_companies.id " .
119           "order by insurance_companies.name, addresses.zip";
121         $rez = sqlStatement($sql);
123         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
124     switch ($GLOBALS['insurance_information']) {
125         case $GLOBALS['insurance_information'] = '0':
126             $returnval[$row['id']] = $row['name'];
127         break;
128         case $GLOBALS['insurance_information'] = '1':
129             $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
130         break; 
131         case $GLOBALS['insurance_information'] = '2':
132            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";      
133         break;
134         case $GLOBALS['insurance_information'] = '3':
135            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
136         break; 
137         case $GLOBALS['insurance_information'] = '4':
138                $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
139            "," . $row['zip'] . ")";
140         break;
141         case $GLOBALS['insurance_information'] = '5':
142             preg_match("/\d+/", $row['line1'], $matches);
143             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
144               "," . $matches[0] . ")";
145         break; 
146         }
147     }
149     return $returnval;
152 function getProviders() {
153     $returnval = array("");
154     $sql = "select fname, lname from users where authorized = 1 and " .
155         "active = 1 and username != ''";
156     $rez = sqlStatement($sql);
157     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
158         if (($row["fname"] != "") && ($row["lname"] != "")) {
159             array_push($returnval, $row["fname"] . " " . $row["lname"]);
160         }
161     }
162     return $returnval;
165 // ----------------------------------------------------------------------------
166 // Get one facility row.  If the ID is not specified, then get either the
167 // "main" (billing) facility, or the default facility of the currently
168 // logged-in user.  This was created to support genFacilityTitle() but
169 // may find additional uses.
171 function getFacility($facid=0) {
173   //create a sql binding array
174   $sqlBindArray = array();
175   
176   if ($facid > 0) {
177     $query = "SELECT * FROM facility WHERE id = ?";
178     array_push($sqlBindArray,$facid);
179   }
180   else if ($facid == 0) {
181     $query = "SELECT * FROM facility ORDER BY " .
182       "billing_location DESC, service_location, id LIMIT 1";
183   }
184   else {
185     $query = "SELECT facility.* FROM users, facility WHERE " .
186       "users.id = ? AND " .
187       "facility.id = users.facility_id";
188     array_push($sqlBindArray,$_SESSION['authUserID']);
189   }
190   return sqlQuery($query,$sqlBindArray);
193 // Generate a report title including report name and facility name, address
194 // and phone.
196 function genFacilityTitle($repname='', $facid=0) {
197   $s = '';
198   $s .= "<table class='ftitletable'>\n";
199   $s .= " <tr>\n";
200   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
201   $s .= "  <td class='ftitlecell2'>\n";
202   $r = getFacility($facid);
203   if (!empty($r)) {
204     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
205     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
206     if ($r['city'] || $r['state'] || $r['postal_code']) {
207       $s .= "<br />";
208       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
209       if ($r['state']) {
210         if ($r['city']) $s .= ", \n";
211         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
212       }
213       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
214       $s .= "\n";
215     }
216     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
217     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
218   }
219   $s .= "  </td>\n";
220   $s .= " </tr>\n";
221   $s .= "</table>\n";
222   return $s;
226 GET FACILITIES
228 returns all facilities or just the id for the first one
229 (FACILITY FILTERING (lemonsoftware))
231 @param string - if 'first' return first facility ordered by id
232 @return array | int for 'first' case
234 function getFacilities($first = '') {
235     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
236     $ret = array();
237     while ( $row = sqlFetchArray($r) ) {
238        $ret[] = $row;
241         if ( $first == 'first') {
242             return $ret[0]['id'];
243         } else {
244             return $ret;
245         }
249 GET SERVICE FACILITIES
251 returns all service_location facilities or just the id for the first one
252 (FACILITY FILTERING (CHEMED))
254 @param string - if 'first' return first facility ordered by id
255 @return array | int for 'first' case
257 function getServiceFacilities($first = '') {
258     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
259     $ret = array();
260     while ( $row = sqlFetchArray($r) ) {
261        $ret[] = $row;
264         if ( $first == 'first') {
265             return $ret[0]['id'];
266         } else {
267             return $ret;
268         }
271 //(CHEMED) facility filter
272 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
273     $param1 = "";
274     if ($providers_only === 'any') {
275       $param1 = " AND authorized = 1 AND active = 1 ";
276     }
277     else if ($providers_only) {
278       $param1 = " AND authorized = 1 AND calendar = 1 ";
279     }
281     //--------------------------------
282     //(CHEMED) facility filter
283     $param2 = "";
284     if ($facility) {
285       if ($GLOBALS['restrict_user_facility']) {
286         $param2 = " AND (facility_id = $facility 
287           OR  $facility IN
288                 (select facility_id 
289                 from users_facility
290                 where tablename = 'users'
291                 and table_id = id)
292                 )
293           ";
294       }
295       else {
296         $param2 = " AND facility_id = $facility ";
297       }
298     }
299     //--------------------------------
301     $command = "=";
302     if ($providerID == "%") {
303         $command = "like";
304     }
305     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
306         "from users where username != '' and active = 1 and id $command '" .
307         add_escape_custom($providerID) . "' " . $param1 . $param2;
308     // sort by last name -- JRM June 2008
309     $query .= " ORDER BY lname, fname ";
310     $rez = sqlStatement($query);
311     for($iter=0; $row=sqlFetchArray($rez); $iter++)
312         $returnval[$iter]=$row;
314     //if only one result returned take the key/value pairs in array [0] and merge them down the the base array so that $resultval[0]['key'] is also
315     //accessible from $resultval['key']
317     if($iter==1) {
318         $akeys = array_keys($returnval[0]);
319         foreach($akeys as $key) {
320             $returnval[0][$key] = $returnval[0][$key];
321         }
322     }
323     return $returnval;
326 //same as above but does not reduce if only 1 row returned
327 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
328     $param1 = "";
329     if ($providers_only) {
330         $param1 = "AND authorized=1";
331     }
332     $command = "=";
333     if ($providerID == "%") {
334         $command = "like";
335     }
336     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
337         "from users where active = 1 and username != '' and id $command '" .
338         add_escape_custom($providerID) . "' " . $param1;
340     $rez = sqlStatement($query);
341     for($iter=0; $row=sqlFetchArray($rez); $iter++)
342         $returnval[$iter]=$row;
344     return $returnval;
347 function getProviderName($providerID) {
348     $pi = getProviderInfo($providerID, 'any');
349     if (strlen($pi[0]["lname"]) > 0) {
350         return $pi[0]['fname'] . " " . $pi[0]['lname'];
351     }
352     return "";
355 function getProviderId($providerName) {
356     $query = "select id from users where username = ?";
357     $rez = sqlStatement($query, array($providerName) );
358     for($iter=0; $row=sqlFetchArray($rez); $iter++)
359         $returnval[$iter]=$row;
360     return $returnval;
363 function getEthnoRacials() {
364     $returnval = array("");
365     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
366     $rez = sqlStatement($sql);
367     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
368         if (($row["ethnoracial"] != "")) {
369             array_push($returnval, $row["ethnoracial"]);
370         }
371     }
372     return $returnval;
375 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
378     if ($dateStart && $dateEnd) {
379         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
380     }
381     else if ($dateStart && !$dateEnd) {
382         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
383     }
384     else if (!$dateStart && $dateEnd) {
385         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
386     }
387     else {
388         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
389     }
390     
391     if($given == 'tobacco'){
392         $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));
393     }
395     return $res;
398 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
399 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
401   $sql = "select $given from insurance_data as insd " .
402     "left join insurance_companies as ic on ic.id = insd.provider " .
403     "where pid = ? and type = ? order by date DESC limit 1";
404   return sqlQuery($sql, array($pid, $type) );
407 function getInsuranceDataByDate($pid, $date, $type,
408   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
409 { // this must take the date in the following manner: YYYY-MM-DD
410   // this function recalls the insurance value that was most recently enterred from the
411   // given date. it will call up most recent records up to and on the date given,
412   // but not records enterred after the given date
413   $sql = "select $given from insurance_data as insd " .
414     "left join insurance_companies as ic on ic.id = provider " .
415     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
416     "type=? order by date DESC limit 1";
417   return sqlQuery($sql, array($pid,$date,$type) );
420 function getEmployerData($pid, $given = "*")
422     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
423     return sqlQuery($sql, array($pid) );
426 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
427   // When the limit is exceeded, find out what the unlimited count would be.
428   $GLOBALS['PATIENT_INC_COUNT'] = $count;
429   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
430   if ($limit != "all") {
431     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
432     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
433   }
437  * Allow the last name to be followed by a comma and some part of a first name(can
438  *   also place middle name after the first name with a space separating them)
439  * Allows comma alone followed by some part of a first name(can also place middle name
440  *   after the first name with a space separating them).
441  * Allows comma alone preceded by some part of a last name.
442  * If no comma or space, then will search both last name and first name.
443  * If the first letter of either name is capital, searches for name starting
444  *   with given substring (the expected behavior). If it is lower case, it
445  *   searches for the substring anywhere in the name. This applies to either
446  *   last name, first name, and middle name.
447  * Also allows first name followed by middle and/or last name when separated by spaces.
448  * @param string $term
449  * @param string $given
450  * @param string $orderby
451  * @param string $limit
452  * @param string $start
453  * @return array
454  */
455 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")
457     $names = getPatientNameSplit($term);
458     
459     foreach ($names as $key => $val) {
460       if (!empty($val)) {
461         if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
462             $names[$key] = '%' . $val . '%';            
463         } else { 
464             $names[$key] = $val . '%';            
465         }
466       }
467     }
469     // Debugging section below
470     //if(array_key_exists('first',$names)) {
471     //    error_log("first name search term :".$names['first']);
472     //}
473     //if(array_key_exists('middle',$names)) {
474     //    error_log("middle name search term :".$names['middle']);
475     //}
476     //if(array_key_exists('last',$names)) {
477     //    error_log("last name search term :".$names['last']);
478     //}
479     // Debugging section above
481     $sqlBindArray = array();
482     if(array_key_exists('last',$names) && $names['last'] == '') {
483         // Do not search last name
484         $where = "fname LIKE ? ";
485         array_push($sqlBindArray, $names['first']);
486         if ($names['middle'] != '') {        
487             $where .= "AND mname LIKE ? ";  
488             array_push($sqlBindArray, $names['middle']);
489         }
490     } elseif(array_key_exists('first',$names) && $names['first'] == '') {
491         // Do not search first name or middle name
492         $where = "lname LIKE ? ";
493         array_push($sqlBindArray, $names['last']);
494     } elseif($names['first'] == '' && $names['last'] != '') {
495         // Search both first name and last name with same term
496         $names['first'] = $names['last']; 
497         $where = "lname LIKE ? OR fname LIKE ? ";
498         array_push($sqlBindArray, $names['last'], $names['first']);
499     } elseif ($names['middle'] != '') {        
500         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";  
501         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
502     } else {
503         $where = "lname LIKE ? AND fname LIKE ? ";
504         array_push($sqlBindArray, $names['last'], $names['first']);
505     }
507         if (!empty($GLOBALS['pt_restrict_field'])) {
508                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
509                         $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
510                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
511                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
512                         array_push($sqlBindArray, $_SESSION{"authUser"});
513                 }
514         }
516     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
517     if ($limit != "all") $sql .= " LIMIT $start, $limit";
519     $rez = sqlStatement($sql, $sqlBindArray);
521     $returnval=array();
522     for($iter=0; $row=sqlFetchArray($rez); $iter++)
523         $returnval[$iter] = $row;
525     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
526     return $returnval;
529  * Accept a string used by a search function expected to find a patient name, 
530  * then split up the string if a comma or space exists. Return an array having 
531  * from 1 to 3 elements, named first, middle, and last.
532  * See above getPatientLnames() function for details on how the splitting occurs.
533  * @param string $term
534  * @return array
535  */
536 function getPatientNameSplit($term) {
537     $term = trim($term);
538     if (strpos($term, ',') !== false) {
539         $names = explode(',', $term);        
540         $n['last'] = $names[0];
541         if (strpos(trim($names[1]), ' ') !== false) {
542             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
543         } else {
544             $n['first'] = $names[1];
545         }
546     } elseif (strpos($term, ' ') !== false) {
547         $names = explode(' ', $term);
548         if (count($names) == 1) {
549             $n['last'] = $names[0];
550         } elseif (count($names) == 3) {
551             $n['first'] = $names[0];
552             $n['middle'] = $names[1];
553             $n['last'] = $names[2];
554         } else {
555             // This will handle first and last name or first followed by 
556             // multiple names only using just the last of the names in the list.
557             $n['first'] = $names[0];
558             $n['last'] = end($names);
559         }
560     } else {
561         $n['last'] = $term;
562         if(empty($n['last'])) $n['last'] = '%';
563     }
564     // Trim whitespace off the names before returning
565     foreach($n as $key => $val) {
566         $n[$key] = trim($val);
567     }
568     return $n; // associative array containing names
571 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")
574     $sqlBindArray = array();
575     $where = "pubpid LIKE ? ";
576     array_push($sqlBindArray, $pid."%");
577         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
578                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
579                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
580                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
581                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
582                         array_push($sqlBindArray, $_SESSION{"authUser"});
583                 }
584         }
586     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
587     if ($limit != "all") $sql .= " limit $start, $limit";
588     $rez = sqlStatement($sql, $sqlBindArray);
589     for($iter=0; $row=sqlFetchArray($rez); $iter++)
590         $returnval[$iter]=$row;
592     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
593     return $returnval;
596 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")
598   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
600   $sqlBindArray = array();
601   $where = "";
602   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
603     if ( $iter > 0 ) {
604       $where .= " or ";
605     }
606     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
607     array_push($sqlBindArray, "%".$searchTerm."%");
608   }
610   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
611   if ($limit != "all") $sql .= " limit $start, $limit";
612   $rez = sqlStatement($sql, $sqlBindArray);
613   for($iter=0; $row=sqlFetchArray($rez); $iter++)
614     $returnval[$iter]=$row;
615   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
616   return $returnval;
619 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
620   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
621   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
623         $layoutCols = explode( '~', $searchFields );
624   $sqlBindArray = array();
625   $where = "";
626   $i = 0;
627   foreach ($layoutCols as $val) {
628     if (empty($val)) continue;
629                 if ( $i > 0 ) {
630                    $where .= " or ";
631                 }
632     if ($val == 'pid') {
633                 $where .= " ".add_escape_custom($val)." = ? ";
634                 array_push($sqlBindArray, $searchTerm);
635     }
636     else {
637                 $where .= " ".add_escape_custom($val)." like ? ";
638                 array_push($sqlBindArray, $searchTerm."%");
639     }
640                 $i++;
641         }
643   // If no search terms, ensure valid syntax.
644   if ($i == 0) $where = "1 = 1";
646   // If a non-empty service code was given, then restrict to patients who
647   // have been provided that service.  Since the code is used in a LIKE
648   // clause, % and _ wildcards are supported.
649   if ($search_service_code) {
650     $where = "( $where ) AND " .
651       "( SELECT COUNT(*) FROM billing AS b WHERE " .
652       "b.pid = patient_data.pid AND " .
653       "b.activity = 1 AND " .
654       "b.code_type != 'COPAY' AND " .
655       "b.code LIKE ? " .
656       ") > 0";
657     array_push($sqlBindArray, $search_service_code);
658   }
660   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
661   if ($limit != "all") $sql .= " limit $start, $limit";
662   $rez = sqlStatement($sql, $sqlBindArray);
663   for($iter=0; $row=sqlFetchArray($rez); $iter++)
664       $returnval[$iter]=$row;
665   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
666   return $returnval;
669 // return a collection of Patient PIDs
670 // new arg style by JRM March 2008
671 // 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")
672 function getPatientPID($args)
674     $pid = "%";
675     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
676     $orderby = "lname ASC, fname ASC";
677     $limit="all";
678     $start="0";
680     // alter default values if defined in the passed in args
681     if (isset($args['pid'])) { $pid = $args['pid']; }
682     if (isset($args['given'])) { $given = $args['given']; }
683     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
684     if (isset($args['limit'])) { $limit = $args['limit']; }
685     if (isset($args['start'])) { $start = $args['start']; }
687     $command = "=";
688     if ($pid == -1) $pid = "%";
689     elseif (empty($pid)) $pid = "NULL";
691     if (strstr($pid,"%")) $command = "like";
693     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
694     if ($limit != "all") $sql .= " limit $start, $limit";
696     $rez = sqlStatement($sql);
697     for($iter=0; $row=sqlFetchArray($rez); $iter++)
698         $returnval[$iter]=$row;
700     return $returnval;
703 /* return a patient's name in the format LAST, FIRST */
704 function getPatientName($pid) {
705     if (empty($pid)) return "";
706     $patientData = getPatientPID(array("pid"=>$pid));
707     if (empty($patientData[0]['lname'])) return "";
708     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
709     return $patientName;
712 /* find patient data by DOB */
713 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
715     $DOB = fixDate($DOB, $DOB);
716     $sqlBindArray = array();
717     $where = "DOB like ? ";
718     array_push($sqlBindArray, $DOB."%");
719         if (!empty($GLOBALS['pt_restrict_field'])) {
720                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
721                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
722                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
723                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
724                         array_push($sqlBindArray, $_SESSION{"authUser"});
725                 }
726         }
728     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
730     if ($limit != "all") $sql .= " LIMIT $start, $limit";
732     $rez = sqlStatement($sql, $sqlBindArray);
733     for($iter=0; $row=sqlFetchArray($rez); $iter++)
734         $returnval[$iter]=$row;
736     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
737     return $returnval;
740 /* find patient data by SSN */
741 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
743     $sqlBindArray = array();
744     $where = "ss LIKE ?";
745     array_push($sqlBindArray, $ss."%");
746     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
747     if ($limit != "all") $sql .= " LIMIT $start, $limit";
749     $rez = sqlStatement($sql, $sqlBindArray);
750     for($iter=0; $row=sqlFetchArray($rez); $iter++)
751         $returnval[$iter]=$row;
753     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
754     return $returnval;
757 //(CHEMED) Search by phone number
758 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
760     $phone = preg_replace( "/[[:punct:]]/","", $phone );
761     $sqlBindArray = array();
762     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
763     array_push($sqlBindArray, $phone);
764     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
765     if ($limit != "all") $sql .= " LIMIT $start, $limit";
767     $rez = sqlStatement($sql, $sqlBindArray);
768     for($iter=0; $row=sqlFetchArray($rez); $iter++)
769         $returnval[$iter]=$row;
771     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
772     return $returnval;
775 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
777     $sql="select $given from patient_data order by $orderby";
779     if ($limit != "all")
780         $sql .= " limit $start, $limit";
782     $rez = sqlStatement($sql);
783     for($iter=0; $row=sqlFetchArray($rez); $iter++)
784         $returnval[$iter]=$row;
786     return $returnval;
789 //----------------------input functions
790 function newPatientData(    $db_id="",
791                 $title = "",
792                 $fname = "",
793                 $lname = "",
794                 $mname = "",
795                 $sex = "",
796                 $DOB = "",
797                 $street = "",
798                 $postal_code = "",
799                 $city = "",
800                 $state = "",
801                 $country_code = "",
802                 $ss = "",
803                 $occupation = "",
804                 $phone_home = "",
805                 $phone_biz = "",
806                 $phone_contact = "",
807                 $status = "",
808                 $contact_relationship = "",
809                 $referrer = "",
810                 $referrerID = "",
811                 $email = "",
812                 $language = "",
813                 $ethnoracial = "",
814                 $interpretter = "",
815                 $migrantseasonal = "",
816                 $family_size = "",
817                 $monthly_income = "",
818                 $homeless = "",
819                 $financial_review = "",
820                 $pubpid = "",
821                 $pid = "MAX(pid)+1",
822                 $providerID = "",
823                 $genericname1 = "",
824                 $genericval1 = "",
825                 $genericname2 = "",
826                 $genericval2 = "",
827                 $billing_note="",
828                 $phone_cell = "",
829                 $hipaa_mail = "",
830                 $hipaa_voice = "",
831                 $squad = 0,
832                 $pharmacy_id = 0,
833                 $drivers_license = "",
834                 $hipaa_notice = "",
835                 $hipaa_message = "",
836                 $regdate = ""
837             )
839     $DOB = fixDate($DOB);
840     $regdate = fixDate($regdate);
842     $fitness = 0;
843     $referral_source = '';
844     if ($pid) {
845         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
846         // Check for brain damage:
847         if ($db_id != $rez['id']) {
848             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
849               $rez['id'] . "' to '$db_id' for pid '$pid'";
850             die($errmsg);
851         }
852         $fitness = $rez['fitness'];
853         $referral_source = $rez['referral_source'];
854     }
856     // Get the default price level.
857     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
858       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
859     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
861     $query = ("replace into patient_data set
862         id='$db_id',
863         title='$title',
864         fname='$fname',
865         lname='$lname',
866         mname='$mname',
867         sex='$sex',
868         DOB='$DOB',
869         street='$street',
870         postal_code='$postal_code',
871         city='$city',
872         state='$state',
873         country_code='$country_code',
874         drivers_license='$drivers_license',
875         ss='$ss',
876         occupation='$occupation',
877         phone_home='$phone_home',
878         phone_biz='$phone_biz',
879         phone_contact='$phone_contact',
880         status='$status',
881         contact_relationship='$contact_relationship',
882         referrer='$referrer',
883         referrerID='$referrerID',
884         email='$email',
885         language='$language',
886         ethnoracial='$ethnoracial',
887         interpretter='$interpretter',
888         migrantseasonal='$migrantseasonal',
889         family_size='$family_size',
890         monthly_income='$monthly_income',
891         homeless='$homeless',
892         financial_review='$financial_review',
893         pubpid='$pubpid',
894         pid = $pid,
895         providerID = '$providerID',
896         genericname1 = '$genericname1',
897         genericval1 = '$genericval1',
898         genericname2 = '$genericname2',
899         genericval2 = '$genericval2',
900         billing_note= '$billing_note';
901         phone_cell = '$phone_cell',
902         pharmacy_id = '$pharmacy_id',
903         hipaa_mail = '$hipaa_mail',
904         hipaa_voice = '$hipaa_voice',
905         hipaa_notice = '$hipaa_notice',
906         hipaa_message = '$hipaa_message',
907         squad = '$squad',
908         fitness='$fitness',
909         referral_source='$referral_source',
910         regdate='$regdate',
911         pricelevel='$pricelevel',
912         date=NOW()");
914     $id = sqlInsert($query);
916     if ( !$db_id ) {
917       // find the last inserted id for new patient case
918       $db_id = getSqlLastID();
919     }
921     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
923     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
924                 $phone_biz,$phone_cell,$email,$pid);
926     return $foo['pid'];
929 // Supported input date formats are:
930 //   mm/dd/yyyy
931 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
932 //   yyyy/mm/dd
933 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
935 function fixDate($date, $default="0000-00-00") {
936     $fixed_date = $default;
937     $date = trim($date);
938     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
939         $dmy = preg_split("'[/.-]'", $date);
940         if ($dmy[0] > 99) {
941             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
942         } else {
943             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
944               if ($dmy[2] < 1000) $dmy[2] += 1900;
945               if ($dmy[2] < 1910) $dmy[2] += 100;
946             }
947             // phone_country_code indicates format of ambiguous input dates.
948             if ($GLOBALS['phone_country_code'] == 1)
949               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
950             else
951               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
952         }
953     }
955     return $fixed_date;
958 function pdValueOrNull($key, $value) {
959   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
960     substr($key, 0, 8) == 'userdate') &&
961     (empty($value) || $value == '0000-00-00'))
962   {
963     return "NULL";
964   }
965   else {
966     return "'$value'";
967   }
970 // Create or update patient data from an array.
972 function updatePatientData($pid, $new, $create=false)
974   /*******************************************************************
975     $real = getPatientData($pid);
976     $new['DOB'] = fixDate($new['DOB']);
977     while(list($key, $value) = each ($new))
978         $real[$key] = $value;
979     $real['date'] = "'+NOW()+'";
980     $real['id'] = "";
981     $sql = "insert into patient_data set ";
982     while(list($key, $value) = each($real))
983         $sql .= $key." = '$value', ";
984     $sql = substr($sql, 0, -2);
985     return sqlInsert($sql);
986   *******************************************************************/
988   // The above was broken, though seems intent to insert a new patient_data
989   // row for each update.  A good idea, but nothing is doing that yet so
990   // the code below does not yet attempt it.
992   $new['DOB'] = fixDate($new['DOB']);
994   if ($create) {
995     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
996     foreach ($new as $key => $value) {
997       if ($key == 'id') continue;
998       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
999     }
1000     $db_id = sqlInsert($sql);
1001   }
1002   else {
1003     $db_id = $new['id'];
1004     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1005     // Check for brain damage:
1006     if ($pid != $rez['pid']) {
1007       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1008         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1009       die($errmsg);
1010     }
1011     $sql = "UPDATE patient_data SET date = NOW()";
1012     foreach ($new as $key => $value) {
1013       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1014     }
1015     $sql .= " WHERE id = '$db_id'";
1016     sqlStatement($sql);
1017   }
1019   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
1020   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
1021     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
1022     $rez['phone_cell'],$rez['email'],$rez['pid']);
1024   return $db_id;
1027 function newEmployerData(    $pid,
1028                 $name = "",
1029                 $street = "",
1030                 $postal_code = "",
1031                 $city = "",
1032                 $state = "",
1033                 $country = ""
1034             )
1036     return sqlInsert("insert into employer_data set
1037         name='$name',
1038         street='$street',
1039         postal_code='$postal_code',
1040         city='$city',
1041         state='$state',
1042         country='$country',
1043         pid='$pid',
1044         date=NOW()
1045         ");
1048 // Create or update employer data from an array.
1050 function updateEmployerData($pid, $new, $create=false)
1052   $colnames = array('name','street','city','state','postal_code','country');
1054   if ($create) {
1055     $set .= "pid = '$pid', date = NOW()";
1056     foreach ($colnames as $key) {
1057       $value = isset($new[$key]) ? $new[$key] : '';
1058       $set .= ", `$key` = '$value'";
1059     }
1060     return sqlInsert("INSERT INTO employer_data SET $set");
1061   }
1062   else {
1063     $set = '';
1064     $old = getEmployerData($pid);
1065     $modified = false;
1066     foreach ($colnames as $key) {
1067       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1068       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1069         $value = $new[$key];
1070         $modified = true;
1071       }
1072       $set .= "`$key` = '$value', ";
1073     }
1074     if ($modified) {
1075       $set .= "pid = '$pid', date = NOW()";
1076       return sqlInsert("INSERT INTO employer_data SET $set");
1077     }
1078     return $old['id'];
1079   }
1082 // This updates or adds the given insurance data info, while retaining any
1083 // previously added insurance_data rows that should be preserved.
1084 // This does not directly support the maintenance of non-current insurance.
1086 function newInsuranceData(
1087   $pid,
1088   $type = "",
1089   $provider = "",
1090   $policy_number = "",
1091   $group_number = "",
1092   $plan_name = "",
1093   $subscriber_lname = "",
1094   $subscriber_mname = "",
1095   $subscriber_fname = "",
1096   $subscriber_relationship = "",
1097   $subscriber_ss = "",
1098   $subscriber_DOB = "",
1099   $subscriber_street = "",
1100   $subscriber_postal_code = "",
1101   $subscriber_city = "",
1102   $subscriber_state = "",
1103   $subscriber_country = "",
1104   $subscriber_phone = "",
1105   $subscriber_employer = "",
1106   $subscriber_employer_street = "",
1107   $subscriber_employer_city = "",
1108   $subscriber_employer_postal_code = "",
1109   $subscriber_employer_state = "",
1110   $subscriber_employer_country = "",
1111   $copay = "",
1112   $subscriber_sex = "",
1113   $effective_date = "0000-00-00",
1114   $accept_assignment = "TRUE",
1115   $policy_type = "")
1117   if (strlen($type) <= 0) return FALSE;
1119   // If a bad date was passed, err on the side of caution.
1120   $effective_date = fixDate($effective_date, date('Y-m-d'));
1122   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1123     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1124   $idrow = sqlFetchArray($idres);
1126   // Replace the most recent entry in any of the following cases:
1127   // * Its effective date is >= this effective date.
1128   // * It is the first entry and it has no (insurance) provider.
1129   // * There is no encounter that is earlier than the new effective date but
1130   //   on or after the old effective date.
1131   // Otherwise insert a new entry.
1133   $replace = false;
1134   if ($idrow) {
1135     if (strcmp($idrow['date'], $effective_date) > 0) {
1136       $replace = true;
1137     }
1138     else {
1139       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1140         $replace = true;
1141       }
1142       else {
1143         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1144           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1145           "date >= '" . $idrow['date'] . " 00:00:00'");
1146         if ($ferow['count'] == 0) $replace = true;
1147       }
1148     }
1149   }
1151   if ($replace) {
1153     // TBD: This is a bit dangerous in that a typo in entering the effective
1154     // date can wipe out previous insurance history.  So we want some data
1155     // entry validation somewhere.
1156     sqlStatement("DELETE FROM insurance_data WHERE " .
1157       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1158       "id != " . $idrow['id']);
1160     $data = array();
1161     $data['type'] = $type;
1162     $data['provider'] = $provider;
1163     $data['policy_number'] = $policy_number;
1164     $data['group_number'] = $group_number;
1165     $data['plan_name'] = $plan_name;
1166     $data['subscriber_lname'] = $subscriber_lname;
1167     $data['subscriber_mname'] = $subscriber_mname;
1168     $data['subscriber_fname'] = $subscriber_fname;
1169     $data['subscriber_relationship'] = $subscriber_relationship;
1170     $data['subscriber_ss'] = $subscriber_ss;
1171     $data['subscriber_DOB'] = $subscriber_DOB;
1172     $data['subscriber_street'] = $subscriber_street;
1173     $data['subscriber_postal_code'] = $subscriber_postal_code;
1174     $data['subscriber_city'] = $subscriber_city;
1175     $data['subscriber_state'] = $subscriber_state;
1176     $data['subscriber_country'] = $subscriber_country;
1177     $data['subscriber_phone'] = $subscriber_phone;
1178     $data['subscriber_employer'] = $subscriber_employer;
1179     $data['subscriber_employer_city'] = $subscriber_employer_city;
1180     $data['subscriber_employer_street'] = $subscriber_employer_street;
1181     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1182     $data['subscriber_employer_state'] = $subscriber_employer_state;
1183     $data['subscriber_employer_country'] = $subscriber_employer_country;
1184     $data['copay'] = $copay;
1185     $data['subscriber_sex'] = $subscriber_sex;
1186     $data['pid'] = $pid;
1187     $data['date'] = $effective_date;
1188     $data['accept_assignment'] = $accept_assignment;
1189     $data['policy_type'] = $policy_type;
1190     updateInsuranceData($idrow['id'], $data);
1191     return $idrow['id'];
1192   }
1193   else {
1194     return sqlInsert("INSERT INTO insurance_data SET
1195       type = '$type',
1196       provider = '$provider',
1197       policy_number = '$policy_number',
1198       group_number = '$group_number',
1199       plan_name = '$plan_name',
1200       subscriber_lname = '$subscriber_lname',
1201       subscriber_mname = '$subscriber_mname',
1202       subscriber_fname = '$subscriber_fname',
1203       subscriber_relationship = '$subscriber_relationship',
1204       subscriber_ss = '$subscriber_ss',
1205       subscriber_DOB = '$subscriber_DOB',
1206       subscriber_street = '$subscriber_street',
1207       subscriber_postal_code = '$subscriber_postal_code',
1208       subscriber_city = '$subscriber_city',
1209       subscriber_state = '$subscriber_state',
1210       subscriber_country = '$subscriber_country',
1211       subscriber_phone = '$subscriber_phone',
1212       subscriber_employer = '$subscriber_employer',
1213       subscriber_employer_city = '$subscriber_employer_city',
1214       subscriber_employer_street = '$subscriber_employer_street',
1215       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1216       subscriber_employer_state = '$subscriber_employer_state',
1217       subscriber_employer_country = '$subscriber_employer_country',
1218       copay = '$copay',
1219       subscriber_sex = '$subscriber_sex',
1220       pid = '$pid',
1221       date = '$effective_date',
1222       accept_assignment = '$accept_assignment',
1223       policy_type = '$policy_type'
1224     ");
1225   }
1228 // This is used internally only.
1229 function updateInsuranceData($id, $new)
1231   $fields = sqlListFields("insurance_data");
1232   $use = array();
1234   while(list($key, $value) = each ($new)) {
1235     if (in_array($key, $fields)) {
1236       $use[$key] = $value;
1237     }
1238   }
1240   $sql = "UPDATE insurance_data SET ";
1241   while(list($key, $value) = each($use))
1242     $sql .= "`$key` = '$value', ";
1243   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1245   sqlStatement($sql);
1248 function newHistoryData($pid, $new=false) {
1249   $arraySqlBind = array();
1250   $sql = "insert into history_data set pid = ?, date = NOW()";
1251   array_push($arraySqlBind,$pid);
1252   if ($new) {
1253     while(list($key, $value) = each($new)) {
1254       array_push($arraySqlBind,$value);
1255       $sql .= ", `$key` = ?";
1256     }
1257   }
1258   return sqlInsert($sql, $arraySqlBind );
1261 function updateHistoryData($pid,$new)
1263         $real = getHistoryData($pid);
1264         while(list($key, $value) = each ($new))
1265                 $real[$key] = $value;
1266         $real['id'] = "";
1267         // need to unset date, so can reset it below
1268         unset($real['date']);
1270         $arraySqlBind = array();
1271         $sql = "insert into history_data set `date` = NOW(), ";
1272         while(list($key, $value) = each($real)) {
1273                 array_push($arraySqlBind,$value);
1274                 $sql .= "`$key` = ?, ";
1275         }
1276         $sql = substr($sql, 0, -2);
1278         return sqlInsert($sql, $arraySqlBind );
1281 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1282                 $phone_biz,$phone_cell,$email,$pid="")
1284     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1285     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1287     $db = $GLOBALS['adodb']['db'];
1288     $customer_info = array();
1290     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1291     $result = $db->Execute($sql);
1292     if ($result && !$result->EOF) {
1293         $customer_info['foreign_update'] = true;
1294         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1295         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1296     }
1298     ///xml rpc code to connect to accounting package and add user to it
1299     $customer_info['firstname'] = $fname;
1300     $customer_info['lastname'] = $lname;
1301     $customer_info['address'] = $street;
1302     $customer_info['suburb'] = $city;
1303     $customer_info['state'] = $state;
1304     $customer_info['postcode'] = $postal_code;
1306     //ezybiz wants state as a code rather than abbreviation
1307     $customer_info['geo_zone_id'] = "";
1308     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1309     $db = $GLOBALS['adodb']['db'];
1310     $result = $db->Execute($sql);
1311     if ($result && !$result->EOF) {
1312         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1313     }
1315     //ezybiz wants country as a code rather than abbreviation
1316     $customer_info['geo_country_id'] = "";
1317     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1318     $db = $GLOBALS['adodb']['db'];
1319     $result = $db->Execute($sql);
1320     if ($result && !$result->EOF) {
1321         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1322     }
1324     $customer_info['phone1'] = $phone_home;
1325     $customer_info['phone1comment'] = "Home Phone";
1326     $customer_info['phone2'] = $phone_biz;
1327     $customer_info['phone2comment'] = "Business Phone";
1328     $customer_info['phone3'] = $phone_cell;
1329     $customer_info['phone3comment'] = "Cell Phone";
1330     $customer_info['email'] = $email;
1331     $customer_info['customernumber'] = $pid;
1333     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1334     $ws = new WSWrapper($function);
1336     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1337     if (is_numeric($ws->value)) {
1338         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1339         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1340     }
1343 // Returns Age 
1344 //   in months if < 2 years old
1345 //   in years  if > 2 years old
1346 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1347 // (optional) nowYMD is a date in YYYYMMDD format
1348 function getPatientAge($dobYMD, $nowYMD=null)
1350     // strip any dashes from the DOB
1351     $dobYMD = preg_replace("/-/", "", $dobYMD);
1352     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1353     
1354     // set the 'now' date values
1355     if ($nowYMD == null) {
1356         $nowDay = date("d");
1357         $nowMonth = date("m");
1358         $nowYear = date("Y");
1359     }
1360     else {
1361         $nowDay = substr($nowYMD,6,2);
1362         $nowMonth = substr($nowYMD,4,2);
1363         $nowYear = substr($nowYMD,0,4);
1364     }
1366     $dayDiff = $nowDay - $dobDay;
1367     $monthDiff = $nowMonth - $dobMonth;
1368     $yearDiff = $nowYear - $dobYear;
1370     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1372     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1373     if($dayDiff<0) { $ageInMonths-=1; } 
1374     
1375     if ( $ageInMonths > 24 ) {
1376         $age = $yearDiff;
1377         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1378         else if ($monthDiff < 0) { $age -= 1; }
1379     }
1380     else  {
1381         $age = "$ageInMonths month"; 
1382     }
1384     return $age;
1388  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1389  * format expected by getPatientAgeYMD
1391  * @param  string  $dob     date of birth
1392  * @param  string  $target  date to calculate age on
1393  * @return array containing
1394  *      age - decimal age in years
1395  *      age_in_months - decimal age in months
1396  *      ageinYMD - formatted string #y #m #d */
1397 function parseAgeInfo($dob,$target)
1399     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1400     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1401     // Prepare target (Y-M-D H:M:S)
1402     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1404     return getPatientAgeYMD($dateDOB,$dateTarget);
1409  * 
1410  * @param type $dob
1411  * @param type $date
1412  * @return array containing
1413  *      age - decimal age in years
1414  *      age_in_months - decimal age in months
1415  *      ageinYMD - formatted string #y #m #d
1416  */
1417 function getPatientAgeYMD($dob, $date=null) {
1418         
1419     if ($date == null) {
1420         $daynow = date("d");
1421         $monthnow = date("m");
1422         $yearnow = date("Y");
1423         $datenow=$yearnow.$monthnow.$daynow;
1424     }
1425     else {
1426         $datenow=preg_replace("/-/", "", $date);
1427         $yearnow=substr($datenow,0,4);
1428         $monthnow=substr($datenow,4,2);
1429         $daynow=substr($datenow,6,2);
1430         $datenow=$yearnow.$monthnow.$daynow;
1431     }
1433     $dob=preg_replace("/-/", "", $dob);
1434     $dobyear=substr($dob,0,4);
1435     $dobmonth=substr($dob,4,2);
1436     $dobday=substr($dob,6,2);
1437     $dob=$dobyear.$dobmonth.$dobday;
1439     //to compensate for 30, 31, 28, 29 days/month
1440     $mo=$monthnow; //to avoid confusion with later calculation
1442     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1443         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1444     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1445     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1446         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1447         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1448         else {$nd=28;} //otherwise, it is not a leap year.
1449     }
1450     else {$nd=31;} // other months have 31 days
1452     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1453     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1454     {
1455         $age_year = $yearnow - $dobyear - 1;
1456         if ($daynow < $dobday) {
1457             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1458             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1459         }
1460         else {
1461             $months_since_birthday=12 - $dobmonth + $monthnow;
1462             $days_since_dobday=$daynow - $dobday;
1463         }
1464     }
1465     else // if patient has had birthday this calandar year
1466     {
1467         $age_year = $yearnow - $dobyear;
1468         if ($daynow < $dobday) {
1469             $months_since_birthday=$monthnow - $dobmonth -1;
1470             $days_since_dobday=$nd - $dobday + $daynow;
1471         }
1472         else {
1473             $months_since_birthday=$monthnow - $dobmonth;
1474             $days_since_dobday=$daynow - $dobday;
1475         }       
1476     }
1477     
1478     $day_as_month_decimal = $days_since_dobday / 30;
1479     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1480     $month_as_year_decimal = $months_since_birthday_float / 12;
1481     $age_float = $age_year + $month_as_year_decimal;
1483     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1484     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1485     $age = round($age_float,2);
1487     // round the years to 2 floating points
1488     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1489     return compact('age','age_in_months','ageinYMD');
1492 // Returns Age in days
1493 //   in months if < 2 years old
1494 //   in years  if > 2 years old
1495 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1496 // (optional) nowYMD is a date in YYYYMMDD format
1497 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1498     $age = -1;
1500     // strip any dashes from the DOB
1501     $dobYMD = preg_replace("/-/", "", $dobYMD);
1502     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1503     
1504     // set the 'now' date values
1505     if ($nowYMD == null) {
1506         $nowDay = date("d");
1507         $nowMonth = date("m");
1508         $nowYear = date("Y");
1509     }
1510     else {
1511         $nowDay = substr($nowYMD,6,2);
1512         $nowMonth = substr($nowYMD,4,2);
1513         $nowYear = substr($nowYMD,0,4);
1514     }
1516     // do the date math
1517     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1518     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1519     $timediff = $nowtime - $dobtime;
1520     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1522     return $age;
1525  * Returns a string to be used to display a patient's age
1526  * 
1527  * @param type $dobYMD
1528  * @param type $asOfYMD
1529  * @return string suitable for displaying patient's age based on preferences
1530  */
1531 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1533     if($GLOBALS['age_display_format']=='1')
1534     {
1535         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1536         if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1537         {
1538             return $ageYMD['ageinYMD'];
1539         }
1540         else
1541         {
1542             return getPatientAge($dobYMD, $asOfYMD);                    
1543         }
1544     }
1545     else
1546     {
1547         return getPatientAge($dobYMD, $asOfYMD);
1548     }
1549     
1551 function dateToDB ($date)
1553     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1554     return $date;
1558 // ----------------------------------------------------------------------------
1560  * DROPDOWN FOR COUNTRIES
1561  * 
1562  * build a dropdown with all countries from geo_country_reference
1563  * 
1564  * @param int $selected - id for selected record
1565  * @param string $name - the name/id for select form
1566  * @return void - just echo the html encoded string
1567  */
1568 function dropdown_countries($selected = 0, $name = 'country_code') {
1569     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1571     $string = "<select name='$name' id='$name'>";
1572     while ( $row = sqlFetchArray($r) ) {
1573         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1574         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1575     }
1577     $string .= '</select>';
1578     echo $string;
1582 // ----------------------------------------------------------------------------
1584  * DROPDOWN FOR YES/NO
1585  * 
1586  * build a dropdown with two options (yes - 1, no - 0)
1587  * 
1588  * @param int $selected - id for selected record
1589  * @param string $name - the name/id for select form
1590  * @return void - just echo the html encoded string 
1591  */
1592 function dropdown_yesno($selected = 0, $name = 'yesno') {
1593     $string = "<select name='$name' id='$name'>";
1595     $selected = (int)$selected;
1596     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1597     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1599     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1600     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1601     $string .= '</select>';
1603     echo $string;
1606 // ----------------------------------------------------------------------------
1608  * DROPDOWN FOR MALE/FEMALE options
1609  * 
1610  * build a dropdown with three options (unselected/male/female)
1611  * 
1612  * @param int $selected - id for selected record
1613  * @param string $name - the name/id for select form
1614  * @return void - just echo the html encoded string
1615  */
1616 function dropdown_sex($selected = 0, $name = 'sex') {
1617     $string = "<select name='$name' id='$name'>";
1619     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1620     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1621     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1623     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1624     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1625     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1626     $string .= '</select>';
1628     echo $string;
1631 // ----------------------------------------------------------------------------
1633  * DROPDOWN FOR MARITAL STATUS
1634  * 
1635  * build a dropdown with marital status
1636  * 
1637  * @param int $selected - id for selected record
1638  * @param string $name - the name/id for select form
1639  * @return void - just echo the html encoded string
1640  */
1641 function dropdown_marital($selected = 0, $name = 'status') {
1642     $string = "<select name='$name' id='$name'>";
1644     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1646     foreach ( $statii as $st ) {
1647         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1648         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1649     }
1651     $string .= '</select>';
1653     echo $string;
1656 // ----------------------------------------------------------------------------
1658  * DROPDOWN FOR PROVIDERS
1659  * 
1660  * build a dropdown with all providers
1661  * 
1662  * @param int $selected - id for selected record
1663  * @param string $name - the name/id for select form
1664  * @return void - just echo the html encoded string
1665  */
1666 function dropdown_providers($selected = 0, $name = 'status') {
1667     $provideri = getProviderInfo();
1669     $string = "<select name='$name' id='$name'>";
1670     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1671     foreach ( $provideri as $s ) {
1672         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1673         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1674     }
1676     $string .= '</select>';
1678     echo $string;
1681 // ----------------------------------------------------------------------------
1683  * DROPDOWN FOR INSURANCE COMPANIES
1684  * 
1685  * build a dropdown with all insurers
1686  * 
1687  * @param int $selected - id for selected record
1688  * @param string $name - the name/id for select form
1689  * @return void - just echo the html encoded string
1690  */
1691 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1692     $insurancei = getInsuranceProviders();
1694     $string = "<select name='$name' id='$name'>";
1695     $string .= '<option value="0">Onbekend</option>';
1696     foreach ( $insurancei as $iid => $iname ) {
1697         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1698         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1699     }
1701     $string .= '</select>';
1703     echo $string;
1707 // ----------------------------------------------------------------------------
1709  * COUNTRY CODE
1710  * 
1711  * return the name or the country code, function of arguments
1712  * 
1713  * @param int $country_code
1714  * @param string $country_name
1715  * @return string | int - name or code
1716  */
1717 function country_code($country_code = 0, $country_name = '') {
1718     $strint = '';
1719     if ( $country_code ) {
1720         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1721     } else {
1722         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1723     }
1725     $db = $GLOBALS['adodb']['db'];
1726     $result = $db->Execute($sql);
1727     if ($result && !$result->EOF) {
1728         $strint = $result->fields['res'];
1729     }
1731     return $strint;
1734 function DBToDate ($date)
1736     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1737     return $date;
1741  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1742  * for the given patient on the given date.
1744  * @param int     The PID of the patient.
1745  * @param string  Date in yyyy-mm-dd format.
1746  * @return array  Array of 0-3 insurance_data rows.
1747  */
1748 function getEffectiveInsurances($patient_id, $encdate) {
1749   $insarr = array();
1750   foreach (array('primary','secondary','tertiary') as $instype) {
1751     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1752       "WHERE pid = ? AND type = ? " .
1753       "AND date <= ? ORDER BY date DESC LIMIT 1",
1754       array($patient_id, $instype, $encdate));
1755     if (empty($tmp['provider'])) break;
1756     $insarr[] = $tmp;
1757   }
1758   return $insarr;
1762  * Get the patient's balance due. Normally this excludes amounts that are out
1763  * to insurance.  If you want to include what insurance owes, set the second
1764  * parameter to true.
1766  * @param int     The PID of the patient.
1767  * @param boolean Indicates if amounts owed by insurance are to be included.
1768  * @return number The balance.
1769  */
1770 function get_patient_balance($pid, $with_insurance=false) {
1771   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1772     $balance = 0;
1773     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1774       "last_level_closed, stmt_count " .
1775       "FROM form_encounter WHERE pid = ?", array($pid));
1776     while ($ferow = sqlFetchArray($feres)) {
1777       $encounter = $ferow['encounter'];
1778       $dos = substr($ferow['date'], 0, 10);
1779       $insarr = getEffectiveInsurances($pid, $dos);
1780       $inscount = count($insarr);
1781       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1782         // It's out to insurance so only the co-pay might be due.
1783         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1784           "pid = ? AND encounter = ? AND " .
1785           "code_type = 'copay' AND activity = 1",
1786           array($pid, $encounter));
1787         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1788           "FROM ar_activity WHERE " .
1789           "pid = ? AND encounter = ? AND payer_type = 0",
1790           array($pid, $encounter));
1791         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1792         if ($ptbal > 0) $balance += $ptbal;
1793       }
1794       else {
1795         // Including insurance or not out to insurance, everything is due.
1796         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1797           "pid = ? AND encounter = ? AND " .
1798           "activity = 1", array($pid, $encounter));
1799         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1800           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1801           "pid = ? AND encounter = ?", array($pid, $encounter));
1802         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1803           "pid = ? AND encounter = ?", array($pid, $encounter));
1804         $balance += $brow['amount'] + $srow['amount']
1805           - $drow['payments'] - $drow['adjustments'];
1806       }
1807     }
1808     return sprintf('%01.2f', $balance);
1809   }
1810   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1811     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1812     $conn = $GLOBALS['adodb']['db'];
1813     $customer_info['id'] = 0;
1814     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1815       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1816       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1817       "im.foreign_table = 'customer'";
1818     $result = $conn->Execute($sql);
1819     if($result && !$result->EOF) {
1820       $customer_info['id'] = $result->fields['foreign_id'];
1821     }
1822     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1823     $ws = new WSWrapper($function);
1824     if(is_numeric($ws->value)) {
1825       return sprintf('%01.2f', $ws->value);
1826     }
1827   }
1828   return '';
1831 // Function to check if patient is deceased.
1832 //  Param:
1833 //    $pid  - patient id
1834 //    $date - date checking if deceased (will default to current date if blank)
1835 //  Return:
1836 //    If deceased, then will return the number of
1837 //      days that patient has been deceased.
1838 //    If not deceased, then will return false.
1839 function is_patient_deceased($pid,$date='') {
1841   // Set date to current if not set
1842   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1844   // Query for deceased status (gets days deceased if patient is deceased)
1845   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1846                       "FROM `patient_data` " .
1847                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1849   if (empty($results)) {
1850     // Patient is alive, so return false
1851     return false;
1852   }
1853   else {
1854     // Patient is dead, so return the number of days patient has been deceased.
1855     //  Don't let it be zero days or else will confuse calls to this function.
1856     if ($results['days_deceased'] === 0) {
1857       $results['days_deceased'] = 1;
1858     }
1859     return $results['days_deceased'];
1860   }