Added Somali language
[openemr.git] / library / patient.inc
blob4cb24595a32fd99a3c428f21a0a0375f3d30ca31
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         $sql = "select insurance_companies.name, insurance_companies.id, " .
81           "addresses.zip, addresses.line1, addresses.state " .
82           "from insurance_companies, addresses " .
83           "where addresses.foreign_id = insurance_companies.id " .
84           "order by insurance_companies.name, addresses.zip";
86         $rez = sqlStatement($sql);
88         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
89     switch ($GLOBALS['insurance_information']) {
90         case $GLOBALS['insurance_information'] = '0':
91             $returnval[$row['id']] = $row['name'];
92         break;
93         case $GLOBALS['insurance_information'] = '1':
94             $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
95         break; 
96         case $GLOBALS['insurance_information'] = '2':
97            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";      
98         break;
99         case $GLOBALS['insurance_information'] = '3':
100            $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
101         break; 
102         case $GLOBALS['insurance_information'] = '4':
103                $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
104            "," . $row['zip'] . ")";
105         break;
106         case $GLOBALS['insurance_information'] = '5':
107             preg_match("/\d+/", $row['line1'], $matches);
108             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
109               "," . $matches[0] . ")";
110         break; 
111         }
112     }
114     return $returnval;
117 function getProviders() {
118     $returnval = array("");
119     $sql = "select fname, lname from users where authorized = 1 and " .
120         "active = 1 and username != ''";
121     $rez = sqlStatement($sql);
122     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
123         if (($row["fname"] != "") && ($row["lname"] != "")) {
124             array_push($returnval, $row["fname"] . " " . $row["lname"]);
125         }
126     }
127     return $returnval;
130 // ----------------------------------------------------------------------------
131 // Get one facility row.  If the ID is not specified, then get either the
132 // "main" (billing) facility, or the default facility of the currently
133 // logged-in user.  This was created to support genFacilityTitle() but
134 // may find additional uses.
136 function getFacility($facid=0) {
138   //create a sql binding array
139   $sqlBindArray = array();
140   
141   if ($facid > 0) {
142     $query = "SELECT * FROM facility WHERE id = ?";
143     array_push($sqlBindArray,$facid);
144   }
145   else if ($facid == 0) {
146     $query = "SELECT * FROM facility ORDER BY " .
147       "billing_location DESC, service_location, id LIMIT 1";
148   }
149   else {
150     $query = "SELECT facility.* FROM users, facility WHERE " .
151       "users.id = ? AND " .
152       "facility.id = users.facility_id";
153     array_push($sqlBindArray,$_SESSION['authUserID']);
154   }
155   return sqlQuery($query,$sqlBindArray);
158 // Generate a report title including report name and facility name, address
159 // and phone.
161 function genFacilityTitle($repname='', $facid=0) {
162   $s = '';
163   $s .= "<table class='ftitletable'>\n";
164   $s .= " <tr>\n";
165   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
166   $s .= "  <td class='ftitlecell2'>\n";
167   $r = getFacility($facid);
168   if (!empty($r)) {
169     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
170     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
171     if ($r['city'] || $r['state'] || $r['postal_code']) {
172       $s .= "<br />";
173       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
174       if ($r['state']) {
175         if ($r['city']) $s .= ", \n";
176         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
177       }
178       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
179       $s .= "\n";
180     }
181     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
182     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
183   }
184   $s .= "  </td>\n";
185   $s .= " </tr>\n";
186   $s .= "</table>\n";
187   return $s;
191 GET FACILITIES
193 returns all facilities or just the id for the first one
194 (FACILITY FILTERING (lemonsoftware))
196 @param string - if 'first' return first facility ordered by id
197 @return array | int for 'first' case
199 function getFacilities($first = '') {
200     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
201     $ret = array();
202     while ( $row = sqlFetchArray($r) ) {
203        $ret[] = $row;
206         if ( $first == 'first') {
207             return $ret[0]['id'];
208         } else {
209             return $ret;
210         }
214 GET SERVICE FACILITIES
216 returns all service_location facilities or just the id for the first one
217 (FACILITY FILTERING (CHEMED))
219 @param string - if 'first' return first facility ordered by id
220 @return array | int for 'first' case
222 function getServiceFacilities($first = '') {
223     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
224     $ret = array();
225     while ( $row = sqlFetchArray($r) ) {
226        $ret[] = $row;
229         if ( $first == 'first') {
230             return $ret[0]['id'];
231         } else {
232             return $ret;
233         }
236 //(CHEMED) facility filter
237 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
238     $param1 = "";
239     if ($providers_only === 'any') {
240       $param1 = " AND authorized = 1 AND active = 1 ";
241     }
242     else if ($providers_only) {
243       $param1 = " AND authorized = 1 AND calendar = 1 ";
244     }
246     //--------------------------------
247     //(CHEMED) facility filter
248     $param2 = "";
249     if ($facility) {
250       if ($GLOBALS['restrict_user_facility']) {
251         $param2 = " AND (facility_id = $facility 
252           OR  $facility IN
253                 (select facility_id 
254                 from users_facility
255                 where tablename = 'users'
256                 and table_id = id)
257                 )
258           ";
259       }
260       else {
261         $param2 = " AND facility_id = $facility ";
262       }
263     }
264     //--------------------------------
266     $command = "=";
267     if ($providerID == "%") {
268         $command = "like";
269     }
270     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
271         "from users where username != '' and active = 1 and id $command '" .
272         add_escape_custom($providerID) . "' " . $param1 . $param2;
273     // sort by last name -- JRM June 2008
274     $query .= " ORDER BY lname, fname ";
275     $rez = sqlStatement($query);
276     for($iter=0; $row=sqlFetchArray($rez); $iter++)
277         $returnval[$iter]=$row;
279     //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
280     //accessible from $resultval['key']
282     if($iter==1) {
283         $akeys = array_keys($returnval[0]);
284         foreach($akeys as $key) {
285             $returnval[0][$key] = $returnval[0][$key];
286         }
287     }
288     return $returnval;
291 //same as above but does not reduce if only 1 row returned
292 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
293     $param1 = "";
294     if ($providers_only) {
295         $param1 = "AND authorized=1";
296     }
297     $command = "=";
298     if ($providerID == "%") {
299         $command = "like";
300     }
301     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
302         "from users where active = 1 and username != '' and id $command '" .
303         add_escape_custom($providerID) . "' " . $param1;
305     $rez = sqlStatement($query);
306     for($iter=0; $row=sqlFetchArray($rez); $iter++)
307         $returnval[$iter]=$row;
309     return $returnval;
312 function getProviderName($providerID) {
313     $pi = getProviderInfo($providerID, 'any');
314     if (strlen($pi[0]["lname"]) > 0) {
315         return $pi[0]['fname'] . " " . $pi[0]['lname'];
316     }
317     return "";
320 function getProviderId($providerName) {
321     $query = "select id from users where username = ?";
322     $rez = sqlStatement($query, array($providerName) );
323     for($iter=0; $row=sqlFetchArray($rez); $iter++)
324         $returnval[$iter]=$row;
325     return $returnval;
328 function getEthnoRacials() {
329     $returnval = array("");
330     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
331     $rez = sqlStatement($sql);
332     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
333         if (($row["ethnoracial"] != "")) {
334             array_push($returnval, $row["ethnoracial"]);
335         }
336     }
337     return $returnval;
340 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
343     if ($dateStart && $dateEnd) {
344         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
345     }
346     else if ($dateStart && !$dateEnd) {
347         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
348     }
349     else if (!$dateStart && $dateEnd) {
350         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
351     }
352     else {
353         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
354     }
356     return $res;
359 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
360 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
362   $sql = "select $given from insurance_data as insd " .
363     "left join insurance_companies as ic on ic.id = insd.provider " .
364     "where pid = ? and type = ? order by date DESC limit 1";
365   return sqlQuery($sql, array($pid, $type) );
368 function getInsuranceDataByDate($pid, $date, $type,
369   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
370 { // this must take the date in the following manner: YYYY-MM-DD
371   // this function recalls the insurance value that was most recently enterred from the
372   // given date. it will call up most recent records up to and on the date given,
373   // but not records enterred after the given date
374   $sql = "select $given from insurance_data as insd " .
375     "left join insurance_companies as ic on ic.id = provider " .
376     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
377     "type=? order by date DESC limit 1";
378   return sqlQuery($sql, array($pid,$date,$type) );
381 function getEmployerData($pid, $given = "*")
383     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
384     return sqlQuery($sql, array($pid) );
387 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
388   // When the limit is exceeded, find out what the unlimited count would be.
389   $GLOBALS['PATIENT_INC_COUNT'] = $count;
390   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
391   if ($limit != "all") {
392     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
393     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
394   }
398  * Allow the last name to be followed by a comma and some part of a first name(can
399  *   also place middle name after the first name with a space separating them)
400  * Allows comma alone followed by some part of a first name(can also place middle name
401  *   after the first name with a space separating them).
402  * Allows comma alone preceded by some part of a last name.
403  * If no comma or space, then will search both last name and first name.
404  * If the first letter of either name is capital, searches for name starting
405  *   with given substring (the expected behavior). If it is lower case, it
406  *   searches for the substring anywhere in the name. This applies to either
407  *   last name, first name, and middle name.
408  * Also allows first name followed by middle and/or last name when separated by spaces.
409  * @param string $term
410  * @param string $given
411  * @param string $orderby
412  * @param string $limit
413  * @param string $start
414  * @return array
415  */
416 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")
418     $names = getPatientNameSplit($term);
419     
420     foreach ($names as $key => $val) {
421       if (!empty($val)) {
422         if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
423             $names[$key] = '%' . $val . '%';            
424         } else { 
425             $names[$key] = $val . '%';            
426         }
427       }
428     }
430     // Debugging section below
431     //if(array_key_exists('first',$names)) {
432     //    error_log("first name search term :".$names['first']);
433     //}
434     //if(array_key_exists('middle',$names)) {
435     //    error_log("middle name search term :".$names['middle']);
436     //}
437     //if(array_key_exists('last',$names)) {
438     //    error_log("last name search term :".$names['last']);
439     //}
440     // Debugging section above
442     $sqlBindArray = array();
443     if(array_key_exists('last',$names) && $names['last'] == '') {
444         // Do not search last name
445         $where = "fname LIKE ? ";
446         array_push($sqlBindArray, $names['first']);
447         if ($names['middle'] != '') {        
448             $where .= "AND mname LIKE ? ";  
449             array_push($sqlBindArray, $names['middle']);
450         }
451     } elseif(array_key_exists('first',$names) && $names['first'] == '') {
452         // Do not search first name or middle name
453         $where = "lname LIKE ? ";
454         array_push($sqlBindArray, $names['last']);
455     } elseif($names['first'] == '' && $names['last'] != '') {
456         // Search both first name and last name with same term
457         $names['first'] = $names['last']; 
458         $where = "lname LIKE ? OR fname LIKE ? ";
459         array_push($sqlBindArray, $names['last'], $names['first']);
460     } elseif ($names['middle'] != '') {        
461         $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";  
462         array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
463     } else {
464         $where = "lname LIKE ? AND fname LIKE ? ";
465         array_push($sqlBindArray, $names['last'], $names['first']);
466     }
468         if (!empty($GLOBALS['pt_restrict_field'])) {
469                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
470                         $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
471                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
472                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
473                         array_push($sqlBindArray, $_SESSION{"authUser"});
474                 }
475         }
477     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
478     if ($limit != "all") $sql .= " LIMIT $start, $limit";
480     $rez = sqlStatement($sql, $sqlBindArray);
482     $returnval=array();
483     for($iter=0; $row=sqlFetchArray($rez); $iter++)
484         $returnval[$iter] = $row;
486     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
487     return $returnval;
490  * Accept a string used by a search function expected to find a patient name, 
491  * then split up the string if a comma or space exists. Return an array having 
492  * from 1 to 3 elements, named first, middle, and last.
493  * See above getPatientLnames() function for details on how the splitting occurs.
494  * @param string $term
495  * @return array
496  */
497 function getPatientNameSplit($term) {
498     $term = trim($term);
499     if (strpos($term, ',') !== false) {
500         $names = explode(',', $term);        
501         $n['last'] = $names[0];
502         if (strpos(trim($names[1]), ' ') !== false) {
503             list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
504         } else {
505             $n['first'] = $names[1];
506         }
507     } elseif (strpos($term, ' ') !== false) {
508         $names = explode(' ', $term);
509         if (count($names) == 1) {
510             $n['last'] = $names[0];
511         } elseif (count($names) == 3) {
512             $n['first'] = $names[0];
513             $n['middle'] = $names[1];
514             $n['last'] = $names[2];
515         } else {
516             // This will handle first and last name or first followed by 
517             // multiple names only using just the last of the names in the list.
518             $n['first'] = $names[0];
519             $n['last'] = end($names);
520         }
521     } else {
522         $n['last'] = $term;       
523     }
524     // Trim whitespace off the names before returning
525     foreach($n as $key => $val) {
526         $n[$key] = trim($val);
527     }
528     return $n; // associative array containing names
531 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")
534     $sqlBindArray = array();
535     $where = "pubpid LIKE ? ";
536     array_push($sqlBindArray, $pid."%");
537         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
538                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
539                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
540                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
541                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
542                         array_push($sqlBindArray, $_SESSION{"authUser"});
543                 }
544         }
546     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
547     if ($limit != "all") $sql .= " limit $start, $limit";
548     $rez = sqlStatement($sql, $sqlBindArray);
549     for($iter=0; $row=sqlFetchArray($rez); $iter++)
550         $returnval[$iter]=$row;
552     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
553     return $returnval;
556 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")
558   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
560   $sqlBindArray = array();
561   $where = "";
562   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
563     if ( $iter > 0 ) {
564       $where .= " or ";
565     }
566     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
567     array_push($sqlBindArray, "%".$searchTerm."%");
568   }
570   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
571   if ($limit != "all") $sql .= " limit $start, $limit";
572   $rez = sqlStatement($sql, $sqlBindArray);
573   for($iter=0; $row=sqlFetchArray($rez); $iter++)
574     $returnval[$iter]=$row;
575   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
576   return $returnval;
579 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
580   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
581   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
583         $layoutCols = explode( '~', $searchFields );
584   $sqlBindArray = array();
585   $where = "";
586   $i = 0;
587   foreach ($layoutCols as $val) {
588     if (empty($val)) continue;
589                 if ( $i > 0 ) {
590                    $where .= " or ";
591                 }
592     if ($val == 'pid') {
593                 $where .= " ".add_escape_custom($val)." = ? ";
594                 array_push($sqlBindArray, $searchTerm);
595     }
596     else {
597                 $where .= " ".add_escape_custom($val)." like ? ";
598                 array_push($sqlBindArray, $searchTerm."%");
599     }
600                 $i++;
601         }
603   // If no search terms, ensure valid syntax.
604   if ($i == 0) $where = "1 = 1";
606   // If a non-empty service code was given, then restrict to patients who
607   // have been provided that service.  Since the code is used in a LIKE
608   // clause, % and _ wildcards are supported.
609   if ($search_service_code) {
610     $where = "( $where ) AND " .
611       "( SELECT COUNT(*) FROM billing AS b WHERE " .
612       "b.pid = patient_data.pid AND " .
613       "b.activity = 1 AND " .
614       "b.code_type != 'COPAY' AND " .
615       "b.code LIKE ? " .
616       ") > 0";
617     array_push($sqlBindArray, $search_service_code);
618   }
620   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
621   if ($limit != "all") $sql .= " limit $start, $limit";
622   $rez = sqlStatement($sql, $sqlBindArray);
623   for($iter=0; $row=sqlFetchArray($rez); $iter++)
624       $returnval[$iter]=$row;
625   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
626   return $returnval;
629 // return a collection of Patient PIDs
630 // new arg style by JRM March 2008
631 // 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")
632 function getPatientPID($args)
634     $pid = "%";
635     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
636     $orderby = "lname ASC, fname ASC";
637     $limit="all";
638     $start="0";
640     // alter default values if defined in the passed in args
641     if (isset($args['pid'])) { $pid = $args['pid']; }
642     if (isset($args['given'])) { $given = $args['given']; }
643     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
644     if (isset($args['limit'])) { $limit = $args['limit']; }
645     if (isset($args['start'])) { $start = $args['start']; }
647     $command = "=";
648     if ($pid == -1) $pid = "%";
649     elseif (empty($pid)) $pid = "NULL";
651     if (strstr($pid,"%")) $command = "like";
653     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
654     if ($limit != "all") $sql .= " limit $start, $limit";
656     $rez = sqlStatement($sql);
657     for($iter=0; $row=sqlFetchArray($rez); $iter++)
658         $returnval[$iter]=$row;
660     return $returnval;
663 /* return a patient's name in the format LAST, FIRST */
664 function getPatientName($pid) {
665     if (empty($pid)) return "";
666     $patientData = getPatientPID(array("pid"=>$pid));
667     if (empty($patientData[0]['lname'])) return "";
668     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
669     return $patientName;
672 /* find patient data by DOB */
673 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
675     $DOB = fixDate($DOB, $DOB);
676     $sqlBindArray = array();
677     $where = "DOB like ? ";
678     array_push($sqlBindArray, $DOB."%");
679         if (!empty($GLOBALS['pt_restrict_field'])) {
680                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
681                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
682                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
683                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
684                         array_push($sqlBindArray, $_SESSION{"authUser"});
685                 }
686         }
688     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
690     if ($limit != "all") $sql .= " LIMIT $start, $limit";
692     $rez = sqlStatement($sql, $sqlBindArray);
693     for($iter=0; $row=sqlFetchArray($rez); $iter++)
694         $returnval[$iter]=$row;
696     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
697     return $returnval;
700 /* find patient data by SSN */
701 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
703     $sqlBindArray = array();
704     $where = "ss LIKE ?";
705     array_push($sqlBindArray, $ss."%");
706     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
707     if ($limit != "all") $sql .= " LIMIT $start, $limit";
709     $rez = sqlStatement($sql, $sqlBindArray);
710     for($iter=0; $row=sqlFetchArray($rez); $iter++)
711         $returnval[$iter]=$row;
713     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
714     return $returnval;
717 //(CHEMED) Search by phone number
718 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
720     $phone = preg_replace( "/[[:punct:]]/","", $phone );
721     $sqlBindArray = array();
722     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
723     array_push($sqlBindArray, $phone);
724     $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 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
737     $sql="select $given from patient_data order by $orderby";
739     if ($limit != "all")
740         $sql .= " limit $start, $limit";
742     $rez = sqlStatement($sql);
743     for($iter=0; $row=sqlFetchArray($rez); $iter++)
744         $returnval[$iter]=$row;
746     return $returnval;
749 //----------------------input functions
750 function newPatientData(    $db_id="",
751                 $title = "",
752                 $fname = "",
753                 $lname = "",
754                 $mname = "",
755                 $sex = "",
756                 $DOB = "",
757                 $street = "",
758                 $postal_code = "",
759                 $city = "",
760                 $state = "",
761                 $country_code = "",
762                 $ss = "",
763                 $occupation = "",
764                 $phone_home = "",
765                 $phone_biz = "",
766                 $phone_contact = "",
767                 $status = "",
768                 $contact_relationship = "",
769                 $referrer = "",
770                 $referrerID = "",
771                 $email = "",
772                 $language = "",
773                 $ethnoracial = "",
774                 $interpretter = "",
775                 $migrantseasonal = "",
776                 $family_size = "",
777                 $monthly_income = "",
778                 $homeless = "",
779                 $financial_review = "",
780                 $pubpid = "",
781                 $pid = "MAX(pid)+1",
782                 $providerID = "",
783                 $genericname1 = "",
784                 $genericval1 = "",
785                 $genericname2 = "",
786                 $genericval2 = "",
787                 $billing_note="",
788                 $phone_cell = "",
789                 $hipaa_mail = "",
790                 $hipaa_voice = "",
791                 $squad = 0,
792                 $pharmacy_id = 0,
793                 $drivers_license = "",
794                 $hipaa_notice = "",
795                 $hipaa_message = "",
796                 $regdate = ""
797             )
799     $DOB = fixDate($DOB);
800     $regdate = fixDate($regdate);
802     $fitness = 0;
803     $referral_source = '';
804     if ($pid) {
805         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
806         // Check for brain damage:
807         if ($db_id != $rez['id']) {
808             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
809               $rez['id'] . "' to '$db_id' for pid '$pid'";
810             die($errmsg);
811         }
812         $fitness = $rez['fitness'];
813         $referral_source = $rez['referral_source'];
814     }
816     // Get the default price level.
817     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
818       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
819     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
821     $query = ("replace into patient_data set
822         id='$db_id',
823         title='$title',
824         fname='$fname',
825         lname='$lname',
826         mname='$mname',
827         sex='$sex',
828         DOB='$DOB',
829         street='$street',
830         postal_code='$postal_code',
831         city='$city',
832         state='$state',
833         country_code='$country_code',
834         drivers_license='$drivers_license',
835         ss='$ss',
836         occupation='$occupation',
837         phone_home='$phone_home',
838         phone_biz='$phone_biz',
839         phone_contact='$phone_contact',
840         status='$status',
841         contact_relationship='$contact_relationship',
842         referrer='$referrer',
843         referrerID='$referrerID',
844         email='$email',
845         language='$language',
846         ethnoracial='$ethnoracial',
847         interpretter='$interpretter',
848         migrantseasonal='$migrantseasonal',
849         family_size='$family_size',
850         monthly_income='$monthly_income',
851         homeless='$homeless',
852         financial_review='$financial_review',
853         pubpid='$pubpid',
854         pid = $pid,
855         providerID = '$providerID',
856         genericname1 = '$genericname1',
857         genericval1 = '$genericval1',
858         genericname2 = '$genericname2',
859         genericval2 = '$genericval2',
860         billing_note= '$billing_note';
861         phone_cell = '$phone_cell',
862         pharmacy_id = '$pharmacy_id',
863         hipaa_mail = '$hipaa_mail',
864         hipaa_voice = '$hipaa_voice',
865         hipaa_notice = '$hipaa_notice',
866         hipaa_message = '$hipaa_message',
867         squad = '$squad',
868         fitness='$fitness',
869         referral_source='$referral_source',
870         regdate='$regdate',
871         pricelevel='$pricelevel',
872         date=NOW()");
874     $id = sqlInsert($query);
876     if ( !$db_id ) {
877       // find the last inserted id for new patient case
878       $db_id = getSqlLastID();
879     }
881     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
883     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
884                 $phone_biz,$phone_cell,$email,$pid);
886     return $foo['pid'];
889 // Supported input date formats are:
890 //   mm/dd/yyyy
891 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
892 //   yyyy/mm/dd
893 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
895 function fixDate($date, $default="0000-00-00") {
896     $fixed_date = $default;
897     $date = trim($date);
898     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
899         $dmy = preg_split("'[/.-]'", $date);
900         if ($dmy[0] > 99) {
901             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
902         } else {
903             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
904               if ($dmy[2] < 1000) $dmy[2] += 1900;
905               if ($dmy[2] < 1910) $dmy[2] += 100;
906             }
907             // phone_country_code indicates format of ambiguous input dates.
908             if ($GLOBALS['phone_country_code'] == 1)
909               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
910             else
911               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
912         }
913     }
915     return $fixed_date;
918 function pdValueOrNull($key, $value) {
919   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
920     substr($key, 0, 8) == 'userdate') &&
921     (empty($value) || $value == '0000-00-00'))
922   {
923     return "NULL";
924   }
925   else {
926     return "'$value'";
927   }
930 // Create or update patient data from an array.
932 function updatePatientData($pid, $new, $create=false)
934   /*******************************************************************
935     $real = getPatientData($pid);
936     $new['DOB'] = fixDate($new['DOB']);
937     while(list($key, $value) = each ($new))
938         $real[$key] = $value;
939     $real['date'] = "'+NOW()+'";
940     $real['id'] = "";
941     $sql = "insert into patient_data set ";
942     while(list($key, $value) = each($real))
943         $sql .= $key." = '$value', ";
944     $sql = substr($sql, 0, -2);
945     return sqlInsert($sql);
946   *******************************************************************/
948   // The above was broken, though seems intent to insert a new patient_data
949   // row for each update.  A good idea, but nothing is doing that yet so
950   // the code below does not yet attempt it.
952   $new['DOB'] = fixDate($new['DOB']);
954   if ($create) {
955     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
956     foreach ($new as $key => $value) {
957       if ($key == 'id') continue;
958       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
959     }
960     $db_id = sqlInsert($sql);
961   }
962   else {
963     $db_id = $new['id'];
964     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
965     // Check for brain damage:
966     if ($pid != $rez['pid']) {
967       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
968         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
969       die($errmsg);
970     }
971     $sql = "UPDATE patient_data SET date = NOW()";
972     foreach ($new as $key => $value) {
973       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
974     }
975     $sql .= " WHERE id = '$db_id'";
976     sqlStatement($sql);
977   }
979   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
980   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
981     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
982     $rez['phone_cell'],$rez['email'],$rez['pid']);
984   return $db_id;
987 function newEmployerData(    $pid,
988                 $name = "",
989                 $street = "",
990                 $postal_code = "",
991                 $city = "",
992                 $state = "",
993                 $country = ""
994             )
996     return sqlInsert("insert into employer_data set
997         name='$name',
998         street='$street',
999         postal_code='$postal_code',
1000         city='$city',
1001         state='$state',
1002         country='$country',
1003         pid='$pid',
1004         date=NOW()
1005         ");
1008 // Create or update employer data from an array.
1010 function updateEmployerData($pid, $new, $create=false)
1012   $colnames = array('name','street','city','state','postal_code','country');
1014   if ($create) {
1015     $set .= "pid = '$pid', date = NOW()";
1016     foreach ($colnames as $key) {
1017       $value = isset($new[$key]) ? $new[$key] : '';
1018       $set .= ", `$key` = '$value'";
1019     }
1020     return sqlInsert("INSERT INTO employer_data SET $set");
1021   }
1022   else {
1023     $set = '';
1024     $old = getEmployerData($pid);
1025     $modified = false;
1026     foreach ($colnames as $key) {
1027       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
1028       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1029         $value = $new[$key];
1030         $modified = true;
1031       }
1032       $set .= "`$key` = '$value', ";
1033     }
1034     if ($modified) {
1035       $set .= "pid = '$pid', date = NOW()";
1036       return sqlInsert("INSERT INTO employer_data SET $set");
1037     }
1038     return $old['id'];
1039   }
1042 // This updates or adds the given insurance data info, while retaining any
1043 // previously added insurance_data rows that should be preserved.
1044 // This does not directly support the maintenance of non-current insurance.
1046 function newInsuranceData(
1047   $pid,
1048   $type = "",
1049   $provider = "",
1050   $policy_number = "",
1051   $group_number = "",
1052   $plan_name = "",
1053   $subscriber_lname = "",
1054   $subscriber_mname = "",
1055   $subscriber_fname = "",
1056   $subscriber_relationship = "",
1057   $subscriber_ss = "",
1058   $subscriber_DOB = "",
1059   $subscriber_street = "",
1060   $subscriber_postal_code = "",
1061   $subscriber_city = "",
1062   $subscriber_state = "",
1063   $subscriber_country = "",
1064   $subscriber_phone = "",
1065   $subscriber_employer = "",
1066   $subscriber_employer_street = "",
1067   $subscriber_employer_city = "",
1068   $subscriber_employer_postal_code = "",
1069   $subscriber_employer_state = "",
1070   $subscriber_employer_country = "",
1071   $copay = "",
1072   $subscriber_sex = "",
1073   $effective_date = "0000-00-00",
1074   $accept_assignment = "TRUE",
1075   $policy_type = "")
1077   if (strlen($type) <= 0) return FALSE;
1079   // If a bad date was passed, err on the side of caution.
1080   $effective_date = fixDate($effective_date, date('Y-m-d'));
1082   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1083     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
1084   $idrow = sqlFetchArray($idres);
1086   // Replace the most recent entry in any of the following cases:
1087   // * Its effective date is >= this effective date.
1088   // * It is the first entry and it has no (insurance) provider.
1089   // * There is no encounter that is earlier than the new effective date but
1090   //   on or after the old effective date.
1091   // Otherwise insert a new entry.
1093   $replace = false;
1094   if ($idrow) {
1095     if (strcmp($idrow['date'], $effective_date) > 0) {
1096       $replace = true;
1097     }
1098     else {
1099       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1100         $replace = true;
1101       }
1102       else {
1103         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1104           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1105           "date >= '" . $idrow['date'] . " 00:00:00'");
1106         if ($ferow['count'] == 0) $replace = true;
1107       }
1108     }
1109   }
1111   if ($replace) {
1113     // TBD: This is a bit dangerous in that a typo in entering the effective
1114     // date can wipe out previous insurance history.  So we want some data
1115     // entry validation somewhere.
1116     sqlStatement("DELETE FROM insurance_data WHERE " .
1117       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1118       "id != " . $idrow['id']);
1120     $data = array();
1121     $data['type'] = $type;
1122     $data['provider'] = $provider;
1123     $data['policy_number'] = $policy_number;
1124     $data['group_number'] = $group_number;
1125     $data['plan_name'] = $plan_name;
1126     $data['subscriber_lname'] = $subscriber_lname;
1127     $data['subscriber_mname'] = $subscriber_mname;
1128     $data['subscriber_fname'] = $subscriber_fname;
1129     $data['subscriber_relationship'] = $subscriber_relationship;
1130     $data['subscriber_ss'] = $subscriber_ss;
1131     $data['subscriber_DOB'] = $subscriber_DOB;
1132     $data['subscriber_street'] = $subscriber_street;
1133     $data['subscriber_postal_code'] = $subscriber_postal_code;
1134     $data['subscriber_city'] = $subscriber_city;
1135     $data['subscriber_state'] = $subscriber_state;
1136     $data['subscriber_country'] = $subscriber_country;
1137     $data['subscriber_phone'] = $subscriber_phone;
1138     $data['subscriber_employer'] = $subscriber_employer;
1139     $data['subscriber_employer_city'] = $subscriber_employer_city;
1140     $data['subscriber_employer_street'] = $subscriber_employer_street;
1141     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1142     $data['subscriber_employer_state'] = $subscriber_employer_state;
1143     $data['subscriber_employer_country'] = $subscriber_employer_country;
1144     $data['copay'] = $copay;
1145     $data['subscriber_sex'] = $subscriber_sex;
1146     $data['pid'] = $pid;
1147     $data['date'] = $effective_date;
1148     $data['accept_assignment'] = $accept_assignment;
1149     $data['policy_type'] = $policy_type;
1150     updateInsuranceData($idrow['id'], $data);
1151     return $idrow['id'];
1152   }
1153   else {
1154     return sqlInsert("INSERT INTO insurance_data SET
1155       type = '$type',
1156       provider = '$provider',
1157       policy_number = '$policy_number',
1158       group_number = '$group_number',
1159       plan_name = '$plan_name',
1160       subscriber_lname = '$subscriber_lname',
1161       subscriber_mname = '$subscriber_mname',
1162       subscriber_fname = '$subscriber_fname',
1163       subscriber_relationship = '$subscriber_relationship',
1164       subscriber_ss = '$subscriber_ss',
1165       subscriber_DOB = '$subscriber_DOB',
1166       subscriber_street = '$subscriber_street',
1167       subscriber_postal_code = '$subscriber_postal_code',
1168       subscriber_city = '$subscriber_city',
1169       subscriber_state = '$subscriber_state',
1170       subscriber_country = '$subscriber_country',
1171       subscriber_phone = '$subscriber_phone',
1172       subscriber_employer = '$subscriber_employer',
1173       subscriber_employer_city = '$subscriber_employer_city',
1174       subscriber_employer_street = '$subscriber_employer_street',
1175       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1176       subscriber_employer_state = '$subscriber_employer_state',
1177       subscriber_employer_country = '$subscriber_employer_country',
1178       copay = '$copay',
1179       subscriber_sex = '$subscriber_sex',
1180       pid = '$pid',
1181       date = '$effective_date',
1182       accept_assignment = '$accept_assignment',
1183       policy_type = '$policy_type'
1184     ");
1185   }
1188 // This is used internally only.
1189 function updateInsuranceData($id, $new)
1191   $fields = sqlListFields("insurance_data");
1192   $use = array();
1194   while(list($key, $value) = each ($new)) {
1195     if (in_array($key, $fields)) {
1196       $use[$key] = $value;
1197     }
1198   }
1200   $sql = "UPDATE insurance_data SET ";
1201   while(list($key, $value) = each($use))
1202     $sql .= "`$key` = '$value', ";
1203   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1205   sqlStatement($sql);
1208 function newHistoryData($pid, $new=false) {
1209   $arraySqlBind = array();
1210   $sql = "insert into history_data set pid = ?, date = NOW()";
1211   array_push($arraySqlBind,$pid);
1212   if ($new) {
1213     while(list($key, $value) = each($new)) {
1214       array_push($arraySqlBind,$value);
1215       $sql .= ", `$key` = ?";
1216     }
1217   }
1218   return sqlInsert($sql, $arraySqlBind );
1221 function updateHistoryData($pid,$new)
1223         $real = getHistoryData($pid);
1224         while(list($key, $value) = each ($new))
1225                 $real[$key] = $value;
1226         $real['id'] = "";
1227         // need to unset date, so can reset it below
1228         unset($real['date']);
1230         $arraySqlBind = array();
1231         $sql = "insert into history_data set `date` = NOW(), ";
1232         while(list($key, $value) = each($real)) {
1233                 array_push($arraySqlBind,$value);
1234                 $sql .= "`$key` = ?, ";
1235         }
1236         $sql = substr($sql, 0, -2);
1238         return sqlInsert($sql, $arraySqlBind );
1241 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1242                 $phone_biz,$phone_cell,$email,$pid="")
1244     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1245     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1247     $db = $GLOBALS['adodb']['db'];
1248     $customer_info = array();
1250     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1251     $result = $db->Execute($sql);
1252     if ($result && !$result->EOF) {
1253         $customer_info['foreign_update'] = true;
1254         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1255         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1256     }
1258     ///xml rpc code to connect to accounting package and add user to it
1259     $customer_info['firstname'] = $fname;
1260     $customer_info['lastname'] = $lname;
1261     $customer_info['address'] = $street;
1262     $customer_info['suburb'] = $city;
1263     $customer_info['state'] = $state;
1264     $customer_info['postcode'] = $postal_code;
1266     //ezybiz wants state as a code rather than abbreviation
1267     $customer_info['geo_zone_id'] = "";
1268     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1269     $db = $GLOBALS['adodb']['db'];
1270     $result = $db->Execute($sql);
1271     if ($result && !$result->EOF) {
1272         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1273     }
1275     //ezybiz wants country as a code rather than abbreviation
1276     $customer_info['geo_country_id'] = "";
1277     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1278     $db = $GLOBALS['adodb']['db'];
1279     $result = $db->Execute($sql);
1280     if ($result && !$result->EOF) {
1281         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1282     }
1284     $customer_info['phone1'] = $phone_home;
1285     $customer_info['phone1comment'] = "Home Phone";
1286     $customer_info['phone2'] = $phone_biz;
1287     $customer_info['phone2comment'] = "Business Phone";
1288     $customer_info['phone3'] = $phone_cell;
1289     $customer_info['phone3comment'] = "Cell Phone";
1290     $customer_info['email'] = $email;
1291     $customer_info['customernumber'] = $pid;
1293     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1294     $ws = new WSWrapper($function);
1296     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1297     if (is_numeric($ws->value)) {
1298         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1299         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1300     }
1303 // Returns Age 
1304 //   in months if < 2 years old
1305 //   in years  if > 2 years old
1306 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1307 // (optional) nowYMD is a date in YYYYMMDD format
1308 function getPatientAge($dobYMD, $nowYMD=null)
1310     // strip any dashes from the DOB
1311     $dobYMD = preg_replace("/-/", "", $dobYMD);
1312     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1313     
1314     // set the 'now' date values
1315     if ($nowYMD == null) {
1316         $nowDay = date("d");
1317         $nowMonth = date("m");
1318         $nowYear = date("Y");
1319     }
1320     else {
1321         $nowDay = substr($nowYMD,6,2);
1322         $nowMonth = substr($nowYMD,4,2);
1323         $nowYear = substr($nowYMD,0,4);
1324     }
1326     $dayDiff = $nowDay - $dobDay;
1327     $monthDiff = $nowMonth - $dobMonth;
1328     $yearDiff = $nowYear - $dobYear;
1330     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1332     // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1333     if($dayDiff<0) { $ageInMonths-=1; } 
1334     
1335     if ( $ageInMonths > 24 ) {
1336         $age = $yearDiff;
1337         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1338         else if ($monthDiff < 0) { $age -= 1; }
1339     }
1340     else  {
1341         $age = "$ageInMonths month"; 
1342     }
1344     return $age;
1348  * Wrapper to make sure the clinical rules dates formats corresponds to the 
1349  * format expected by getPatientAgeYMD
1351  * @param  string  $dob     date of birth
1352  * @param  string  $target  date to calculate age on
1353  * @return array containing
1354  *      age - decimal age in years
1355  *      age_in_months - decimal age in months
1356  *      ageinYMD - formatted string #y #m #d */
1357 function parseAgeInfo($dob,$target)
1359     // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1360     $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1361     // Prepare target (Y-M-D H:M:S)
1362     $dateTarget = preg_replace("/[-\s\/]/","",$target);
1364     return getPatientAgeYMD($dateDOB,$dateTarget);
1369  * 
1370  * @param type $dob
1371  * @param type $date
1372  * @return array containing
1373  *      age - decimal age in years
1374  *      age_in_months - decimal age in months
1375  *      ageinYMD - formatted string #y #m #d
1376  */
1377 function getPatientAgeYMD($dob, $date=null) {
1378         
1379     if ($date == null) {
1380         $daynow = date("d");
1381         $monthnow = date("m");
1382         $yearnow = date("Y");
1383         $datenow=$yearnow.$monthnow.$daynow;
1384     }
1385     else {
1386         $datenow=preg_replace("/-/", "", $date);
1387         $yearnow=substr($datenow,0,4);
1388         $monthnow=substr($datenow,4,2);
1389         $daynow=substr($datenow,6,2);
1390         $datenow=$yearnow.$monthnow.$daynow;
1391     }
1393     $dob=preg_replace("/-/", "", $dob);
1394     $dobyear=substr($dob,0,4);
1395     $dobmonth=substr($dob,4,2);
1396     $dobday=substr($dob,6,2);
1397     $dob=$dobyear.$dobmonth.$dobday;
1399     //to compensate for 30, 31, 28, 29 days/month
1400     $mo=$monthnow; //to avoid confusion with later calculation
1402     if ($mo==05 or $mo==07 or $mo==10 or $mo==12) {  //determined by monthnow-1 
1403         $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then 
1404     }  // look at April, June, September, November for calculation.  These months only have 30 days.
1405     elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1406         $check_leap_Y=$yearnow/4; // To check if this is a leap year. 
1407         if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1408         else {$nd=28;} //otherwise, it is not a leap year.
1409     }
1410     else {$nd=31;} // other months have 31 days
1412     $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1413     if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1414     {
1415         $age_year = $yearnow - $dobyear - 1;
1416         if ($daynow < $dobday) {
1417             $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1418             $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1419         }
1420         else {
1421             $months_since_birthday=12 - $dobmonth + $monthnow;
1422             $days_since_dobday=$daynow - $dobday;
1423         }
1424     }
1425     else // if patient has had birthday this calandar year
1426     {
1427         $age_year = $yearnow - $dobyear;
1428         if ($daynow < $dobday) {
1429             $months_since_birthday=$monthnow - $dobmonth -1;
1430             $days_since_dobday=$nd - $dobday + $daynow;
1431         }
1432         else {
1433             $months_since_birthday=$monthnow - $dobmonth;
1434             $days_since_dobday=$daynow - $dobday;
1435         }       
1436     }
1437     
1438     $day_as_month_decimal = $days_since_dobday / 30;
1439     $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1440     $month_as_year_decimal = $months_since_birthday_float / 12;
1441     $age_float = $age_year + $month_as_year_decimal;
1443     $age_in_months = $age_year * 12 + $months_since_birthday_float;
1444     $age_in_months = round($age_in_months,2);  //round the months to xx.xx 2 floating points
1445     $age = round($age_float,2);
1447     // round the years to 2 floating points
1448     $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1449     return compact('age','age_in_months','ageinYMD');
1452 // Returns Age in days
1453 //   in months if < 2 years old
1454 //   in years  if > 2 years old
1455 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1456 // (optional) nowYMD is a date in YYYYMMDD format
1457 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1458     $age = -1;
1460     // strip any dashes from the DOB
1461     $dobYMD = preg_replace("/-/", "", $dobYMD);
1462     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1463     
1464     // set the 'now' date values
1465     if ($nowYMD == null) {
1466         $nowDay = date("d");
1467         $nowMonth = date("m");
1468         $nowYear = date("Y");
1469     }
1470     else {
1471         $nowDay = substr($nowYMD,6,2);
1472         $nowMonth = substr($nowYMD,4,2);
1473         $nowYear = substr($nowYMD,0,4);
1474     }
1476     // do the date math
1477     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1478     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1479     $timediff = $nowtime - $dobtime;
1480     $age = $timediff / 86400; // 24 hours * 3600 seconds/hour  = 86400 seconds
1482     return $age;
1485  * Returns a string to be used to display a patient's age
1486  * 
1487  * @param type $dobYMD
1488  * @param type $asOfYMD
1489  * @return string suitable for displaying patient's age based on preferences
1490  */
1491 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1493     if($GLOBALS['age_display_format']=='1')
1494     {
1495         $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);    
1496         if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1497         {
1498             return $ageYMD['ageinYMD'];
1499         }
1500         else
1501         {
1502             return getPatientAge($dobYMD, $asOfYMD);                    
1503         }
1504     }
1505     else
1506     {
1507         return getPatientAge($dobYMD, $asOfYMD);
1508     }
1509     
1511 function dateToDB ($date)
1513     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1514     return $date;
1518 // ----------------------------------------------------------------------------
1520  * DROPDOWN FOR COUNTRIES
1521  * 
1522  * build a dropdown with all countries from geo_country_reference
1523  * 
1524  * @param int $selected - id for selected record
1525  * @param string $name - the name/id for select form
1526  * @return void - just echo the html encoded string
1527  */
1528 function dropdown_countries($selected = 0, $name = 'country_code') {
1529     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1531     $string = "<select name='$name' id='$name'>";
1532     while ( $row = sqlFetchArray($r) ) {
1533         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1534         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1535     }
1537     $string .= '</select>';
1538     echo $string;
1542 // ----------------------------------------------------------------------------
1544  * DROPDOWN FOR YES/NO
1545  * 
1546  * build a dropdown with two options (yes - 1, no - 0)
1547  * 
1548  * @param int $selected - id for selected record
1549  * @param string $name - the name/id for select form
1550  * @return void - just echo the html encoded string 
1551  */
1552 function dropdown_yesno($selected = 0, $name = 'yesno') {
1553     $string = "<select name='$name' id='$name'>";
1555     $selected = (int)$selected;
1556     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1557     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1559     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1560     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1561     $string .= '</select>';
1563     echo $string;
1566 // ----------------------------------------------------------------------------
1568  * DROPDOWN FOR MALE/FEMALE options
1569  * 
1570  * build a dropdown with three options (unselected/male/female)
1571  * 
1572  * @param int $selected - id for selected record
1573  * @param string $name - the name/id for select form
1574  * @return void - just echo the html encoded string
1575  */
1576 function dropdown_sex($selected = 0, $name = 'sex') {
1577     $string = "<select name='$name' id='$name'>";
1579     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1580     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1581     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1583     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1584     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1585     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1586     $string .= '</select>';
1588     echo $string;
1591 // ----------------------------------------------------------------------------
1593  * DROPDOWN FOR MARITAL STATUS
1594  * 
1595  * build a dropdown with marital status
1596  * 
1597  * @param int $selected - id for selected record
1598  * @param string $name - the name/id for select form
1599  * @return void - just echo the html encoded string
1600  */
1601 function dropdown_marital($selected = 0, $name = 'status') {
1602     $string = "<select name='$name' id='$name'>";
1604     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1606     foreach ( $statii as $st ) {
1607         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1608         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1609     }
1611     $string .= '</select>';
1613     echo $string;
1616 // ----------------------------------------------------------------------------
1618  * DROPDOWN FOR PROVIDERS
1619  * 
1620  * build a dropdown with all providers
1621  * 
1622  * @param int $selected - id for selected record
1623  * @param string $name - the name/id for select form
1624  * @return void - just echo the html encoded string
1625  */
1626 function dropdown_providers($selected = 0, $name = 'status') {
1627     $provideri = getProviderInfo();
1629     $string = "<select name='$name' id='$name'>";
1630     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1631     foreach ( $provideri as $s ) {
1632         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1633         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1634     }
1636     $string .= '</select>';
1638     echo $string;
1641 // ----------------------------------------------------------------------------
1643  * DROPDOWN FOR INSURANCE COMPANIES
1644  * 
1645  * build a dropdown with all insurers
1646  * 
1647  * @param int $selected - id for selected record
1648  * @param string $name - the name/id for select form
1649  * @return void - just echo the html encoded string
1650  */
1651 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1652     $insurancei = getInsuranceProviders();
1654     $string = "<select name='$name' id='$name'>";
1655     $string .= '<option value="0">Onbekend</option>';
1656     foreach ( $insurancei as $iid => $iname ) {
1657         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1658         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1659     }
1661     $string .= '</select>';
1663     echo $string;
1667 // ----------------------------------------------------------------------------
1669  * COUNTRY CODE
1670  * 
1671  * return the name or the country code, function of arguments
1672  * 
1673  * @param int $country_code
1674  * @param string $country_name
1675  * @return string | int - name or code
1676  */
1677 function country_code($country_code = 0, $country_name = '') {
1678     $strint = '';
1679     if ( $country_code ) {
1680         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1681     } else {
1682         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1683     }
1685     $db = $GLOBALS['adodb']['db'];
1686     $result = $db->Execute($sql);
1687     if ($result && !$result->EOF) {
1688         $strint = $result->fields['res'];
1689     }
1691     return $strint;
1694 function DBToDate ($date)
1696     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1697     return $date;
1701  * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1702  * for the given patient on the given date.
1704  * @param int     The PID of the patient.
1705  * @param string  Date in yyyy-mm-dd format.
1706  * @return array  Array of 0-3 insurance_data rows.
1707  */
1708 function getEffectiveInsurances($patient_id, $encdate) {
1709   $insarr = array();
1710   foreach (array('primary','secondary','tertiary') as $instype) {
1711     $tmp = sqlQuery("SELECT * FROM insurance_data " .
1712       "WHERE pid = ? AND type = ? " .
1713       "AND date <= ? ORDER BY date DESC LIMIT 1",
1714       array($patient_id, $instype, $encdate));
1715     if (empty($tmp['provider'])) break;
1716     $insarr[] = $tmp;
1717   }
1718   return $insarr;
1722  * Get the patient's balance due. Normally this excludes amounts that are out
1723  * to insurance.  If you want to include what insurance owes, set the second
1724  * parameter to true.
1726  * @param int     The PID of the patient.
1727  * @param boolean Indicates if amounts owed by insurance are to be included.
1728  * @return number The balance.
1729  */
1730 function get_patient_balance($pid, $with_insurance=false) {
1731   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1732     $balance = 0;
1733     $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1734       "last_level_closed, stmt_count " .
1735       "FROM form_encounter WHERE pid = ?", array($pid));
1736     while ($ferow = sqlFetchArray($feres)) {
1737       $encounter = $ferow['encounter'];
1738       $dos = substr($ferow['date'], 0, 10);
1739       $insarr = getEffectiveInsurances($pid, $dos);
1740       $inscount = count($insarr);
1741       if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1742         // It's out to insurance so only the co-pay might be due.
1743         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1744           "pid = ? AND encounter = ? AND " .
1745           "code_type = 'copay' AND activity = 1",
1746           array($pid, $encounter));
1747         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1748           "FROM ar_activity WHERE " .
1749           "pid = ? AND encounter = ? AND payer_type = 0",
1750           array($pid, $encounter));
1751         $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1752         if ($ptbal > 0) $balance += $ptbal;
1753       }
1754       else {
1755         // Including insurance or not out to insurance, everything is due.
1756         $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1757           "pid = ? AND encounter = ? AND " .
1758           "activity = 1", array($pid, $encounter));
1759         $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1760           "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1761           "pid = ? AND encounter = ?", array($pid, $encounter));
1762         $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1763           "pid = ? AND encounter = ?", array($pid, $encounter));
1764         $balance += $brow['amount'] + $srow['amount']
1765           - $drow['payments'] - $drow['adjustments'];
1766       }
1767     }
1768     return sprintf('%01.2f', $balance);
1769   }
1770   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1771     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1772     $conn = $GLOBALS['adodb']['db'];
1773     $customer_info['id'] = 0;
1774     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1775       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1776       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1777       "im.foreign_table = 'customer'";
1778     $result = $conn->Execute($sql);
1779     if($result && !$result->EOF) {
1780       $customer_info['id'] = $result->fields['foreign_id'];
1781     }
1782     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1783     $ws = new WSWrapper($function);
1784     if(is_numeric($ws->value)) {
1785       return sprintf('%01.2f', $ws->value);
1786     }
1787   }
1788   return '';
1791 // Function to check if patient is deceased.
1792 //  Param:
1793 //    $pid  - patient id
1794 //    $date - date checking if deceased (will default to current date if blank)
1795 //  Return:
1796 //    If deceased, then will return the number of
1797 //      days that patient has been deceased.
1798 //    If not deceased, then will return false.
1799 function is_patient_deceased($pid,$date='') {
1801   // Set date to current if not set
1802   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1804   // Query for deceased status (gets days deceased if patient is deceased)
1805   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1806                       "FROM `patient_data` " .
1807                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1809   if (empty($results)) {
1810     // Patient is alive, so return false
1811     return false;
1812   }
1813   else {
1814     // Patient is dead, so return the number of days patient has been deceased.
1815     //  Don't let it be zero days or else will confuse calls to this function.
1816     if ($results['days_deceased'] === 0) {
1817       $results['days_deceased'] = 1;
1818     }
1819     return $results['days_deceased'];
1820   }