prepping ubuntu packages
[openemr.git] / library / patient.inc
blob1dbf67281d07cb5087e7dcb28c7a72e842705321
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     }
391     return $res;
394 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
395 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
397   $sql = "select $given from insurance_data as insd " .
398     "left join insurance_companies as ic on ic.id = insd.provider " .
399     "where pid = ? and type = ? order by date DESC limit 1";
400   return sqlQuery($sql, array($pid, $type) );
403 function getInsuranceDataByDate($pid, $date, $type,
404   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
405 { // this must take the date in the following manner: YYYY-MM-DD
406   // this function recalls the insurance value that was most recently enterred from the
407   // given date. it will call up most recent records up to and on the date given,
408   // but not records enterred after the given date
409   $sql = "select $given from insurance_data as insd " .
410     "left join insurance_companies as ic on ic.id = provider " .
411     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
412     "type=? order by date DESC limit 1";
413   return sqlQuery($sql, array($pid,$date,$type) );
416 function getEmployerData($pid, $given = "*")
418     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
419     return sqlQuery($sql, array($pid) );
422 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
423   // When the limit is exceeded, find out what the unlimited count would be.
424   $GLOBALS['PATIENT_INC_COUNT'] = $count;
425   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
426   if ($limit != "all") {
427     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
428     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
429   }
433  * Allow the last name to be followed by a comma and some part of a first name(can
434  *   also place middle name after the first name with a space separating them)
435  * Allows comma alone followed by some part of a first name(can also place middle name
436  *   after the first name with a space separating them).
437  * Allows comma alone preceded by some part of a last name.
438  * If no comma or space, then will search both last name and first name.
439  * If the first letter of either name is capital, searches for name starting
440  *   with given substring (the expected behavior). If it is lower case, it
441  *   searches for the substring anywhere in the name. This applies to either
442  *   last name, first name, and middle name.
443  * Also allows first name followed by middle and/or last name when separated by spaces.
444  * @param string $term
445  * @param string $given
446  * @param string $orderby
447  * @param string $limit
448  * @param string $start
449  * @return array
450  */
451 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")
453     $names = getPatientNameSplit($term);
454     
455     foreach ($names as $key => $val) {
456       if (!empty($val)) {
457         if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
458             $names[$key] = '%' . $val . '%';            
459         } else { 
460             $names[$key] = $val . '%';            
461         }
462       }
463     }
465     // Debugging section below
466     //if(array_key_exists('first',$names)) {
467     //    error_log("first name search term :".$names['first']);
468     //}
469     //if(array_key_exists('middle',$names)) {
470     //    error_log("middle name search term :".$names['middle']);
471     //}
472     //if(array_key_exists('last',$names)) {
473     //    error_log("last name search term :".$names['last']);
474     //}
475     // Debugging section above
477     $sqlBindArray = array();
478     if(array_key_exists('last',$names) && $names['last'] == '') {
479         // Do not search last name
480         $where = "fname LIKE ? ";
481         array_push($sqlBindArray, $names['first']);
482         if ($names['middle'] != '') {        
483             $where .= "AND mname LIKE ? ";  
484             array_push($sqlBindArray, $names['middle']);
485         }
486     } elseif(array_key_exists('first',$names) && $names['first'] == '') {
487         // Do not search first name or middle name
488         $where = "lname LIKE ? ";
489         array_push($sqlBindArray, $names['last']);
490     } elseif($names['first'] == '' && $names['last'] != '') {
491         // Search both first name and last name with same term
492         $names['first'] = $names['last']; 
493         $where = "lname LIKE ? OR fname LIKE ? ";
494         array_push($sqlBindArray, $names['last'], $names['first']);
495     } elseif ($names['middle'] != '') {        
496         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";  
497         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
498     } else {
499         $where = "lname LIKE ? AND fname LIKE ? ";
500         array_push($sqlBindArray, $names['last'], $names['first']);
501     }
503         if (!empty($GLOBALS['pt_restrict_field'])) {
504                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
505                         $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
506                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
507                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
508                         array_push($sqlBindArray, $_SESSION{"authUser"});
509                 }
510         }
512     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
513     if ($limit != "all") $sql .= " LIMIT $start, $limit";
515     $rez = sqlStatement($sql, $sqlBindArray);
517     $returnval=array();
518     for($iter=0; $row=sqlFetchArray($rez); $iter++)
519         $returnval[$iter] = $row;
521     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
522     return $returnval;
525  * Accept a string used by a search function expected to find a patient name, 
526  * then split up the string if a comma or space exists. Return an array having 
527  * from 1 to 3 elements, named first, middle, and last.
528  * See above getPatientLnames() function for details on how the splitting occurs.
529  * @param string $term
530  * @return array
531  */
532 function getPatientNameSplit($term) {
533     $term = trim($term);
534     if (strpos($term, ',') !== false) {
535         $names = explode(',', $term);        
536         $n['last'] = $names[0];
537         if (strpos(trim($names[1]), ' ') !== false) {
538             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
539         } else {
540             $n['first'] = $names[1];
541         }
542     } elseif (strpos($term, ' ') !== false) {
543         $names = explode(' ', $term);
544         if (count($names) == 1) {
545             $n['last'] = $names[0];
546         } elseif (count($names) == 3) {
547             $n['first'] = $names[0];
548             $n['middle'] = $names[1];
549             $n['last'] = $names[2];
550         } else {
551             // This will handle first and last name or first followed by 
552             // multiple names only using just the last of the names in the list.
553             $n['first'] = $names[0];
554             $n['last'] = end($names);
555         }
556     } else {
557         $n['last'] = $term;       
558     }
559     // Trim whitespace off the names before returning
560     foreach($n as $key => $val) {
561         $n[$key] = trim($val);
562     }
563     return $n; // associative array containing names
566 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")
569     $sqlBindArray = array();
570     $where = "pubpid LIKE ? ";
571     array_push($sqlBindArray, $pid."%");
572         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
573                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
574                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
575                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
576                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
577                         array_push($sqlBindArray, $_SESSION{"authUser"});
578                 }
579         }
581     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
582     if ($limit != "all") $sql .= " limit $start, $limit";
583     $rez = sqlStatement($sql, $sqlBindArray);
584     for($iter=0; $row=sqlFetchArray($rez); $iter++)
585         $returnval[$iter]=$row;
587     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
588     return $returnval;
591 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")
593   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
595   $sqlBindArray = array();
596   $where = "";
597   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
598     if ( $iter > 0 ) {
599       $where .= " or ";
600     }
601     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
602     array_push($sqlBindArray, "%".$searchTerm."%");
603   }
605   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
606   if ($limit != "all") $sql .= " limit $start, $limit";
607   $rez = sqlStatement($sql, $sqlBindArray);
608   for($iter=0; $row=sqlFetchArray($rez); $iter++)
609     $returnval[$iter]=$row;
610   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
611   return $returnval;
614 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
615   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
616   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
618         $layoutCols = explode( '~', $searchFields );
619   $sqlBindArray = array();
620   $where = "";
621   $i = 0;
622   foreach ($layoutCols as $val) {
623     if (empty($val)) continue;
624                 if ( $i > 0 ) {
625                    $where .= " or ";
626                 }
627     if ($val == 'pid') {
628                 $where .= " ".add_escape_custom($val)." = ? ";
629                 array_push($sqlBindArray, $searchTerm);
630     }
631     else {
632                 $where .= " ".add_escape_custom($val)." like ? ";
633                 array_push($sqlBindArray, $searchTerm."%");
634     }
635                 $i++;
636         }
638   // If no search terms, ensure valid syntax.
639   if ($i == 0) $where = "1 = 1";
641   // If a non-empty service code was given, then restrict to patients who
642   // have been provided that service.  Since the code is used in a LIKE
643   // clause, % and _ wildcards are supported.
644   if ($search_service_code) {
645     $where = "( $where ) AND " .
646       "( SELECT COUNT(*) FROM billing AS b WHERE " .
647       "b.pid = patient_data.pid AND " .
648       "b.activity = 1 AND " .
649       "b.code_type != 'COPAY' AND " .
650       "b.code LIKE ? " .
651       ") > 0";
652     array_push($sqlBindArray, $search_service_code);
653   }
655   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
656   if ($limit != "all") $sql .= " limit $start, $limit";
657   $rez = sqlStatement($sql, $sqlBindArray);
658   for($iter=0; $row=sqlFetchArray($rez); $iter++)
659       $returnval[$iter]=$row;
660   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
661   return $returnval;
664 // return a collection of Patient PIDs
665 // new arg style by JRM March 2008
666 // 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")
667 function getPatientPID($args)
669     $pid = "%";
670     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
671     $orderby = "lname ASC, fname ASC";
672     $limit="all";
673     $start="0";
675     // alter default values if defined in the passed in args
676     if (isset($args['pid'])) { $pid = $args['pid']; }
677     if (isset($args['given'])) { $given = $args['given']; }
678     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
679     if (isset($args['limit'])) { $limit = $args['limit']; }
680     if (isset($args['start'])) { $start = $args['start']; }
682     $command = "=";
683     if ($pid == -1) $pid = "%";
684     elseif (empty($pid)) $pid = "NULL";
686     if (strstr($pid,"%")) $command = "like";
688     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
689     if ($limit != "all") $sql .= " limit $start, $limit";
691     $rez = sqlStatement($sql);
692     for($iter=0; $row=sqlFetchArray($rez); $iter++)
693         $returnval[$iter]=$row;
695     return $returnval;
698 /* return a patient's name in the format LAST, FIRST */
699 function getPatientName($pid) {
700     if (empty($pid)) return "";
701     $patientData = getPatientPID(array("pid"=>$pid));
702     if (empty($patientData[0]['lname'])) return "";
703     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
704     return $patientName;
707 /* find patient data by DOB */
708 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
710     $DOB = fixDate($DOB, $DOB);
711     $sqlBindArray = array();
712     $where = "DOB like ? ";
713     array_push($sqlBindArray, $DOB."%");
714         if (!empty($GLOBALS['pt_restrict_field'])) {
715                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
716                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
717                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
718                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
719                         array_push($sqlBindArray, $_SESSION{"authUser"});
720                 }
721         }
723     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
725     if ($limit != "all") $sql .= " LIMIT $start, $limit";
727     $rez = sqlStatement($sql, $sqlBindArray);
728     for($iter=0; $row=sqlFetchArray($rez); $iter++)
729         $returnval[$iter]=$row;
731     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
732     return $returnval;
735 /* find patient data by SSN */
736 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
738     $sqlBindArray = array();
739     $where = "ss LIKE ?";
740     array_push($sqlBindArray, $ss."%");
741     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
742     if ($limit != "all") $sql .= " LIMIT $start, $limit";
744     $rez = sqlStatement($sql, $sqlBindArray);
745     for($iter=0; $row=sqlFetchArray($rez); $iter++)
746         $returnval[$iter]=$row;
748     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
749     return $returnval;
752 //(CHEMED) Search by phone number
753 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
755     $phone = preg_replace( "/[[:punct:]]/","", $phone );
756     $sqlBindArray = array();
757     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
758     array_push($sqlBindArray, $phone);
759     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
760     if ($limit != "all") $sql .= " LIMIT $start, $limit";
762     $rez = sqlStatement($sql, $sqlBindArray);
763     for($iter=0; $row=sqlFetchArray($rez); $iter++)
764         $returnval[$iter]=$row;
766     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
767     return $returnval;
770 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
772     $sql="select $given from patient_data order by $orderby";
774     if ($limit != "all")
775         $sql .= " limit $start, $limit";
777     $rez = sqlStatement($sql);
778     for($iter=0; $row=sqlFetchArray($rez); $iter++)
779         $returnval[$iter]=$row;
781     return $returnval;
784 //----------------------input functions
785 function newPatientData(    $db_id="",
786                 $title = "",
787                 $fname = "",
788                 $lname = "",
789                 $mname = "",
790                 $sex = "",
791                 $DOB = "",
792                 $street = "",
793                 $postal_code = "",
794                 $city = "",
795                 $state = "",
796                 $country_code = "",
797                 $ss = "",
798                 $occupation = "",
799                 $phone_home = "",
800                 $phone_biz = "",
801                 $phone_contact = "",
802                 $status = "",
803                 $contact_relationship = "",
804                 $referrer = "",
805                 $referrerID = "",
806                 $email = "",
807                 $language = "",
808                 $ethnoracial = "",
809                 $interpretter = "",
810                 $migrantseasonal = "",
811                 $family_size = "",
812                 $monthly_income = "",
813                 $homeless = "",
814                 $financial_review = "",
815                 $pubpid = "",
816                 $pid = "MAX(pid)+1",
817                 $providerID = "",
818                 $genericname1 = "",
819                 $genericval1 = "",
820                 $genericname2 = "",
821                 $genericval2 = "",
822                 $billing_note="",
823                 $phone_cell = "",
824                 $hipaa_mail = "",
825                 $hipaa_voice = "",
826                 $squad = 0,
827                 $pharmacy_id = 0,
828                 $drivers_license = "",
829                 $hipaa_notice = "",
830                 $hipaa_message = "",
831                 $regdate = ""
832             )
834     $DOB = fixDate($DOB);
835     $regdate = fixDate($regdate);
837     $fitness = 0;
838     $referral_source = '';
839     if ($pid) {
840         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
841         // Check for brain damage:
842         if ($db_id != $rez['id']) {
843             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
844               $rez['id'] . "' to '$db_id' for pid '$pid'";
845             die($errmsg);
846         }
847         $fitness = $rez['fitness'];
848         $referral_source = $rez['referral_source'];
849     }
851     // Get the default price level.
852     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
853       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
854     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
856     $query = ("replace into patient_data set
857         id='$db_id',
858         title='$title',
859         fname='$fname',
860         lname='$lname',
861         mname='$mname',
862         sex='$sex',
863         DOB='$DOB',
864         street='$street',
865         postal_code='$postal_code',
866         city='$city',
867         state='$state',
868         country_code='$country_code',
869         drivers_license='$drivers_license',
870         ss='$ss',
871         occupation='$occupation',
872         phone_home='$phone_home',
873         phone_biz='$phone_biz',
874         phone_contact='$phone_contact',
875         status='$status',
876         contact_relationship='$contact_relationship',
877         referrer='$referrer',
878         referrerID='$referrerID',
879         email='$email',
880         language='$language',
881         ethnoracial='$ethnoracial',
882         interpretter='$interpretter',
883         migrantseasonal='$migrantseasonal',
884         family_size='$family_size',
885         monthly_income='$monthly_income',
886         homeless='$homeless',
887         financial_review='$financial_review',
888         pubpid='$pubpid',
889         pid = $pid,
890         providerID = '$providerID',
891         genericname1 = '$genericname1',
892         genericval1 = '$genericval1',
893         genericname2 = '$genericname2',
894         genericval2 = '$genericval2',
895         billing_note= '$billing_note';
896         phone_cell = '$phone_cell',
897         pharmacy_id = '$pharmacy_id',
898         hipaa_mail = '$hipaa_mail',
899         hipaa_voice = '$hipaa_voice',
900         hipaa_notice = '$hipaa_notice',
901         hipaa_message = '$hipaa_message',
902         squad = '$squad',
903         fitness='$fitness',
904         referral_source='$referral_source',
905         regdate='$regdate',
906         pricelevel='$pricelevel',
907         date=NOW()");
909     $id = sqlInsert($query);
911     if ( !$db_id ) {
912       // find the last inserted id for new patient case
913       $db_id = getSqlLastID();
914     }
916     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
918     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
919                 $phone_biz,$phone_cell,$email,$pid);
921     return $foo['pid'];
924 // Supported input date formats are:
925 //   mm/dd/yyyy
926 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
927 //   yyyy/mm/dd
928 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
930 function fixDate($date, $default="0000-00-00") {
931     $fixed_date = $default;
932     $date = trim($date);
933     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
934         $dmy = preg_split("'[/.-]'", $date);
935         if ($dmy[0] > 99) {
936             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
937         } else {
938             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
939               if ($dmy[2] < 1000) $dmy[2] += 1900;
940               if ($dmy[2] < 1910) $dmy[2] += 100;
941             }
942             // phone_country_code indicates format of ambiguous input dates.
943             if ($GLOBALS['phone_country_code'] == 1)
944               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
945             else
946               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
947         }
948     }
950     return $fixed_date;
953 function pdValueOrNull($key, $value) {
954   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
955     substr($key, 0, 8) == 'userdate') &&
956     (empty($value) || $value == '0000-00-00'))
957   {
958     return "NULL";
959   }
960   else {
961     return "'$value'";
962   }
965 // Create or update patient data from an array.
967 function updatePatientData($pid, $new, $create=false)
969   /*******************************************************************
970     $real = getPatientData($pid);
971     $new['DOB'] = fixDate($new['DOB']);
972     while(list($key, $value) = each ($new))
973         $real[$key] = $value;
974     $real['date'] = "'+NOW()+'";
975     $real['id'] = "";
976     $sql = "insert into patient_data set ";
977     while(list($key, $value) = each($real))
978         $sql .= $key." = '$value', ";
979     $sql = substr($sql, 0, -2);
980     return sqlInsert($sql);
981   *******************************************************************/
983   // The above was broken, though seems intent to insert a new patient_data
984   // row for each update.  A good idea, but nothing is doing that yet so
985   // the code below does not yet attempt it.
987   $new['DOB'] = fixDate($new['DOB']);
989   if ($create) {
990     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
991     foreach ($new as $key => $value) {
992       if ($key == 'id') continue;
993       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
994     }
995     $db_id = sqlInsert($sql);
996   }
997   else {
998     $db_id = $new['id'];
999     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
1000     // Check for brain damage:
1001     if ($pid != $rez['pid']) {
1002       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1003         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
1004       die($errmsg);
1005     }
1006     $sql = "UPDATE patient_data SET date = NOW()";
1007     foreach ($new as $key => $value) {
1008       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1009     }
1010     $sql .= " WHERE id = '$db_id'";
1011     sqlStatement($sql);
1012   }
1014   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
1015   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
1016     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
1017     $rez['phone_cell'],$rez['email'],$rez['pid']);
1019   return $db_id;
1022 function newEmployerData(    $pid,
1023                 $name = "",
1024                 $street = "",
1025                 $postal_code = "",
1026                 $city = "",
1027                 $state = "",
1028                 $country = ""
1029             )
1031     return sqlInsert("insert into employer_data set
1032         name='$name',
1033         street='$street',
1034         postal_code='$postal_code',
1035         city='$city',
1036         state='$state',
1037         country='$country',
1038         pid='$pid',
1039         date=NOW()
1040         ");
1043 // Create or update employer data from an array.
1045 function updateEmployerData($pid, $new, $create=false)
1047   $colnames = array('name','street','city','state','postal_code','country');
1049   if ($create) {
1050     $set .= "pid = '$pid', date = NOW()";
1051     foreach ($colnames as $key) {
1052       $value = isset($new[$key]) ? $new[$key] : '';
1053       $set .= ", `$key` = '$value'";
1054     }
1055     return sqlInsert("INSERT INTO employer_data SET $set");
1056   }
1057   else {
1058     $set = '';
1059     $old = getEmployerData($pid);
1060     $modified = false;
1061     foreach ($colnames as $key) {
1062       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1063       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1064         $value = $new[$key];
1065         $modified = true;
1066       }
1067       $set .= "`$key` = '$value', ";
1068     }
1069     if ($modified) {
1070       $set .= "pid = '$pid', date = NOW()";
1071       return sqlInsert("INSERT INTO employer_data SET $set");
1072     }
1073     return $old['id'];
1074   }
1077 // This updates or adds the given insurance data info, while retaining any
1078 // previously added insurance_data rows that should be preserved.
1079 // This does not directly support the maintenance of non-current insurance.
1081 function newInsuranceData(
1082   $pid,
1083   $type = "",
1084   $provider = "",
1085   $policy_number = "",
1086   $group_number = "",
1087   $plan_name = "",
1088   $subscriber_lname = "",
1089   $subscriber_mname = "",
1090   $subscriber_fname = "",
1091   $subscriber_relationship = "",
1092   $subscriber_ss = "",
1093   $subscriber_DOB = "",
1094   $subscriber_street = "",
1095   $subscriber_postal_code = "",
1096   $subscriber_city = "",
1097   $subscriber_state = "",
1098   $subscriber_country = "",
1099   $subscriber_phone = "",
1100   $subscriber_employer = "",
1101   $subscriber_employer_street = "",
1102   $subscriber_employer_city = "",
1103   $subscriber_employer_postal_code = "",
1104   $subscriber_employer_state = "",
1105   $subscriber_employer_country = "",
1106   $copay = "",
1107   $subscriber_sex = "",
1108   $effective_date = "0000-00-00",
1109   $accept_assignment = "TRUE",
1110   $policy_type = "")
1112   if (strlen($type) <= 0) return FALSE;
1114   // If a bad date was passed, err on the side of caution.
1115   $effective_date = fixDate($effective_date, date('Y-m-d'));
1117   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1118     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1119   $idrow = sqlFetchArray($idres);
1121   // Replace the most recent entry in any of the following cases:
1122   // * Its effective date is >= this effective date.
1123   // * It is the first entry and it has no (insurance) provider.
1124   // * There is no encounter that is earlier than the new effective date but
1125   //   on or after the old effective date.
1126   // Otherwise insert a new entry.
1128   $replace = false;
1129   if ($idrow) {
1130     if (strcmp($idrow['date'], $effective_date) > 0) {
1131       $replace = true;
1132     }
1133     else {
1134       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1135         $replace = true;
1136       }
1137       else {
1138         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1139           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1140           "date >= '" . $idrow['date'] . " 00:00:00'");
1141         if ($ferow['count'] == 0) $replace = true;
1142       }
1143     }
1144   }
1146   if ($replace) {
1148     // TBD: This is a bit dangerous in that a typo in entering the effective
1149     // date can wipe out previous insurance history.  So we want some data
1150     // entry validation somewhere.
1151     sqlStatement("DELETE FROM insurance_data WHERE " .
1152       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1153       "id != " . $idrow['id']);
1155     $data = array();
1156     $data['type'] = $type;
1157     $data['provider'] = $provider;
1158     $data['policy_number'] = $policy_number;
1159     $data['group_number'] = $group_number;
1160     $data['plan_name'] = $plan_name;
1161     $data['subscriber_lname'] = $subscriber_lname;
1162     $data['subscriber_mname'] = $subscriber_mname;
1163     $data['subscriber_fname'] = $subscriber_fname;
1164     $data['subscriber_relationship'] = $subscriber_relationship;
1165     $data['subscriber_ss'] = $subscriber_ss;
1166     $data['subscriber_DOB'] = $subscriber_DOB;
1167     $data['subscriber_street'] = $subscriber_street;
1168     $data['subscriber_postal_code'] = $subscriber_postal_code;
1169     $data['subscriber_city'] = $subscriber_city;
1170     $data['subscriber_state'] = $subscriber_state;
1171     $data['subscriber_country'] = $subscriber_country;
1172     $data['subscriber_phone'] = $subscriber_phone;
1173     $data['subscriber_employer'] = $subscriber_employer;
1174     $data['subscriber_employer_city'] = $subscriber_employer_city;
1175     $data['subscriber_employer_street'] = $subscriber_employer_street;
1176     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1177     $data['subscriber_employer_state'] = $subscriber_employer_state;
1178     $data['subscriber_employer_country'] = $subscriber_employer_country;
1179     $data['copay'] = $copay;
1180     $data['subscriber_sex'] = $subscriber_sex;
1181     $data['pid'] = $pid;
1182     $data['date'] = $effective_date;
1183     $data['accept_assignment'] = $accept_assignment;
1184     $data['policy_type'] = $policy_type;
1185     updateInsuranceData($idrow['id'], $data);
1186     return $idrow['id'];
1187   }
1188   else {
1189     return sqlInsert("INSERT INTO insurance_data SET
1190       type = '$type',
1191       provider = '$provider',
1192       policy_number = '$policy_number',
1193       group_number = '$group_number',
1194       plan_name = '$plan_name',
1195       subscriber_lname = '$subscriber_lname',
1196       subscriber_mname = '$subscriber_mname',
1197       subscriber_fname = '$subscriber_fname',
1198       subscriber_relationship = '$subscriber_relationship',
1199       subscriber_ss = '$subscriber_ss',
1200       subscriber_DOB = '$subscriber_DOB',
1201       subscriber_street = '$subscriber_street',
1202       subscriber_postal_code = '$subscriber_postal_code',
1203       subscriber_city = '$subscriber_city',
1204       subscriber_state = '$subscriber_state',
1205       subscriber_country = '$subscriber_country',
1206       subscriber_phone = '$subscriber_phone',
1207       subscriber_employer = '$subscriber_employer',
1208       subscriber_employer_city = '$subscriber_employer_city',
1209       subscriber_employer_street = '$subscriber_employer_street',
1210       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1211       subscriber_employer_state = '$subscriber_employer_state',
1212       subscriber_employer_country = '$subscriber_employer_country',
1213       copay = '$copay',
1214       subscriber_sex = '$subscriber_sex',
1215       pid = '$pid',
1216       date = '$effective_date',
1217       accept_assignment = '$accept_assignment',
1218       policy_type = '$policy_type'
1219     ");
1220   }
1223 // This is used internally only.
1224 function updateInsuranceData($id, $new)
1226   $fields = sqlListFields("insurance_data");
1227   $use = array();
1229   while(list($key, $value) = each ($new)) {
1230     if (in_array($key, $fields)) {
1231       $use[$key] = $value;
1232     }
1233   }
1235   $sql = "UPDATE insurance_data SET ";
1236   while(list($key, $value) = each($use))
1237     $sql .= "`$key` = '$value', ";
1238   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1240   sqlStatement($sql);
1243 function newHistoryData($pid, $new=false) {
1244   $arraySqlBind = array();
1245   $sql = "insert into history_data set pid = ?, date = NOW()";
1246   array_push($arraySqlBind,$pid);
1247   if ($new) {
1248     while(list($key, $value) = each($new)) {
1249       array_push($arraySqlBind,$value);
1250       $sql .= ", `$key` = ?";
1251     }
1252   }
1253   return sqlInsert($sql, $arraySqlBind );
1256 function updateHistoryData($pid,$new)
1258         $real = getHistoryData($pid);
1259         while(list($key, $value) = each ($new))
1260                 $real[$key] = $value;
1261         $real['id'] = "";
1262         // need to unset date, so can reset it below
1263         unset($real['date']);
1265         $arraySqlBind = array();
1266         $sql = "insert into history_data set `date` = NOW(), ";
1267         while(list($key, $value) = each($real)) {
1268                 array_push($arraySqlBind,$value);
1269                 $sql .= "`$key` = ?, ";
1270         }
1271         $sql = substr($sql, 0, -2);
1273         return sqlInsert($sql, $arraySqlBind );
1276 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1277                 $phone_biz,$phone_cell,$email,$pid="")
1279     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1280     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1282     $db = $GLOBALS['adodb']['db'];
1283     $customer_info = array();
1285     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1286     $result = $db->Execute($sql);
1287     if ($result && !$result->EOF) {
1288         $customer_info['foreign_update'] = true;
1289         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1290         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1291     }
1293     ///xml rpc code to connect to accounting package and add user to it
1294     $customer_info['firstname'] = $fname;
1295     $customer_info['lastname'] = $lname;
1296     $customer_info['address'] = $street;
1297     $customer_info['suburb'] = $city;
1298     $customer_info['state'] = $state;
1299     $customer_info['postcode'] = $postal_code;
1301     //ezybiz wants state as a code rather than abbreviation
1302     $customer_info['geo_zone_id'] = "";
1303     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1304     $db = $GLOBALS['adodb']['db'];
1305     $result = $db->Execute($sql);
1306     if ($result && !$result->EOF) {
1307         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1308     }
1310     //ezybiz wants country as a code rather than abbreviation
1311     $customer_info['geo_country_id'] = "";
1312     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1313     $db = $GLOBALS['adodb']['db'];
1314     $result = $db->Execute($sql);
1315     if ($result && !$result->EOF) {
1316         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1317     }
1319     $customer_info['phone1'] = $phone_home;
1320     $customer_info['phone1comment'] = "Home Phone";
1321     $customer_info['phone2'] = $phone_biz;
1322     $customer_info['phone2comment'] = "Business Phone";
1323     $customer_info['phone3'] = $phone_cell;
1324     $customer_info['phone3comment'] = "Cell Phone";
1325     $customer_info['email'] = $email;
1326     $customer_info['customernumber'] = $pid;
1328     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1329     $ws = new WSWrapper($function);
1331     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1332     if (is_numeric($ws->value)) {
1333         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1334         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1335     }
1338 // Returns Age 
1339 //   in months if < 2 years old
1340 //   in years  if > 2 years old
1341 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1342 // (optional) nowYMD is a date in YYYYMMDD format
1343 function getPatientAge($dobYMD, $nowYMD=null)
1345     // strip any dashes from the DOB
1346     $dobYMD = preg_replace("/-/", "", $dobYMD);
1347     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1348     
1349     // set the 'now' date values
1350     if ($nowYMD == null) {
1351         $nowDay = date("d");
1352         $nowMonth = date("m");
1353         $nowYear = date("Y");
1354     }
1355     else {
1356         $nowDay = substr($nowYMD,6,2);
1357         $nowMonth = substr($nowYMD,4,2);
1358         $nowYear = substr($nowYMD,0,4);
1359     }
1361     $dayDiff = $nowDay - $dobDay;
1362     $monthDiff = $nowMonth - $dobMonth;
1363     $yearDiff = $nowYear - $dobYear;
1365     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1367     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1368     if($dayDiff<0) { $ageInMonths-=1; } 
1369     
1370     if ( $ageInMonths > 24 ) {
1371         $age = $yearDiff;
1372         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1373         else if ($monthDiff < 0) { $age -= 1; }
1374     }
1375     else  {
1376         $age = "$ageInMonths month"; 
1377     }
1379     return $age;
1383  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1384  * format expected by getPatientAgeYMD
1386  * @param  string  $dob     date of birth
1387  * @param  string  $target  date to calculate age on
1388  * @return array containing
1389  *      age - decimal age in years
1390  *      age_in_months - decimal age in months
1391  *      ageinYMD - formatted string #y #m #d */
1392 function parseAgeInfo($dob,$target)
1394     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1395     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1396     // Prepare target (Y-M-D H:M:S)
1397     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1399     return getPatientAgeYMD($dateDOB,$dateTarget);
1404  * 
1405  * @param type $dob
1406  * @param type $date
1407  * @return array containing
1408  *      age - decimal age in years
1409  *      age_in_months - decimal age in months
1410  *      ageinYMD - formatted string #y #m #d
1411  */
1412 function getPatientAgeYMD($dob, $date=null) {
1413         
1414     if ($date == null) {
1415         $daynow = date("d");
1416         $monthnow = date("m");
1417         $yearnow = date("Y");
1418         $datenow=$yearnow.$monthnow.$daynow;
1419     }
1420     else {
1421         $datenow=preg_replace("/-/", "", $date);
1422         $yearnow=substr($datenow,0,4);
1423         $monthnow=substr($datenow,4,2);
1424         $daynow=substr($datenow,6,2);
1425         $datenow=$yearnow.$monthnow.$daynow;
1426     }
1428     $dob=preg_replace("/-/", "", $dob);
1429     $dobyear=substr($dob,0,4);
1430     $dobmonth=substr($dob,4,2);
1431     $dobday=substr($dob,6,2);
1432     $dob=$dobyear.$dobmonth.$dobday;
1434     //to compensate for 30, 31, 28, 29 days/month
1435     $mo=$monthnow; //to avoid confusion with later calculation
1437     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1438         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1439     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1440     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1441         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1442         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1443         else {$nd=28;} //otherwise, it is not a leap year.
1444     }
1445     else {$nd=31;} // other months have 31 days
1447     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1448     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1449     {
1450         $age_year = $yearnow - $dobyear - 1;
1451         if ($daynow < $dobday) {
1452             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1453             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1454         }
1455         else {
1456             $months_since_birthday=12 - $dobmonth + $monthnow;
1457             $days_since_dobday=$daynow - $dobday;
1458         }
1459     }
1460     else // if patient has had birthday this calandar year
1461     {
1462         $age_year = $yearnow - $dobyear;
1463         if ($daynow < $dobday) {
1464             $months_since_birthday=$monthnow - $dobmonth -1;
1465             $days_since_dobday=$nd - $dobday + $daynow;
1466         }
1467         else {
1468             $months_since_birthday=$monthnow - $dobmonth;
1469             $days_since_dobday=$daynow - $dobday;
1470         }       
1471     }
1472     
1473     $day_as_month_decimal = $days_since_dobday / 30;
1474     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1475     $month_as_year_decimal = $months_since_birthday_float / 12;
1476     $age_float = $age_year + $month_as_year_decimal;
1478     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1479     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1480     $age = round($age_float,2);
1482     // round the years to 2 floating points
1483     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1484     return compact('age','age_in_months','ageinYMD');
1487 // Returns Age in days
1488 //   in months if < 2 years old
1489 //   in years  if > 2 years old
1490 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1491 // (optional) nowYMD is a date in YYYYMMDD format
1492 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1493     $age = -1;
1495     // strip any dashes from the DOB
1496     $dobYMD = preg_replace("/-/", "", $dobYMD);
1497     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1498     
1499     // set the 'now' date values
1500     if ($nowYMD == null) {
1501         $nowDay = date("d");
1502         $nowMonth = date("m");
1503         $nowYear = date("Y");
1504     }
1505     else {
1506         $nowDay = substr($nowYMD,6,2);
1507         $nowMonth = substr($nowYMD,4,2);
1508         $nowYear = substr($nowYMD,0,4);
1509     }
1511     // do the date math
1512     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1513     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1514     $timediff = $nowtime - $dobtime;
1515     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1517     return $age;
1520  * Returns a string to be used to display a patient's age
1521  * 
1522  * @param type $dobYMD
1523  * @param type $asOfYMD
1524  * @return string suitable for displaying patient's age based on preferences
1525  */
1526 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1528     if($GLOBALS['age_display_format']=='1')
1529     {
1530         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1531         if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1532         {
1533             return $ageYMD['ageinYMD'];
1534         }
1535         else
1536         {
1537             return getPatientAge($dobYMD, $asOfYMD);                    
1538         }
1539     }
1540     else
1541     {
1542         return getPatientAge($dobYMD, $asOfYMD);
1543     }
1544     
1546 function dateToDB ($date)
1548     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1549     return $date;
1553 // ----------------------------------------------------------------------------
1555  * DROPDOWN FOR COUNTRIES
1556  * 
1557  * build a dropdown with all countries from geo_country_reference
1558  * 
1559  * @param int $selected - id for selected record
1560  * @param string $name - the name/id for select form
1561  * @return void - just echo the html encoded string
1562  */
1563 function dropdown_countries($selected = 0, $name = 'country_code') {
1564     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1566     $string = "<select name='$name' id='$name'>";
1567     while ( $row = sqlFetchArray($r) ) {
1568         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1569         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1570     }
1572     $string .= '</select>';
1573     echo $string;
1577 // ----------------------------------------------------------------------------
1579  * DROPDOWN FOR YES/NO
1580  * 
1581  * build a dropdown with two options (yes - 1, no - 0)
1582  * 
1583  * @param int $selected - id for selected record
1584  * @param string $name - the name/id for select form
1585  * @return void - just echo the html encoded string 
1586  */
1587 function dropdown_yesno($selected = 0, $name = 'yesno') {
1588     $string = "<select name='$name' id='$name'>";
1590     $selected = (int)$selected;
1591     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1592     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1594     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1595     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1596     $string .= '</select>';
1598     echo $string;
1601 // ----------------------------------------------------------------------------
1603  * DROPDOWN FOR MALE/FEMALE options
1604  * 
1605  * build a dropdown with three options (unselected/male/female)
1606  * 
1607  * @param int $selected - id for selected record
1608  * @param string $name - the name/id for select form
1609  * @return void - just echo the html encoded string
1610  */
1611 function dropdown_sex($selected = 0, $name = 'sex') {
1612     $string = "<select name='$name' id='$name'>";
1614     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1615     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1616     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1618     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1619     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1620     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1621     $string .= '</select>';
1623     echo $string;
1626 // ----------------------------------------------------------------------------
1628  * DROPDOWN FOR MARITAL STATUS
1629  * 
1630  * build a dropdown with marital status
1631  * 
1632  * @param int $selected - id for selected record
1633  * @param string $name - the name/id for select form
1634  * @return void - just echo the html encoded string
1635  */
1636 function dropdown_marital($selected = 0, $name = 'status') {
1637     $string = "<select name='$name' id='$name'>";
1639     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1641     foreach ( $statii as $st ) {
1642         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1643         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1644     }
1646     $string .= '</select>';
1648     echo $string;
1651 // ----------------------------------------------------------------------------
1653  * DROPDOWN FOR PROVIDERS
1654  * 
1655  * build a dropdown with all providers
1656  * 
1657  * @param int $selected - id for selected record
1658  * @param string $name - the name/id for select form
1659  * @return void - just echo the html encoded string
1660  */
1661 function dropdown_providers($selected = 0, $name = 'status') {
1662     $provideri = getProviderInfo();
1664     $string = "<select name='$name' id='$name'>";
1665     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1666     foreach ( $provideri as $s ) {
1667         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1668         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1669     }
1671     $string .= '</select>';
1673     echo $string;
1676 // ----------------------------------------------------------------------------
1678  * DROPDOWN FOR INSURANCE COMPANIES
1679  * 
1680  * build a dropdown with all insurers
1681  * 
1682  * @param int $selected - id for selected record
1683  * @param string $name - the name/id for select form
1684  * @return void - just echo the html encoded string
1685  */
1686 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1687     $insurancei = getInsuranceProviders();
1689     $string = "<select name='$name' id='$name'>";
1690     $string .= '<option value="0">Onbekend</option>';
1691     foreach ( $insurancei as $iid => $iname ) {
1692         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1693         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1694     }
1696     $string .= '</select>';
1698     echo $string;
1702 // ----------------------------------------------------------------------------
1704  * COUNTRY CODE
1705  * 
1706  * return the name or the country code, function of arguments
1707  * 
1708  * @param int $country_code
1709  * @param string $country_name
1710  * @return string | int - name or code
1711  */
1712 function country_code($country_code = 0, $country_name = '') {
1713     $strint = '';
1714     if ( $country_code ) {
1715         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1716     } else {
1717         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1718     }
1720     $db = $GLOBALS['adodb']['db'];
1721     $result = $db->Execute($sql);
1722     if ($result && !$result->EOF) {
1723         $strint = $result->fields['res'];
1724     }
1726     return $strint;
1729 function DBToDate ($date)
1731     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1732     return $date;
1736  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1737  * for the given patient on the given date.
1739  * @param int     The PID of the patient.
1740  * @param string  Date in yyyy-mm-dd format.
1741  * @return array  Array of 0-3 insurance_data rows.
1742  */
1743 function getEffectiveInsurances($patient_id, $encdate) {
1744   $insarr = array();
1745   foreach (array('primary','secondary','tertiary') as $instype) {
1746     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1747       "WHERE pid = ? AND type = ? " .
1748       "AND date <= ? ORDER BY date DESC LIMIT 1",
1749       array($patient_id, $instype, $encdate));
1750     if (empty($tmp['provider'])) break;
1751     $insarr[] = $tmp;
1752   }
1753   return $insarr;
1757  * Get the patient's balance due. Normally this excludes amounts that are out
1758  * to insurance.  If you want to include what insurance owes, set the second
1759  * parameter to true.
1761  * @param int     The PID of the patient.
1762  * @param boolean Indicates if amounts owed by insurance are to be included.
1763  * @return number The balance.
1764  */
1765 function get_patient_balance($pid, $with_insurance=false) {
1766   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1767     $balance = 0;
1768     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1769       "last_level_closed, stmt_count " .
1770       "FROM form_encounter WHERE pid = ?", array($pid));
1771     while ($ferow = sqlFetchArray($feres)) {
1772       $encounter = $ferow['encounter'];
1773       $dos = substr($ferow['date'], 0, 10);
1774       $insarr = getEffectiveInsurances($pid, $dos);
1775       $inscount = count($insarr);
1776       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1777         // It's out to insurance so only the co-pay might be due.
1778         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1779           "pid = ? AND encounter = ? AND " .
1780           "code_type = 'copay' AND activity = 1",
1781           array($pid, $encounter));
1782         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1783           "FROM ar_activity WHERE " .
1784           "pid = ? AND encounter = ? AND payer_type = 0",
1785           array($pid, $encounter));
1786         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1787         if ($ptbal > 0) $balance += $ptbal;
1788       }
1789       else {
1790         // Including insurance or not out to insurance, everything is due.
1791         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1792           "pid = ? AND encounter = ? AND " .
1793           "activity = 1", array($pid, $encounter));
1794         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1795           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1796           "pid = ? AND encounter = ?", array($pid, $encounter));
1797         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1798           "pid = ? AND encounter = ?", array($pid, $encounter));
1799         $balance += $brow['amount'] + $srow['amount']
1800           - $drow['payments'] - $drow['adjustments'];
1801       }
1802     }
1803     return sprintf('%01.2f', $balance);
1804   }
1805   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1806     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1807     $conn = $GLOBALS['adodb']['db'];
1808     $customer_info['id'] = 0;
1809     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1810       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1811       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1812       "im.foreign_table = 'customer'";
1813     $result = $conn->Execute($sql);
1814     if($result && !$result->EOF) {
1815       $customer_info['id'] = $result->fields['foreign_id'];
1816     }
1817     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1818     $ws = new WSWrapper($function);
1819     if(is_numeric($ws->value)) {
1820       return sprintf('%01.2f', $ws->value);
1821     }
1822   }
1823   return '';
1826 // Function to check if patient is deceased.
1827 //  Param:
1828 //    $pid  - patient id
1829 //    $date - date checking if deceased (will default to current date if blank)
1830 //  Return:
1831 //    If deceased, then will return the number of
1832 //      days that patient has been deceased.
1833 //    If not deceased, then will return false.
1834 function is_patient_deceased($pid,$date='') {
1836   // Set date to current if not set
1837   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1839   // Query for deceased status (gets days deceased if patient is deceased)
1840   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1841                       "FROM `patient_data` " .
1842                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1844   if (empty($results)) {
1845     // Patient is alive, so return false
1846     return false;
1847   }
1848   else {
1849     // Patient is dead, so return the number of days patient has been deceased.
1850     //  Don't let it be zero days or else will confuse calls to this function.
1851     if ($results['days_deceased'] === 0) {
1852       $results['days_deceased'] = 1;
1853     }
1854     return $results['days_deceased'];
1855   }