Modified documentation to recommend no longer using the mode, prepend, or append...
[openemr.git] / library / patient.inc
blobe970cdeba586ca3a1468bffefb28795c2d529bba
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 include_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 = "*")
307     $sql = "select $given from history_data where pid=? order by date DESC limit 0,1";
308     return sqlQuery($sql, array($pid) );
311 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
312 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
314   $sql = "select $given from insurance_data as insd " .
315     "left join insurance_companies as ic on ic.id = insd.provider " .
316     "where pid = ? and type = ? order by date DESC limit 1";
317   return sqlQuery($sql, array($pid, $type) );
320 function getInsuranceDataByDate($pid, $date, $type,
321   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
322 { // this must take the date in the following manner: YYYY-MM-DD
323   // this function recalls the insurance value that was most recently enterred from the
324   // given date. it will call up most recent records up to and on the date given,
325   // but not records enterred after the given date
326   $sql = "select $given from insurance_data as insd " .
327     "left join insurance_companies as ic on ic.id = provider " .
328     "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
329     "type=? order by date DESC limit 1";
330   return sqlQuery($sql, array($pid,$date,$type) );
333 function getEmployerData($pid, $given = "*")
335     $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
336     return sqlQuery($sql, array($pid) );
339 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
340   // When the limit is exceeded, find out what the unlimited count would be.
341   $GLOBALS['PATIENT_INC_COUNT'] = $count;
342   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
343   if ($limit != "all") {
344     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
345     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
346   }
349 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")
351     // Allow the last name to be followed by a comma and some part of a first name.
352     // New behavior for searches:
353     // Allows comma alone followed by some part of a first name
354     // If the first letter of either name is capital, searches for name starting
355     // with given substring (the expected behavior).  If it is lower case, it
356     // it searches for the substring anywhere in the name.  This applies to either
357     // last name or first name or both.  The arbitrary limit of 100 results is set
358     // in the sql query below. --Mark Leeds
359     $lname = trim($lname);
360     $fname = '';
361      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
362          $lname = trim($matches[1]);
363          $fname = trim($matches[2]);
364     }
365     $search_for_pieces1 = '';
366     $search_for_pieces2 = '';
367     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
368     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
370     $sqlBindArray = array();
371     $where = "lname LIKE ? AND fname LIKE ? ";
372     array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
373         if (!empty($GLOBALS['pt_restrict_field'])) {
374                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
375                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
376                             " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
377                             add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
378                         array_push($sqlBindArray, $_SESSION{"authUser"});
379                 }
380         }
382     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
383     if ($limit != "all") $sql .= " LIMIT $start, $limit";
385     $rez = sqlStatement($sql, $sqlBindArray);
387     for($iter=0; $row=sqlFetchArray($rez); $iter++)
388         $returnval[$iter] = $row;
390     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
391     return $returnval;
394 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")
397     $sqlBindArray = array();
398     $where = "pubpid LIKE ? ";
399     array_push($sqlBindArray, $pid."%");
400         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
401                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
402                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
403                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
404                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
405                         array_push($sqlBindArray, $_SESSION{"authUser"});
406                 }
407         }
409     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
410     if ($limit != "all") $sql .= " limit $start, $limit";
411     $rez = sqlStatement($sql, $sqlBindArray);
412     for($iter=0; $row=sqlFetchArray($rez); $iter++)
413         $returnval[$iter]=$row;
415     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
416     return $returnval;
419 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")
421   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
423   $sqlBindArray = array();
424   $where = "";
425   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
426     if ( $iter > 0 ) {
427       $where .= " or ";
428     }
429     $where .= " ".add_escape_custom($row["field_id"])." like ? ";
430     array_push($sqlBindArray, "%".$searchTerm."%");
431   }
433   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
434   if ($limit != "all") $sql .= " limit $start, $limit";
435   $rez = sqlStatement($sql, $sqlBindArray);
436   for($iter=0; $row=sqlFetchArray($rez); $iter++)
437     $returnval[$iter]=$row;
438   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
439   return $returnval;
442 function getByPatientDemographicsFilter($searchFields, $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" )
444         $layoutCols = split( '~', $searchFields );
445   $sqlBindArray = array();
446   $where = "";
447   $i = 0;
448   foreach ($layoutCols as $val ) {
449                 if ( $i > 0 ) {
450                    $where .= " or ";
451                 }
452     if ($val == 'pid') {
453                 $where .= " ".add_escape_custom($val)." = ? ";
454                 array_push($sqlBindArray, $searchTerm);
455     }
456     else {
457                 $where .= " ".add_escape_custom($val)." like ? ";
458                 array_push($sqlBindArray, $searchTerm."%");
459     }
460                 $i++;
461         }
462   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
463   if ($limit != "all") $sql .= " limit $start, $limit";
464   $rez = sqlStatement($sql, $sqlBindArray);
465   for($iter=0; $row=sqlFetchArray($rez); $iter++)
466       $returnval[$iter]=$row;
467   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
468   return $returnval;
471 // return a collection of Patient PIDs
472 // new arg style by JRM March 2008
473 // 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")
474 function getPatientPID($args)
476     $pid = "%";
477     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
478     $orderby = "lname ASC, fname ASC";
479     $limit="all";
480     $start="0";
482     // alter default values if defined in the passed in args
483     if (isset($args['pid'])) { $pid = $args['pid']; }
484     if (isset($args['given'])) { $given = $args['given']; }
485     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
486     if (isset($args['limit'])) { $limit = $args['limit']; }
487     if (isset($args['start'])) { $start = $args['start']; }
489     $command = "=";
490     if ($pid == -1) $pid = "%";
491     elseif (empty($pid)) $pid = "NULL";
493     if (strstr($pid,"%")) $command = "like";
495     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
496     if ($limit != "all") $sql .= " limit $start, $limit";
498     $rez = sqlStatement($sql);
499     for($iter=0; $row=sqlFetchArray($rez); $iter++)
500         $returnval[$iter]=$row;
502     return $returnval;
505 /* return a patient's name in the format LAST, FIRST */
506 function getPatientName($pid) {
507     if (empty($pid)) return "";
508     $patientData = getPatientPID(array("pid"=>$pid));
509     if (empty($patientData[0]['lname'])) return "";
510     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
511     return $patientName;
514 /* find patient data by DOB */
515 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
517     $DOB = fixDate($DOB, $DOB);
518     $sqlBindArray = array();
519     $where = "DOB like ? ";
520     array_push($sqlBindArray, $DOB."%");
521         if (!empty($GLOBALS['pt_restrict_field'])) {
522                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
523                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
524                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
525                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
526                         array_push($sqlBindArray, $_SESSION{"authUser"});
527                 }
528         }
530     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
532     if ($limit != "all") $sql .= " LIMIT $start, $limit";
534     $rez = sqlStatement($sql, $sqlBindArray);
535     for($iter=0; $row=sqlFetchArray($rez); $iter++)
536         $returnval[$iter]=$row;
538     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
539     return $returnval;
542 /* find patient data by SSN */
543 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
545     $sqlBindArray = array();
546     $where = "ss LIKE ?";
547     array_push($sqlBindArray, $ss."%");
548     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
549     if ($limit != "all") $sql .= " LIMIT $start, $limit";
551     $rez = sqlStatement($sql, $sqlBindArray);
552     for($iter=0; $row=sqlFetchArray($rez); $iter++)
553         $returnval[$iter]=$row;
555     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
556     return $returnval;
559 //(CHEMED) Search by phone number
560 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
562     $phone = ereg_replace( "[[:punct:]]","", $phone );
563     $sqlBindArray = array();
564     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
565     array_push($sqlBindArray, $phone);
566     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
567     if ($limit != "all") $sql .= " LIMIT $start, $limit";
569     $rez = sqlStatement($sql, $sqlBindArray);
570     for($iter=0; $row=sqlFetchArray($rez); $iter++)
571         $returnval[$iter]=$row;
573     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
574     return $returnval;
577 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
579     $sql="select $given from patient_data order by $orderby";
581     if ($limit != "all")
582         $sql .= " limit $start, $limit";
584     $rez = sqlStatement($sql);
585     for($iter=0; $row=sqlFetchArray($rez); $iter++)
586         $returnval[$iter]=$row;
588     return $returnval;
591 //----------------------input functions
592 function newPatientData(    $db_id="",
593                 $title = "",
594                 $fname = "",
595                 $lname = "",
596                 $mname = "",
597                 $sex = "",
598                 $DOB = "",
599                 $street = "",
600                 $postal_code = "",
601                 $city = "",
602                 $state = "",
603                 $country_code = "",
604                 $ss = "",
605                 $occupation = "",
606                 $phone_home = "",
607                 $phone_biz = "",
608                 $phone_contact = "",
609                 $status = "",
610                 $contact_relationship = "",
611                 $referrer = "",
612                 $referrerID = "",
613                 $email = "",
614                 $language = "",
615                 $ethnoracial = "",
616                 $interpretter = "",
617                 $migrantseasonal = "",
618                 $family_size = "",
619                 $monthly_income = "",
620                 $homeless = "",
621                 $financial_review = "",
622                 $pubpid = "",
623                 $pid = "MAX(pid)+1",
624                 $providerID = "",
625                 $genericname1 = "",
626                 $genericval1 = "",
627                 $genericname2 = "",
628                 $genericval2 = "",
629                 $phone_cell = "",
630                 $hipaa_mail = "",
631                 $hipaa_voice = "",
632                 $squad = 0,
633                 $pharmacy_id = 0,
634                 $drivers_license = "",
635                 $hipaa_notice = "",
636                 $hipaa_message = "",
637                 $regdate = ""
638             )
640     $DOB = fixDate($DOB);
641     $regdate = fixDate($regdate);
643     $fitness = 0;
644     $referral_source = '';
645     if ($pid) {
646         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
647         // Check for brain damage:
648         if ($db_id != $rez['id']) {
649             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
650               $rez['id'] . "' to '$db_id' for pid '$pid'";
651             die($errmsg);
652         }
653         $fitness = $rez['fitness'];
654         $referral_source = $rez['referral_source'];
655     }
657     // Get the default price level.
658     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
659       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
660     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
662     $query = ("replace into patient_data set
663         id='$db_id',
664         title='$title',
665         fname='$fname',
666         lname='$lname',
667         mname='$mname',
668         sex='$sex',
669         DOB='$DOB',
670         street='$street',
671         postal_code='$postal_code',
672         city='$city',
673         state='$state',
674         country_code='$country_code',
675         drivers_license='$drivers_license',
676         ss='$ss',
677         occupation='$occupation',
678         phone_home='$phone_home',
679         phone_biz='$phone_biz',
680         phone_contact='$phone_contact',
681         status='$status',
682         contact_relationship='$contact_relationship',
683         referrer='$referrer',
684         referrerID='$referrerID',
685         email='$email',
686         language='$language',
687         ethnoracial='$ethnoracial',
688         interpretter='$interpretter',
689         migrantseasonal='$migrantseasonal',
690         family_size='$family_size',
691         monthly_income='$monthly_income',
692         homeless='$homeless',
693         financial_review='$financial_review',
694         pubpid='$pubpid',
695         pid = $pid,
696         providerID = '$providerID',
697         genericname1 = '$genericname1',
698         genericval1 = '$genericval1',
699         genericname2 = '$genericname2',
700         genericval2 = '$genericval2',
701         phone_cell = '$phone_cell',
702         pharmacy_id = '$pharmacy_id',
703         hipaa_mail = '$hipaa_mail',
704         hipaa_voice = '$hipaa_voice',
705         hipaa_notice = '$hipaa_notice',
706         hipaa_message = '$hipaa_message',
707         squad = '$squad',
708         fitness='$fitness',
709         referral_source='$referral_source',
710         regdate='$regdate',
711         pricelevel='$pricelevel',
712         date=NOW()");
714     $id = sqlInsert($query);
716     if ( !$db_id ) {
717       // find the last inserted id for new patient case
718       $db_id = mysql_insert_id();
719     }
721     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
723     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
724                 $phone_biz,$phone_cell,$email,$pid);
726     return $foo['pid'];
729 // Supported input date formats are:
730 //   mm/dd/yyyy
731 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
732 //   yyyy/mm/dd
733 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
735 function fixDate($date, $default="0000-00-00") {
736     $fixed_date = $default;
737     $date = trim($date);
738     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
739         $dmy = preg_split("'[/.-]'", $date);
740         if ($dmy[0] > 99) {
741             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
742         } else {
743             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
744               if ($dmy[2] < 1000) $dmy[2] += 1900;
745               if ($dmy[2] < 1910) $dmy[2] += 100;
746             }
747             // phone_country_code indicates format of ambiguous input dates.
748             if ($GLOBALS['phone_country_code'] == 1)
749               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
750             else
751               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
752         }
753     }
755     return $fixed_date;
758 function pdValueOrNull($key, $value) {
759   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
760     substr($key, 0, 8) == 'userdate') &&
761     (empty($value) || $value == '0000-00-00'))
762   {
763     return "NULL";
764   }
765   else {
766     return "'$value'";
767   }
770 // Create or update patient data from an array.
772 function updatePatientData($pid, $new, $create=false)
774   /*******************************************************************
775     $real = getPatientData($pid);
776     $new['DOB'] = fixDate($new['DOB']);
777     while(list($key, $value) = each ($new))
778         $real[$key] = $value;
779     $real['date'] = "'+NOW()+'";
780     $real['id'] = "";
781     $sql = "insert into patient_data set ";
782     while(list($key, $value) = each($real))
783         $sql .= $key." = '$value', ";
784     $sql = substr($sql, 0, -2);
785     return sqlInsert($sql);
786   *******************************************************************/
788   // The above was broken, though seems intent to insert a new patient_data
789   // row for each update.  A good idea, but nothing is doing that yet so
790   // the code below does not yet attempt it.
792   $new['DOB'] = fixDate($new['DOB']);
794   if ($create) {
795     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
796     foreach ($new as $key => $value) {
797       if ($key == 'id') continue;
798       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
799     }
800     $db_id = sqlInsert($sql);
801   }
802   else {
803     $db_id = $new['id'];
804     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
805     // Check for brain damage:
806     if ($pid != $rez['pid']) {
807       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
808         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
809       die($errmsg);
810     }
811     $sql = "UPDATE patient_data SET date = NOW()";
812     foreach ($new as $key => $value) {
813       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
814     }
815     $sql .= " WHERE id = '$db_id'";
816     sqlStatement($sql);
817   }
819   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
820   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
821     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
822     $rez['phone_cell'],$rez['email'],$rez['pid']);
824   return $db_id;
827 function newEmployerData(    $pid,
828                 $name = "",
829                 $street = "",
830                 $postal_code = "",
831                 $city = "",
832                 $state = "",
833                 $country = ""
834             )
836     return sqlInsert("insert into employer_data set
837         name='$name',
838         street='$street',
839         postal_code='$postal_code',
840         city='$city',
841         state='$state',
842         country='$country',
843         pid='$pid',
844         date=NOW()
845         ");
848 // Create or update employer data from an array.
850 function updateEmployerData($pid, $new, $create=false)
852   $colnames = array('name','street','city','state','postal_code','country');
854   if ($create) {
855     $set .= "pid = '$pid', date = NOW()";
856     foreach ($colnames as $key) {
857       $value = isset($new[$key]) ? $new[$key] : '';
858       $set .= ", `$key` = '$value'";
859     }
860     return sqlInsert("INSERT INTO employer_data SET $set");
861   }
862   else {
863     $set = '';
864     $old = getEmployerData($pid);
865     $modified = false;
866     foreach ($colnames as $key) {
867       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
868       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
869         $value = $new[$key];
870         $modified = true;
871       }
872       $set .= "`$key` = '$value', ";
873     }
874     if ($modified) {
875       $set .= "pid = '$pid', date = NOW()";
876       return sqlInsert("INSERT INTO employer_data SET $set");
877     }
878     return $old['id'];
879   }
882 // This updates or adds the given insurance data info, while retaining any
883 // previously added insurance_data rows that should be preserved.
884 // This does not directly support the maintenance of non-current insurance.
886 function newInsuranceData(
887   $pid,
888   $type = "",
889   $provider = "",
890   $policy_number = "",
891   $group_number = "",
892   $plan_name = "",
893   $subscriber_lname = "",
894   $subscriber_mname = "",
895   $subscriber_fname = "",
896   $subscriber_relationship = "",
897   $subscriber_ss = "",
898   $subscriber_DOB = "",
899   $subscriber_street = "",
900   $subscriber_postal_code = "",
901   $subscriber_city = "",
902   $subscriber_state = "",
903   $subscriber_country = "",
904   $subscriber_phone = "",
905   $subscriber_employer = "",
906   $subscriber_employer_street = "",
907   $subscriber_employer_city = "",
908   $subscriber_employer_postal_code = "",
909   $subscriber_employer_state = "",
910   $subscriber_employer_country = "",
911   $copay = "",
912   $subscriber_sex = "",
913   $effective_date = "0000-00-00",
914   $accept_assignment = "TRUE")
916   if (strlen($type) <= 0) return FALSE;
918   // If a bad date was passed, err on the side of caution.
919   $effective_date = fixDate($effective_date, date('Y-m-d'));
921   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
922     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
923   $idrow = sqlFetchArray($idres);
925   // Replace the most recent entry in any of the following cases:
926   // * Its effective date is >= this effective date.
927   // * It is the first entry and it has no (insurance) provider.
928   // * There is no encounter that is earlier than the new effective date but
929   //   on or after the old effective date.
930   // Otherwise insert a new entry.
932   $replace = false;
933   if ($idrow) {
934     if (strcmp($idrow['date'], $effective_date) > 0) {
935       $replace = true;
936     }
937     else {
938       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
939         $replace = true;
940       }
941       else {
942         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
943           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
944           "date >= '" . $idrow['date'] . " 00:00:00'");
945         if ($ferow['count'] == 0) $replace = true;
946       }
947     }
948   }
950   if ($replace) {
952     // TBD: This is a bit dangerous in that a typo in entering the effective
953     // date can wipe out previous insurance history.  So we want some data
954     // entry validation somewhere.
955     sqlStatement("DELETE FROM insurance_data WHERE " .
956       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
957       "id != " . $idrow['id']);
959     $data = array();
960     $data['type'] = $type;
961     $data['provider'] = $provider;
962     $data['policy_number'] = $policy_number;
963     $data['group_number'] = $group_number;
964     $data['plan_name'] = $plan_name;
965     $data['subscriber_lname'] = $subscriber_lname;
966     $data['subscriber_mname'] = $subscriber_mname;
967     $data['subscriber_fname'] = $subscriber_fname;
968     $data['subscriber_relationship'] = $subscriber_relationship;
969     $data['subscriber_ss'] = $subscriber_ss;
970     $data['subscriber_DOB'] = $subscriber_DOB;
971     $data['subscriber_street'] = $subscriber_street;
972     $data['subscriber_postal_code'] = $subscriber_postal_code;
973     $data['subscriber_city'] = $subscriber_city;
974     $data['subscriber_state'] = $subscriber_state;
975     $data['subscriber_country'] = $subscriber_country;
976     $data['subscriber_phone'] = $subscriber_phone;
977     $data['subscriber_employer'] = $subscriber_employer;
978     $data['subscriber_employer_city'] = $subscriber_employer_city;
979     $data['subscriber_employer_street'] = $subscriber_employer_street;
980     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
981     $data['subscriber_employer_state'] = $subscriber_employer_state;
982     $data['subscriber_employer_country'] = $subscriber_employer_country;
983     $data['copay'] = $copay;
984     $data['subscriber_sex'] = $subscriber_sex;
985     $data['pid'] = $pid;
986     $data['date'] = $effective_date;
987     $data['accept_assignment'] = $accept_assignment;
988     updateInsuranceData($idrow['id'], $data);
989     return $idrow['id'];
990   }
991   else {
992     return sqlInsert("INSERT INTO insurance_data SET
993       type = '$type',
994       provider = '$provider',
995       policy_number = '$policy_number',
996       group_number = '$group_number',
997       plan_name = '$plan_name',
998       subscriber_lname = '$subscriber_lname',
999       subscriber_mname = '$subscriber_mname',
1000       subscriber_fname = '$subscriber_fname',
1001       subscriber_relationship = '$subscriber_relationship',
1002       subscriber_ss = '$subscriber_ss',
1003       subscriber_DOB = '$subscriber_DOB',
1004       subscriber_street = '$subscriber_street',
1005       subscriber_postal_code = '$subscriber_postal_code',
1006       subscriber_city = '$subscriber_city',
1007       subscriber_state = '$subscriber_state',
1008       subscriber_country = '$subscriber_country',
1009       subscriber_phone = '$subscriber_phone',
1010       subscriber_employer = '$subscriber_employer',
1011       subscriber_employer_city = '$subscriber_employer_city',
1012       subscriber_employer_street = '$subscriber_employer_street',
1013       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1014       subscriber_employer_state = '$subscriber_employer_state',
1015       subscriber_employer_country = '$subscriber_employer_country',
1016       copay = '$copay',
1017       subscriber_sex = '$subscriber_sex',
1018       pid = '$pid',
1019       date = '$effective_date',
1020       accept_assignment = '$accept_assignment'
1021     ");
1022   }
1025 // This is used internally only.
1026 function updateInsuranceData($id, $new)
1028   $fields = sqlListFields("insurance_data");
1029   $use = array();
1031   while(list($key, $value) = each ($new)) {
1032     if (in_array($key, $fields)) {
1033       $use[$key] = $value;
1034     }
1035   }
1037   $sql = "UPDATE insurance_data SET ";
1038   while(list($key, $value) = each($use))
1039     $sql .= "`$key` = '$value', ";
1040   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1042   sqlStatement($sql);
1045 function newHistoryData($pid, $new=false) {
1046   $arraySqlBind = array();
1047   $sql = "insert into history_data set pid = ?, date = NOW()";
1048   array_push($arraySqlBind,$pid);
1049   if ($new) {
1050     while(list($key, $value) = each($new)) {
1051       array_push($arraySqlBind,$value);
1052       $sql .= ", `$key` = ?";
1053     }
1054   }
1055   return sqlInsert($sql, $arraySqlBind );
1058 function updateHistoryData($pid,$new)
1060         $real = getHistoryData($pid);
1061         while(list($key, $value) = each ($new))
1062                 $real[$key] = $value;
1063         $real['id'] = "";
1064         // need to unset date, so can reset it below
1065         unset($real['date']);
1067         $arraySqlBind = array();
1068         $sql = "insert into history_data set `date` = NOW(), ";
1069         while(list($key, $value) = each($real)) {
1070                 array_push($arraySqlBind,$value);
1071                 $sql .= "`$key` = ?, ";
1072         }
1073         $sql = substr($sql, 0, -2);
1075         return sqlInsert($sql, $arraySqlBind );
1078 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1079                 $phone_biz,$phone_cell,$email,$pid="")
1081     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1082     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1084     $db = $GLOBALS['adodb']['db'];
1085     $customer_info = array();
1087     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1088     $result = $db->Execute($sql);
1089     if ($result && !$result->EOF) {
1090         $customer_info['foreign_update'] = true;
1091         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1092         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1093     }
1095     ///xml rpc code to connect to accounting package and add user to it
1096     $customer_info['firstname'] = $fname;
1097     $customer_info['lastname'] = $lname;
1098     $customer_info['address'] = $street;
1099     $customer_info['suburb'] = $city;
1100     $customer_info['state'] = $state;
1101     $customer_info['postcode'] = $postal_code;
1103     //ezybiz wants state as a code rather than abbreviation
1104     $customer_info['geo_zone_id'] = "";
1105     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1106     $db = $GLOBALS['adodb']['db'];
1107     $result = $db->Execute($sql);
1108     if ($result && !$result->EOF) {
1109         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1110     }
1112     //ezybiz wants country as a code rather than abbreviation
1113     $customer_info['geo_country_id'] = "";
1114     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1115     $db = $GLOBALS['adodb']['db'];
1116     $result = $db->Execute($sql);
1117     if ($result && !$result->EOF) {
1118         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1119     }
1121     $customer_info['phone1'] = $phone_home;
1122     $customer_info['phone1comment'] = "Home Phone";
1123     $customer_info['phone2'] = $phone_biz;
1124     $customer_info['phone2comment'] = "Business Phone";
1125     $customer_info['phone3'] = $phone_cell;
1126     $customer_info['phone3comment'] = "Cell Phone";
1127     $customer_info['email'] = $email;
1128     $customer_info['customernumber'] = $pid;
1130     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1131     $ws = new WSWrapper($function);
1133     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1134     if (is_numeric($ws->value)) {
1135         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1136         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1137     }
1140 // Returns Age 
1141 //   in months if < 2 years old
1142 //   in years  if > 2 years old
1143 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1144 // (optional) nowYMD is a date in YYYYMMDD format
1145 function getPatientAge($dobYMD, $nowYMD=null)
1147     // strip any dashes from the DOB
1148     $dobYMD = preg_replace("/-/", "", $dobYMD);
1149     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1150     
1151     // set the 'now' date values
1152     if ($nowYMD == null) {
1153         $nowDay = date("d");
1154         $nowMonth = date("m");
1155         $nowYear = date("Y");
1156     }
1157     else {
1158         $nowDay = substr($nowYMD,6,2);
1159         $nowMonth = substr($nowYMD,4,2);
1160         $nowYear = substr($nowYMD,0,4);
1161     }
1163     $dayDiff = $nowDay - $dobDay;
1164     $monthDiff = $nowMonth - $dobMonth;
1165     $yearDiff = $nowYear - $dobYear;
1167     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1169     if ( $ageInMonths > 24 ) {
1170         $age = $yearDiff;
1171         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1172         else if ($monthDiff < 0) { $age -= 1; }
1173     }
1174     else  {
1175         $age = "$ageInMonths month"; 
1176     }
1178     return $age;
1182 // Returns Age in days
1183 //   in months if < 2 years old
1184 //   in years  if > 2 years old
1185 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1186 // (optional) nowYMD is a date in YYYYMMDD format
1187 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1188     $age = -1;
1190     // strip any dashes from the DOB
1191     $dobYMD = preg_replace("/-/", "", $dobYMD);
1192     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1193     
1194     // set the 'now' date values
1195     if ($nowYMD == null) {
1196         $nowDay = date("d");
1197         $nowMonth = date("m");
1198         $nowYear = date("Y");
1199     }
1200     else {
1201         $nowDay = substr($nowYMD,6,2);
1202         $nowMonth = substr($nowYMD,4,2);
1203         $nowYear = substr($nowYMD,0,4);
1204     }
1206     // do the date math
1207     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1208     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1209     $timediff = $nowtime - $dobtime;
1210     $age = $timediff / 86400;
1212     return $age;
1215 function dateToDB ($date)
1217     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1218     return $date;
1222 // ----------------------------------------------------------------------------
1224  * DROPDOWN FOR COUNTRIES
1225  * 
1226  * build a dropdown with all countries from geo_country_reference
1227  * 
1228  * @param int $selected - id for selected record
1229  * @param string $name - the name/id for select form
1230  * @return void - just echo the html encoded string
1231  */
1232 function dropdown_countries($selected = 0, $name = 'country_code') {
1233     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1235     $string = "<select name='$name' id='$name'>";
1236     while ( $row = sqlFetchArray($r) ) {
1237         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1238         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1239     }
1241     $string .= '</select>';
1242     echo $string;
1246 // ----------------------------------------------------------------------------
1248  * DROPDOWN FOR YES/NO
1249  * 
1250  * build a dropdown with two options (yes - 1, no - 0)
1251  * 
1252  * @param int $selected - id for selected record
1253  * @param string $name - the name/id for select form
1254  * @return void - just echo the html encoded string 
1255  */
1256 function dropdown_yesno($selected = 0, $name = 'yesno') {
1257     $string = "<select name='$name' id='$name'>";
1259     $selected = (int)$selected;
1260     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1261     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1263     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1264     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1265     $string .= '</select>';
1267     echo $string;
1270 // ----------------------------------------------------------------------------
1272  * DROPDOWN FOR MALE/FEMALE options
1273  * 
1274  * build a dropdown with three options (unselected/male/female)
1275  * 
1276  * @param int $selected - id for selected record
1277  * @param string $name - the name/id for select form
1278  * @return void - just echo the html encoded string
1279  */
1280 function dropdown_sex($selected = 0, $name = 'sex') {
1281     $string = "<select name='$name' id='$name'>";
1283     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1284     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1285     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1287     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1288     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1289     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1290     $string .= '</select>';
1292     echo $string;
1295 // ----------------------------------------------------------------------------
1297  * DROPDOWN FOR MARITAL STATUS
1298  * 
1299  * build a dropdown with marital status
1300  * 
1301  * @param int $selected - id for selected record
1302  * @param string $name - the name/id for select form
1303  * @return void - just echo the html encoded string
1304  */
1305 function dropdown_marital($selected = 0, $name = 'status') {
1306     $string = "<select name='$name' id='$name'>";
1308     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1310     foreach ( $statii as $st ) {
1311         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1312         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1313     }
1315     $string .= '</select>';
1317     echo $string;
1320 // ----------------------------------------------------------------------------
1322  * DROPDOWN FOR PROVIDERS
1323  * 
1324  * build a dropdown with all providers
1325  * 
1326  * @param int $selected - id for selected record
1327  * @param string $name - the name/id for select form
1328  * @return void - just echo the html encoded string
1329  */
1330 function dropdown_providers($selected = 0, $name = 'status') {
1331     $provideri = getProviderInfo();
1333     $string = "<select name='$name' id='$name'>";
1334     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1335     foreach ( $provideri as $s ) {
1336         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1337         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1338     }
1340     $string .= '</select>';
1342     echo $string;
1345 // ----------------------------------------------------------------------------
1347  * DROPDOWN FOR INSURANCE COMPANIES
1348  * 
1349  * build a dropdown with all insurers
1350  * 
1351  * @param int $selected - id for selected record
1352  * @param string $name - the name/id for select form
1353  * @return void - just echo the html encoded string
1354  */
1355 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1356     $insurancei = getInsuranceProviders();
1358     $string = "<select name='$name' id='$name'>";
1359     $string .= '<option value="0">Onbekend</option>';
1360     foreach ( $insurancei as $iid => $iname ) {
1361         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1362         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1363     }
1365     $string .= '</select>';
1367     echo $string;
1371 // ----------------------------------------------------------------------------
1373  * COUNTRY CODE
1374  * 
1375  * return the name or the country code, function of arguments
1376  * 
1377  * @param int $country_code
1378  * @param string $country_name
1379  * @return string | int - name or code
1380  */
1381 function country_code($country_code = 0, $country_name = '') {
1382     $strint = '';
1383     if ( $country_code ) {
1384         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1385     } else {
1386         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1387     }
1389     $db = $GLOBALS['adodb']['db'];
1390     $result = $db->Execute($sql);
1391     if ($result && !$result->EOF) {
1392         $strint = $result->fields['res'];
1393     }
1395     return $strint;
1398 function DBToDate ($date)
1400     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1401     return $date;
1404 function get_patient_balance($pid) {
1405   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1406     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1407       "pid = ? AND activity = 1", array($pid) );
1408     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1409       "pid = ?", array($pid) );
1410     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1411       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1412       "pid = ?", array($pid) );
1413     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1414       - $drow['payments'] - $drow['adjustments']);
1415   }
1416   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1417     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1418     $conn = $GLOBALS['adodb']['db'];
1419     $customer_info['id'] = 0;
1420     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1421       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1422       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1423       "im.foreign_table = 'customer'";
1424     $result = $conn->Execute($sql);
1425     if($result && !$result->EOF) {
1426       $customer_info['id'] = $result->fields['foreign_id'];
1427     }
1428     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1429     $ws = new WSWrapper($function);
1430     if(is_numeric($ws->value)) {
1431       return sprintf('%01.2f', $ws->value);
1432     }
1433   }
1434   return '';