Addressing SQL syntax issue in messages.php
[openemr.git] / library / patient.inc
blobd72835b09b57ef0c10c4eac5ea4183198e01813c
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once("{$GLOBALS['srcdir']}/sql.inc");
8 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
9 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
11 // These are for sports team use:
12 $PLAYER_FITNESSES = array(
13   xl('Full Play'),
14   xl('Full Training'),
15   xl('Restricted Training'),
16   xl('Injured Out'),
17   xl('Rehabilitation'),
18   xl('Illness'),
19   xl('International Duty')
21 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
23 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
24     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
25     return sqlQuery($sql, array($pid) );
28 function getLanguages() {
29     $returnval = array('','english');
30     $sql = "select distinct lower(language) as language from patient_data";
31     $rez = sqlStatement($sql);
32     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
33         if (($row["language"] != "english") && ($row["language"] != "")) {
34             array_push($returnval, $row["language"]);
35         }
36     }
37     return $returnval;
40 function getInsuranceProvider($ins_id) {
41     
42     $sql = "select name from insurance_companies where id=?";
43     $row = sqlQuery($sql,array($ins_id));
44     return $row['name'];
45     
48 function getInsuranceProviders() {
49     $returnval = array();
51     if (true) {
52         $sql = "select name, id from insurance_companies order by name, id";
53         $rez = sqlStatement($sql);
54         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
55             $returnval[$row['id']] = $row['name'];
56         }
57     }
59     // Please leave this here. I have a user who wants to see zip codes and PO
60     // box numbers listed along with the insurance company names, as many companies
61     // have different billing addresses for different plans.  -- Rod Roark
62     //
63     else {
64         $sql = "select insurance_companies.name, insurance_companies.id, " .
65           "addresses.zip, addresses.line1 " .
66           "from insurance_companies, addresses " .
67           "where addresses.foreign_id = insurance_companies.id " .
68           "order by insurance_companies.name, addresses.zip";
70         $rez = sqlStatement($sql);
72         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
73             preg_match("/\d+/", $row['line1'], $matches);
74             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
75               "," . $matches[0] . ")";
76         }
77     }
79     return $returnval;
82 function getProviders() {
83     $returnval = array("");
84     $sql = "select fname, lname from users where authorized = 1 and " .
85         "active = 1 and username != ''";
86     $rez = sqlStatement($sql);
87     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
88         if (($row["fname"] != "") && ($row["lname"] != "")) {
89             array_push($returnval, $row["fname"] . " " . $row["lname"]);
90         }
91     }
92     return $returnval;
95 // ----------------------------------------------------------------------------
96 // Get one facility row.  If the ID is not specified, then get either the
97 // "main" (billing) facility, or the default facility of the currently
98 // logged-in user.  This was created to support genFacilityTitle() but
99 // may find additional uses.
101 function getFacility($facid=0) {
103   //create a sql binding array
104   $sqlBindArray = array();
105   
106   if ($facid > 0) {
107     $query = "SELECT * FROM facility WHERE id = ?";
108     array_push($sqlBindArray,$facid);
109   }
110   else if ($facid == 0) {
111     $query = "SELECT * FROM facility ORDER BY " .
112       "billing_location DESC, service_location, id LIMIT 1";
113   }
114   else {
115     $query = "SELECT facility.* FROM users, facility WHERE " .
116       "users.id = ? AND " .
117       "facility.id = users.facility_id";
118     array_push($sqlBindArray,$_SESSION['authUserID']);
119   }
120   return sqlQuery($query,$sqlBindArray);
123 // Generate a report title including report name and facility name, address
124 // and phone.
126 function genFacilityTitle($repname='', $facid=0) {
127   $s = '';
128   $s .= "<table class='ftitletable'>\n";
129   $s .= " <tr>\n";
130   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
131   $s .= "  <td class='ftitlecell2'>\n";
132   $r = getFacility($facid);
133   if (!empty($r)) {
134     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
135     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
136     if ($r['city'] || $r['state'] || $r['postal_code']) {
137       $s .= "<br />";
138       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
139       if ($r['state']) {
140         if ($r['city']) $s .= ", \n";
141         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
142       }
143       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
144       $s .= "\n";
145     }
146     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
147     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
148   }
149   $s .= "  </td>\n";
150   $s .= " </tr>\n";
151   $s .= "</table>\n";
152   return $s;
156 GET FACILITIES
158 returns all facilities or just the id for the first one
159 (FACILITY FILTERING (lemonsoftware))
161 @param string - if 'first' return first facility ordered by id
162 @return array | int for 'first' case
164 function getFacilities($first = '') {
165     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
166     $ret = array();
167     while ( $row = sqlFetchArray($r) ) {
168        $ret[] = $row;
171         if ( $first == 'first') {
172             return $ret[0]['id'];
173         } else {
174             return $ret;
175         }
179 GET SERVICE FACILITIES
181 returns all service_location facilities or just the id for the first one
182 (FACILITY FILTERING (CHEMED))
184 @param string - if 'first' return first facility ordered by id
185 @return array | int for 'first' case
187 function getServiceFacilities($first = '') {
188     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
189     $ret = array();
190     while ( $row = sqlFetchArray($r) ) {
191        $ret[] = $row;
194         if ( $first == 'first') {
195             return $ret[0]['id'];
196         } else {
197             return $ret;
198         }
201 //(CHEMED) facility filter
202 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
203     $param1 = "";
204     if ($providers_only === 'any') {
205       $param1 = " AND authorized = 1 AND active = 1 ";
206     }
207     else if ($providers_only) {
208       $param1 = " AND authorized = 1 AND calendar = 1 ";
209     }
211     //--------------------------------
212     //(CHEMED) facility filter
213     $param2 = "";
214     if ($facility) {
215       if ($GLOBALS['restrict_user_facility']) {
216         $param2 = " AND (facility_id = $facility 
217           OR  $facility IN
218                 (select facility_id 
219                 from users_facility
220                 where tablename = 'users'
221                 and table_id = id)
222                 )
223           ";
224       }
225       else {
226         $param2 = " AND facility_id = $facility ";
227       }
228     }
229     //--------------------------------
231     $command = "=";
232     if ($providerID == "%") {
233         $command = "like";
234     }
235     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
236         "from users where username != '' and active = 1 and id $command '" .
237         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
238     // sort by last name -- JRM June 2008
239     $query .= " ORDER BY lname, fname ";
240     $rez = sqlStatement($query);
241     for($iter=0; $row=sqlFetchArray($rez); $iter++)
242         $returnval[$iter]=$row;
244     //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
245     //accessible from $resultval['key']
247     if($iter==1) {
248         $akeys = array_keys($returnval[0]);
249         foreach($akeys as $key) {
250             $returnval[0][$key] = $returnval[0][$key];
251         }
252     }
253     return $returnval;
256 //same as above but does not reduce if only 1 row returned
257 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
258     $param1 = "";
259     if ($providers_only) {
260         $param1 = "AND authorized=1";
261     }
262     $command = "=";
263     if ($providerID == "%") {
264         $command = "like";
265     }
266     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
267         "from users where active = 1 and username != '' and id $command '" .
268         mysql_real_escape_string($providerID) . "' " . $param1;
270     $rez = sqlStatement($query);
271     for($iter=0; $row=sqlFetchArray($rez); $iter++)
272         $returnval[$iter]=$row;
274     return $returnval;
277 function getProviderName($providerID) {
278     $pi = getProviderInfo($providerID, 'any');
279     if (strlen($pi[0]["lname"]) > 0) {
280         return $pi[0]['fname'] . " " . $pi[0]['lname'];
281     }
282     return "";
285 function getProviderId($providerName) {
286     $query = "select id from users where username = ?";
287     $rez = sqlStatement($query, array($providerName) );
288     for($iter=0; $row=sqlFetchArray($rez); $iter++)
289         $returnval[$iter]=$row;
290     return $returnval;
293 function getEthnoRacials() {
294     $returnval = array("");
295     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
296     $rez = sqlStatement($sql);
297     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
298         if (($row["ethnoracial"] != "")) {
299             array_push($returnval, $row["ethnoracial"]);
300         }
301     }
302     return $returnval;
305 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
308     if ($dateStart && $dateEnd) {
309         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
310     }
311     else if ($dateStart && !$dateEnd) {
312         $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
313     }
314     else if (!$dateStart && $dateEnd) {
315         $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
316     }
317     else {
318         $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
319     }
321     return $res;
324 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
325 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
327   $sql = "select $given from insurance_data as insd " .
328     "left join insurance_companies as ic on ic.id = insd.provider " .
329     "where pid = ? and type = ? order by date DESC limit 1";
330   return sqlQuery($sql, array($pid, $type) );
333 function getInsuranceDataByDate($pid, $date, $type,
334   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
335 { // this must take the date in the following manner: YYYY-MM-DD
336   // this function recalls the insurance value that was most recently enterred from the
337   // given date. it will call up most recent records up to and on the date given,
338   // but not records enterred after the given date
339   $sql = "select $given from insurance_data as insd " .
340     "left join insurance_companies as ic on ic.id = provider " .
341     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
342     "type=? order by date DESC limit 1";
343   return sqlQuery($sql, array($pid,$date,$type) );
346 function getEmployerData($pid, $given = "*")
348     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
349     return sqlQuery($sql, array($pid) );
352 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
353   // When the limit is exceeded, find out what the unlimited count would be.
354   $GLOBALS['PATIENT_INC_COUNT'] = $count;
355   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
356   if ($limit != "all") {
357     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
358     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
359   }
362 function getPatientLnames($lname = "%", $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")
364     // Allow the last name to be followed by a comma and some part of a first name.
365     // New behavior for searches:
366     // Allows comma alone followed by some part of a first name
367     // If the first letter of either name is capital, searches for name starting
368     // with given substring (the expected behavior).  If it is lower case, it
369     // it searches for the substring anywhere in the name.  This applies to either
370     // last name or first name or both.  The arbitrary limit of 100 results is set
371     // in the sql query below. --Mark Leeds
372     $lname = trim($lname);
373     $fname = '';
374      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
375          $lname = trim($matches[1]);
376          $fname = trim($matches[2]);
377     }
378     $search_for_pieces1 = '';
379     $search_for_pieces2 = '';
380     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
381     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
383     $sqlBindArray = array();
384     $where = "lname LIKE ? AND fname LIKE ? ";
385     array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
386         if (!empty($GLOBALS['pt_restrict_field'])) {
387                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
388                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
389                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
390                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
391                         array_push($sqlBindArray, $_SESSION{"authUser"});
392                 }
393         }
395     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
396     if ($limit != "all") $sql .= " LIMIT $start, $limit";
398     $rez = sqlStatement($sql, $sqlBindArray);
400     for($iter=0; $row=sqlFetchArray($rez); $iter++)
401         $returnval[$iter] = $row;
403     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
404     return $returnval;
407 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")
410     $sqlBindArray = array();
411     $where = "pubpid LIKE ? ";
412     array_push($sqlBindArray, $pid."%");
413         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
414                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
415                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
416                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
417                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
418                         array_push($sqlBindArray, $_SESSION{"authUser"});
419                 }
420         }
422     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
423     if ($limit != "all") $sql .= " limit $start, $limit";
424     $rez = sqlStatement($sql, $sqlBindArray);
425     for($iter=0; $row=sqlFetchArray($rez); $iter++)
426         $returnval[$iter]=$row;
428     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
429     return $returnval;
432 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")
434   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
436   $sqlBindArray = array();
437   $where = "";
438   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
439     if ( $iter > 0 ) {
440       $where .= " or ";
441     }
442     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
443     array_push($sqlBindArray, "%".$searchTerm."%");
444   }
446   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
447   if ($limit != "all") $sql .= " limit $start, $limit";
448   $rez = sqlStatement($sql, $sqlBindArray);
449   for($iter=0; $row=sqlFetchArray($rez); $iter++)
450     $returnval[$iter]=$row;
451   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
452   return $returnval;
455 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
456   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
457   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
459         $layoutCols = split( '~', $searchFields );
460   $sqlBindArray = array();
461   $where = "";
462   $i = 0;
463   foreach ($layoutCols as $val) {
464     if (empty($val)) continue;
465                 if ( $i > 0 ) {
466                    $where .= " or ";
467                 }
468     if ($val == 'pid') {
469                 $where .= " ".add_escape_custom($val)." = ? ";
470                 array_push($sqlBindArray, $searchTerm);
471     }
472     else {
473                 $where .= " ".add_escape_custom($val)." like ? ";
474                 array_push($sqlBindArray, $searchTerm."%");
475     }
476                 $i++;
477         }
479   // If no search terms, ensure valid syntax.
480   if ($i == 0) $where = "1 = 1";
482   // If a non-empty service code was given, then restrict to patients who
483   // have been provided that service.  Since the code is used in a LIKE
484   // clause, % and _ wildcards are supported.
485   if ($search_service_code) {
486     $where = "( $where ) AND " .
487       "( SELECT COUNT(*) FROM billing AS b WHERE " .
488       "b.pid = patient_data.pid AND " .
489       "b.activity = 1 AND " .
490       "b.code_type != 'COPAY' AND " .
491       "b.code LIKE ? " .
492       ") > 0";
493     array_push($sqlBindArray, $search_service_code);
494   }
496   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
497   if ($limit != "all") $sql .= " limit $start, $limit";
498   $rez = sqlStatement($sql, $sqlBindArray);
499   for($iter=0; $row=sqlFetchArray($rez); $iter++)
500       $returnval[$iter]=$row;
501   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
502   return $returnval;
505 // return a collection of Patient PIDs
506 // new arg style by JRM March 2008
507 // 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")
508 function getPatientPID($args)
510     $pid = "%";
511     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
512     $orderby = "lname ASC, fname ASC";
513     $limit="all";
514     $start="0";
516     // alter default values if defined in the passed in args
517     if (isset($args['pid'])) { $pid = $args['pid']; }
518     if (isset($args['given'])) { $given = $args['given']; }
519     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
520     if (isset($args['limit'])) { $limit = $args['limit']; }
521     if (isset($args['start'])) { $start = $args['start']; }
523     $command = "=";
524     if ($pid == -1) $pid = "%";
525     elseif (empty($pid)) $pid = "NULL";
527     if (strstr($pid,"%")) $command = "like";
529     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
530     if ($limit != "all") $sql .= " limit $start, $limit";
532     $rez = sqlStatement($sql);
533     for($iter=0; $row=sqlFetchArray($rez); $iter++)
534         $returnval[$iter]=$row;
536     return $returnval;
539 /* return a patient's name in the format LAST, FIRST */
540 function getPatientName($pid) {
541     if (empty($pid)) return "";
542     $patientData = getPatientPID(array("pid"=>$pid));
543     if (empty($patientData[0]['lname'])) return "";
544     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
545     return $patientName;
548 /* find patient data by DOB */
549 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
551     $DOB = fixDate($DOB, $DOB);
552     $sqlBindArray = array();
553     $where = "DOB like ? ";
554     array_push($sqlBindArray, $DOB."%");
555         if (!empty($GLOBALS['pt_restrict_field'])) {
556                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
557                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
558                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
559                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
560                         array_push($sqlBindArray, $_SESSION{"authUser"});
561                 }
562         }
564     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
566     if ($limit != "all") $sql .= " LIMIT $start, $limit";
568     $rez = sqlStatement($sql, $sqlBindArray);
569     for($iter=0; $row=sqlFetchArray($rez); $iter++)
570         $returnval[$iter]=$row;
572     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
573     return $returnval;
576 /* find patient data by SSN */
577 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
579     $sqlBindArray = array();
580     $where = "ss LIKE ?";
581     array_push($sqlBindArray, $ss."%");
582     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
583     if ($limit != "all") $sql .= " LIMIT $start, $limit";
585     $rez = sqlStatement($sql, $sqlBindArray);
586     for($iter=0; $row=sqlFetchArray($rez); $iter++)
587         $returnval[$iter]=$row;
589     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
590     return $returnval;
593 //(CHEMED) Search by phone number
594 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
596     $phone = ereg_replace( "[[:punct:]]","", $phone );
597     $sqlBindArray = array();
598     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
599     array_push($sqlBindArray, $phone);
600     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
601     if ($limit != "all") $sql .= " LIMIT $start, $limit";
603     $rez = sqlStatement($sql, $sqlBindArray);
604     for($iter=0; $row=sqlFetchArray($rez); $iter++)
605         $returnval[$iter]=$row;
607     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
608     return $returnval;
611 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
613     $sql="select $given from patient_data order by $orderby";
615     if ($limit != "all")
616         $sql .= " limit $start, $limit";
618     $rez = sqlStatement($sql);
619     for($iter=0; $row=sqlFetchArray($rez); $iter++)
620         $returnval[$iter]=$row;
622     return $returnval;
625 //----------------------input functions
626 function newPatientData(    $db_id="",
627                 $title = "",
628                 $fname = "",
629                 $lname = "",
630                 $mname = "",
631                 $sex = "",
632                 $DOB = "",
633                 $street = "",
634                 $postal_code = "",
635                 $city = "",
636                 $state = "",
637                 $country_code = "",
638                 $ss = "",
639                 $occupation = "",
640                 $phone_home = "",
641                 $phone_biz = "",
642                 $phone_contact = "",
643                 $status = "",
644                 $contact_relationship = "",
645                 $referrer = "",
646                 $referrerID = "",
647                 $email = "",
648                 $language = "",
649                 $ethnoracial = "",
650                 $interpretter = "",
651                 $migrantseasonal = "",
652                 $family_size = "",
653                 $monthly_income = "",
654                 $homeless = "",
655                 $financial_review = "",
656                 $pubpid = "",
657                 $pid = "MAX(pid)+1",
658                 $providerID = "",
659                 $genericname1 = "",
660                 $genericval1 = "",
661                 $genericname2 = "",
662                 $genericval2 = "",
663                 $phone_cell = "",
664                 $hipaa_mail = "",
665                 $hipaa_voice = "",
666                 $squad = 0,
667                 $pharmacy_id = 0,
668                 $drivers_license = "",
669                 $hipaa_notice = "",
670                 $hipaa_message = "",
671                 $regdate = ""
672             )
674     $DOB = fixDate($DOB);
675     $regdate = fixDate($regdate);
677     $fitness = 0;
678     $referral_source = '';
679     if ($pid) {
680         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
681         // Check for brain damage:
682         if ($db_id != $rez['id']) {
683             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
684               $rez['id'] . "' to '$db_id' for pid '$pid'";
685             die($errmsg);
686         }
687         $fitness = $rez['fitness'];
688         $referral_source = $rez['referral_source'];
689     }
691     // Get the default price level.
692     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
693       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
694     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
696     $query = ("replace into patient_data set
697         id='$db_id',
698         title='$title',
699         fname='$fname',
700         lname='$lname',
701         mname='$mname',
702         sex='$sex',
703         DOB='$DOB',
704         street='$street',
705         postal_code='$postal_code',
706         city='$city',
707         state='$state',
708         country_code='$country_code',
709         drivers_license='$drivers_license',
710         ss='$ss',
711         occupation='$occupation',
712         phone_home='$phone_home',
713         phone_biz='$phone_biz',
714         phone_contact='$phone_contact',
715         status='$status',
716         contact_relationship='$contact_relationship',
717         referrer='$referrer',
718         referrerID='$referrerID',
719         email='$email',
720         language='$language',
721         ethnoracial='$ethnoracial',
722         interpretter='$interpretter',
723         migrantseasonal='$migrantseasonal',
724         family_size='$family_size',
725         monthly_income='$monthly_income',
726         homeless='$homeless',
727         financial_review='$financial_review',
728         pubpid='$pubpid',
729         pid = $pid,
730         providerID = '$providerID',
731         genericname1 = '$genericname1',
732         genericval1 = '$genericval1',
733         genericname2 = '$genericname2',
734         genericval2 = '$genericval2',
735         phone_cell = '$phone_cell',
736         pharmacy_id = '$pharmacy_id',
737         hipaa_mail = '$hipaa_mail',
738         hipaa_voice = '$hipaa_voice',
739         hipaa_notice = '$hipaa_notice',
740         hipaa_message = '$hipaa_message',
741         squad = '$squad',
742         fitness='$fitness',
743         referral_source='$referral_source',
744         regdate='$regdate',
745         pricelevel='$pricelevel',
746         date=NOW()");
748     $id = sqlInsert($query);
750     if ( !$db_id ) {
751       // find the last inserted id for new patient case
752       $db_id = mysql_insert_id();
753     }
755     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
757     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
758                 $phone_biz,$phone_cell,$email,$pid);
760     return $foo['pid'];
763 // Supported input date formats are:
764 //   mm/dd/yyyy
765 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
766 //   yyyy/mm/dd
767 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
769 function fixDate($date, $default="0000-00-00") {
770     $fixed_date = $default;
771     $date = trim($date);
772     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
773         $dmy = preg_split("'[/.-]'", $date);
774         if ($dmy[0] > 99) {
775             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
776         } else {
777             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
778               if ($dmy[2] < 1000) $dmy[2] += 1900;
779               if ($dmy[2] < 1910) $dmy[2] += 100;
780             }
781             // phone_country_code indicates format of ambiguous input dates.
782             if ($GLOBALS['phone_country_code'] == 1)
783               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
784             else
785               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
786         }
787     }
789     return $fixed_date;
792 function pdValueOrNull($key, $value) {
793   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
794     substr($key, 0, 8) == 'userdate') &&
795     (empty($value) || $value == '0000-00-00'))
796   {
797     return "NULL";
798   }
799   else {
800     return "'$value'";
801   }
804 // Create or update patient data from an array.
806 function updatePatientData($pid, $new, $create=false)
808   /*******************************************************************
809     $real = getPatientData($pid);
810     $new['DOB'] = fixDate($new['DOB']);
811     while(list($key, $value) = each ($new))
812         $real[$key] = $value;
813     $real['date'] = "'+NOW()+'";
814     $real['id'] = "";
815     $sql = "insert into patient_data set ";
816     while(list($key, $value) = each($real))
817         $sql .= $key." = '$value', ";
818     $sql = substr($sql, 0, -2);
819     return sqlInsert($sql);
820   *******************************************************************/
822   // The above was broken, though seems intent to insert a new patient_data
823   // row for each update.  A good idea, but nothing is doing that yet so
824   // the code below does not yet attempt it.
826   $new['DOB'] = fixDate($new['DOB']);
828   if ($create) {
829     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
830     foreach ($new as $key => $value) {
831       if ($key == 'id') continue;
832       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
833     }
834     $db_id = sqlInsert($sql);
835   }
836   else {
837     $db_id = $new['id'];
838     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
839     // Check for brain damage:
840     if ($pid != $rez['pid']) {
841       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
842         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
843       die($errmsg);
844     }
845     $sql = "UPDATE patient_data SET date = NOW()";
846     foreach ($new as $key => $value) {
847       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
848     }
849     $sql .= " WHERE id = '$db_id'";
850     sqlStatement($sql);
851   }
853   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
854   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
855     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
856     $rez['phone_cell'],$rez['email'],$rez['pid']);
858   return $db_id;
861 function newEmployerData(    $pid,
862                 $name = "",
863                 $street = "",
864                 $postal_code = "",
865                 $city = "",
866                 $state = "",
867                 $country = ""
868             )
870     return sqlInsert("insert into employer_data set
871         name='$name',
872         street='$street',
873         postal_code='$postal_code',
874         city='$city',
875         state='$state',
876         country='$country',
877         pid='$pid',
878         date=NOW()
879         ");
882 // Create or update employer data from an array.
884 function updateEmployerData($pid, $new, $create=false)
886   $colnames = array('name','street','city','state','postal_code','country');
888   if ($create) {
889     $set .= "pid = '$pid', date = NOW()";
890     foreach ($colnames as $key) {
891       $value = isset($new[$key]) ? $new[$key] : '';
892       $set .= ", `$key` = '$value'";
893     }
894     return sqlInsert("INSERT INTO employer_data SET $set");
895   }
896   else {
897     $set = '';
898     $old = getEmployerData($pid);
899     $modified = false;
900     foreach ($colnames as $key) {
901       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
902       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
903         $value = $new[$key];
904         $modified = true;
905       }
906       $set .= "`$key` = '$value', ";
907     }
908     if ($modified) {
909       $set .= "pid = '$pid', date = NOW()";
910       return sqlInsert("INSERT INTO employer_data SET $set");
911     }
912     return $old['id'];
913   }
916 // This updates or adds the given insurance data info, while retaining any
917 // previously added insurance_data rows that should be preserved.
918 // This does not directly support the maintenance of non-current insurance.
920 function newInsuranceData(
921   $pid,
922   $type = "",
923   $provider = "",
924   $policy_number = "",
925   $group_number = "",
926   $plan_name = "",
927   $subscriber_lname = "",
928   $subscriber_mname = "",
929   $subscriber_fname = "",
930   $subscriber_relationship = "",
931   $subscriber_ss = "",
932   $subscriber_DOB = "",
933   $subscriber_street = "",
934   $subscriber_postal_code = "",
935   $subscriber_city = "",
936   $subscriber_state = "",
937   $subscriber_country = "",
938   $subscriber_phone = "",
939   $subscriber_employer = "",
940   $subscriber_employer_street = "",
941   $subscriber_employer_city = "",
942   $subscriber_employer_postal_code = "",
943   $subscriber_employer_state = "",
944   $subscriber_employer_country = "",
945   $copay = "",
946   $subscriber_sex = "",
947   $effective_date = "0000-00-00",
948   $accept_assignment = "TRUE")
950   if (strlen($type) <= 0) return FALSE;
952   // If a bad date was passed, err on the side of caution.
953   $effective_date = fixDate($effective_date, date('Y-m-d'));
955   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
956     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
957   $idrow = sqlFetchArray($idres);
959   // Replace the most recent entry in any of the following cases:
960   // * Its effective date is >= this effective date.
961   // * It is the first entry and it has no (insurance) provider.
962   // * There is no encounter that is earlier than the new effective date but
963   //   on or after the old effective date.
964   // Otherwise insert a new entry.
966   $replace = false;
967   if ($idrow) {
968     if (strcmp($idrow['date'], $effective_date) > 0) {
969       $replace = true;
970     }
971     else {
972       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
973         $replace = true;
974       }
975       else {
976         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
977           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
978           "date >= '" . $idrow['date'] . " 00:00:00'");
979         if ($ferow['count'] == 0) $replace = true;
980       }
981     }
982   }
984   if ($replace) {
986     // TBD: This is a bit dangerous in that a typo in entering the effective
987     // date can wipe out previous insurance history.  So we want some data
988     // entry validation somewhere.
989     sqlStatement("DELETE FROM insurance_data WHERE " .
990       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
991       "id != " . $idrow['id']);
993     $data = array();
994     $data['type'] = $type;
995     $data['provider'] = $provider;
996     $data['policy_number'] = $policy_number;
997     $data['group_number'] = $group_number;
998     $data['plan_name'] = $plan_name;
999     $data['subscriber_lname'] = $subscriber_lname;
1000     $data['subscriber_mname'] = $subscriber_mname;
1001     $data['subscriber_fname'] = $subscriber_fname;
1002     $data['subscriber_relationship'] = $subscriber_relationship;
1003     $data['subscriber_ss'] = $subscriber_ss;
1004     $data['subscriber_DOB'] = $subscriber_DOB;
1005     $data['subscriber_street'] = $subscriber_street;
1006     $data['subscriber_postal_code'] = $subscriber_postal_code;
1007     $data['subscriber_city'] = $subscriber_city;
1008     $data['subscriber_state'] = $subscriber_state;
1009     $data['subscriber_country'] = $subscriber_country;
1010     $data['subscriber_phone'] = $subscriber_phone;
1011     $data['subscriber_employer'] = $subscriber_employer;
1012     $data['subscriber_employer_city'] = $subscriber_employer_city;
1013     $data['subscriber_employer_street'] = $subscriber_employer_street;
1014     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1015     $data['subscriber_employer_state'] = $subscriber_employer_state;
1016     $data['subscriber_employer_country'] = $subscriber_employer_country;
1017     $data['copay'] = $copay;
1018     $data['subscriber_sex'] = $subscriber_sex;
1019     $data['pid'] = $pid;
1020     $data['date'] = $effective_date;
1021     $data['accept_assignment'] = $accept_assignment;
1022     updateInsuranceData($idrow['id'], $data);
1023     return $idrow['id'];
1024   }
1025   else {
1026     return sqlInsert("INSERT INTO insurance_data SET
1027       type = '$type',
1028       provider = '$provider',
1029       policy_number = '$policy_number',
1030       group_number = '$group_number',
1031       plan_name = '$plan_name',
1032       subscriber_lname = '$subscriber_lname',
1033       subscriber_mname = '$subscriber_mname',
1034       subscriber_fname = '$subscriber_fname',
1035       subscriber_relationship = '$subscriber_relationship',
1036       subscriber_ss = '$subscriber_ss',
1037       subscriber_DOB = '$subscriber_DOB',
1038       subscriber_street = '$subscriber_street',
1039       subscriber_postal_code = '$subscriber_postal_code',
1040       subscriber_city = '$subscriber_city',
1041       subscriber_state = '$subscriber_state',
1042       subscriber_country = '$subscriber_country',
1043       subscriber_phone = '$subscriber_phone',
1044       subscriber_employer = '$subscriber_employer',
1045       subscriber_employer_city = '$subscriber_employer_city',
1046       subscriber_employer_street = '$subscriber_employer_street',
1047       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1048       subscriber_employer_state = '$subscriber_employer_state',
1049       subscriber_employer_country = '$subscriber_employer_country',
1050       copay = '$copay',
1051       subscriber_sex = '$subscriber_sex',
1052       pid = '$pid',
1053       date = '$effective_date',
1054       accept_assignment = '$accept_assignment'
1055     ");
1056   }
1059 // This is used internally only.
1060 function updateInsuranceData($id, $new)
1062   $fields = sqlListFields("insurance_data");
1063   $use = array();
1065   while(list($key, $value) = each ($new)) {
1066     if (in_array($key, $fields)) {
1067       $use[$key] = $value;
1068     }
1069   }
1071   $sql = "UPDATE insurance_data SET ";
1072   while(list($key, $value) = each($use))
1073     $sql .= "`$key` = '$value', ";
1074   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1076   sqlStatement($sql);
1079 function newHistoryData($pid, $new=false) {
1080   $arraySqlBind = array();
1081   $sql = "insert into history_data set pid = ?, date = NOW()";
1082   array_push($arraySqlBind,$pid);
1083   if ($new) {
1084     while(list($key, $value) = each($new)) {
1085       array_push($arraySqlBind,$value);
1086       $sql .= ", `$key` = ?";
1087     }
1088   }
1089   return sqlInsert($sql, $arraySqlBind );
1092 function updateHistoryData($pid,$new)
1094         $real = getHistoryData($pid);
1095         while(list($key, $value) = each ($new))
1096                 $real[$key] = $value;
1097         $real['id'] = "";
1098         // need to unset date, so can reset it below
1099         unset($real['date']);
1101         $arraySqlBind = array();
1102         $sql = "insert into history_data set `date` = NOW(), ";
1103         while(list($key, $value) = each($real)) {
1104                 array_push($arraySqlBind,$value);
1105                 $sql .= "`$key` = ?, ";
1106         }
1107         $sql = substr($sql, 0, -2);
1109         return sqlInsert($sql, $arraySqlBind );
1112 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1113                 $phone_biz,$phone_cell,$email,$pid="")
1115     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1116     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1118     $db = $GLOBALS['adodb']['db'];
1119     $customer_info = array();
1121     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1122     $result = $db->Execute($sql);
1123     if ($result && !$result->EOF) {
1124         $customer_info['foreign_update'] = true;
1125         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1126         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1127     }
1129     ///xml rpc code to connect to accounting package and add user to it
1130     $customer_info['firstname'] = $fname;
1131     $customer_info['lastname'] = $lname;
1132     $customer_info['address'] = $street;
1133     $customer_info['suburb'] = $city;
1134     $customer_info['state'] = $state;
1135     $customer_info['postcode'] = $postal_code;
1137     //ezybiz wants state as a code rather than abbreviation
1138     $customer_info['geo_zone_id'] = "";
1139     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1140     $db = $GLOBALS['adodb']['db'];
1141     $result = $db->Execute($sql);
1142     if ($result && !$result->EOF) {
1143         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1144     }
1146     //ezybiz wants country as a code rather than abbreviation
1147     $customer_info['geo_country_id'] = "";
1148     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1149     $db = $GLOBALS['adodb']['db'];
1150     $result = $db->Execute($sql);
1151     if ($result && !$result->EOF) {
1152         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1153     }
1155     $customer_info['phone1'] = $phone_home;
1156     $customer_info['phone1comment'] = "Home Phone";
1157     $customer_info['phone2'] = $phone_biz;
1158     $customer_info['phone2comment'] = "Business Phone";
1159     $customer_info['phone3'] = $phone_cell;
1160     $customer_info['phone3comment'] = "Cell Phone";
1161     $customer_info['email'] = $email;
1162     $customer_info['customernumber'] = $pid;
1164     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1165     $ws = new WSWrapper($function);
1167     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1168     if (is_numeric($ws->value)) {
1169         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1170         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1171     }
1174 // Returns Age 
1175 //   in months if < 2 years old
1176 //   in years  if > 2 years old
1177 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1178 // (optional) nowYMD is a date in YYYYMMDD format
1179 function getPatientAge($dobYMD, $nowYMD=null)
1181     // strip any dashes from the DOB
1182     $dobYMD = preg_replace("/-/", "", $dobYMD);
1183     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1184     
1185     // set the 'now' date values
1186     if ($nowYMD == null) {
1187         $nowDay = date("d");
1188         $nowMonth = date("m");
1189         $nowYear = date("Y");
1190     }
1191     else {
1192         $nowDay = substr($nowYMD,6,2);
1193         $nowMonth = substr($nowYMD,4,2);
1194         $nowYear = substr($nowYMD,0,4);
1195     }
1197     $dayDiff = $nowDay - $dobDay;
1198     $monthDiff = $nowMonth - $dobMonth;
1199     $yearDiff = $nowYear - $dobYear;
1201     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1203     if ( $ageInMonths > 24 ) {
1204         $age = $yearDiff;
1205         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1206         else if ($monthDiff < 0) { $age -= 1; }
1207     }
1208     else  {
1209         $age = "$ageInMonths month"; 
1210     }
1212     return $age;
1216 // Returns Age in days
1217 //   in months if < 2 years old
1218 //   in years  if > 2 years old
1219 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1220 // (optional) nowYMD is a date in YYYYMMDD format
1221 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1222     $age = -1;
1224     // strip any dashes from the DOB
1225     $dobYMD = preg_replace("/-/", "", $dobYMD);
1226     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1227     
1228     // set the 'now' date values
1229     if ($nowYMD == null) {
1230         $nowDay = date("d");
1231         $nowMonth = date("m");
1232         $nowYear = date("Y");
1233     }
1234     else {
1235         $nowDay = substr($nowYMD,6,2);
1236         $nowMonth = substr($nowYMD,4,2);
1237         $nowYear = substr($nowYMD,0,4);
1238     }
1240     // do the date math
1241     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1242     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1243     $timediff = $nowtime - $dobtime;
1244     $age = $timediff / 86400;
1246     return $age;
1249 function dateToDB ($date)
1251     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1252     return $date;
1256 // ----------------------------------------------------------------------------
1258  * DROPDOWN FOR COUNTRIES
1259  * 
1260  * build a dropdown with all countries from geo_country_reference
1261  * 
1262  * @param int $selected - id for selected record
1263  * @param string $name - the name/id for select form
1264  * @return void - just echo the html encoded string
1265  */
1266 function dropdown_countries($selected = 0, $name = 'country_code') {
1267     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1269     $string = "<select name='$name' id='$name'>";
1270     while ( $row = sqlFetchArray($r) ) {
1271         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1272         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1273     }
1275     $string .= '</select>';
1276     echo $string;
1280 // ----------------------------------------------------------------------------
1282  * DROPDOWN FOR YES/NO
1283  * 
1284  * build a dropdown with two options (yes - 1, no - 0)
1285  * 
1286  * @param int $selected - id for selected record
1287  * @param string $name - the name/id for select form
1288  * @return void - just echo the html encoded string 
1289  */
1290 function dropdown_yesno($selected = 0, $name = 'yesno') {
1291     $string = "<select name='$name' id='$name'>";
1293     $selected = (int)$selected;
1294     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1295     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1297     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1298     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1299     $string .= '</select>';
1301     echo $string;
1304 // ----------------------------------------------------------------------------
1306  * DROPDOWN FOR MALE/FEMALE options
1307  * 
1308  * build a dropdown with three options (unselected/male/female)
1309  * 
1310  * @param int $selected - id for selected record
1311  * @param string $name - the name/id for select form
1312  * @return void - just echo the html encoded string
1313  */
1314 function dropdown_sex($selected = 0, $name = 'sex') {
1315     $string = "<select name='$name' id='$name'>";
1317     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1318     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1319     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1321     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1322     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1323     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1324     $string .= '</select>';
1326     echo $string;
1329 // ----------------------------------------------------------------------------
1331  * DROPDOWN FOR MARITAL STATUS
1332  * 
1333  * build a dropdown with marital status
1334  * 
1335  * @param int $selected - id for selected record
1336  * @param string $name - the name/id for select form
1337  * @return void - just echo the html encoded string
1338  */
1339 function dropdown_marital($selected = 0, $name = 'status') {
1340     $string = "<select name='$name' id='$name'>";
1342     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1344     foreach ( $statii as $st ) {
1345         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1346         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1347     }
1349     $string .= '</select>';
1351     echo $string;
1354 // ----------------------------------------------------------------------------
1356  * DROPDOWN FOR PROVIDERS
1357  * 
1358  * build a dropdown with all providers
1359  * 
1360  * @param int $selected - id for selected record
1361  * @param string $name - the name/id for select form
1362  * @return void - just echo the html encoded string
1363  */
1364 function dropdown_providers($selected = 0, $name = 'status') {
1365     $provideri = getProviderInfo();
1367     $string = "<select name='$name' id='$name'>";
1368     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1369     foreach ( $provideri as $s ) {
1370         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1371         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1372     }
1374     $string .= '</select>';
1376     echo $string;
1379 // ----------------------------------------------------------------------------
1381  * DROPDOWN FOR INSURANCE COMPANIES
1382  * 
1383  * build a dropdown with all insurers
1384  * 
1385  * @param int $selected - id for selected record
1386  * @param string $name - the name/id for select form
1387  * @return void - just echo the html encoded string
1388  */
1389 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1390     $insurancei = getInsuranceProviders();
1392     $string = "<select name='$name' id='$name'>";
1393     $string .= '<option value="0">Onbekend</option>';
1394     foreach ( $insurancei as $iid => $iname ) {
1395         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1396         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1397     }
1399     $string .= '</select>';
1401     echo $string;
1405 // ----------------------------------------------------------------------------
1407  * COUNTRY CODE
1408  * 
1409  * return the name or the country code, function of arguments
1410  * 
1411  * @param int $country_code
1412  * @param string $country_name
1413  * @return string | int - name or code
1414  */
1415 function country_code($country_code = 0, $country_name = '') {
1416     $strint = '';
1417     if ( $country_code ) {
1418         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1419     } else {
1420         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1421     }
1423     $db = $GLOBALS['adodb']['db'];
1424     $result = $db->Execute($sql);
1425     if ($result && !$result->EOF) {
1426         $strint = $result->fields['res'];
1427     }
1429     return $strint;
1432 function DBToDate ($date)
1434     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1435     return $date;
1438 function get_patient_balance($pid) {
1439   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1440     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1441       "pid = ? AND activity = 1", array($pid) );
1442     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1443       "pid = ?", array($pid) );
1444     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1445       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1446       "pid = ?", array($pid) );
1447     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1448       - $drow['payments'] - $drow['adjustments']);
1449   }
1450   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1451     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1452     $conn = $GLOBALS['adodb']['db'];
1453     $customer_info['id'] = 0;
1454     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1455       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1456       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1457       "im.foreign_table = 'customer'";
1458     $result = $conn->Execute($sql);
1459     if($result && !$result->EOF) {
1460       $customer_info['id'] = $result->fields['foreign_id'];
1461     }
1462     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1463     $ws = new WSWrapper($function);
1464     if(is_numeric($ws->value)) {
1465       return sprintf('%01.2f', $ws->value);
1466     }
1467   }
1468   return '';
1471 // Function to check if patient is deceased.
1472 //  Param:
1473 //    $pid  - patient id
1474 //    $date - date checking if deceased (will default to current date if blank)
1475 //  Return:
1476 //    If deceased, then will return the number of
1477 //      days that patient has been deceased.
1478 //    If not deceased, then will return false.
1479 function is_patient_deceased($pid,$date='') {
1481   // Set date to current if not set
1482   $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1484   // Query for deceased status (gets days deceased if patient is deceased)
1485   $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1486                       "FROM `patient_data` " .
1487                       "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1489   if (empty($results)) {
1490     // Patient is alive, so return false
1491     return false;
1492   }
1493   else {
1494     // Patient is dead, so return the number of days patient has been deceased.
1495     //  Don't let it be zero days or else will confuse calls to this function.
1496     if ($results['days_deceased'] === 0) {
1497       $results['days_deceased'] = 1;
1498     }
1499     return $results['days_deceased'];
1500   }