internationalization bug fixes
[openemr.git] / library / patient.inc
blob7ff57778d6f36900343c76341c32fdb434796f05
1 <?php
2 include_once("{$GLOBALS['srcdir']}/sql.inc");
3 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
5 // These are for sports team use:
6 $PLAYER_FITNESSES = array(
7   xl('Full Play'),
8   xl('Full Training'),
9   xl('Restricted Training'),
10   xl('Injured Out'),
11   xl('Rehabilitation'),
12   xl('Illness'),
13   xl('International Duty')
15 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
17 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
18     $sql = "select $given from patient_data where pid='$pid' order by date DESC limit 0,1";
19     return sqlQuery($sql);
22 function getLanguages() {
23     $returnval = array('','english');
24     $sql = "select distinct lower(language) as language from patient_data";
25     $rez = sqlStatement($sql);
26     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
27         if (($row["language"] != "english") && ($row["language"] != "")) {
28             array_push($returnval, $row["language"]);
29         }
30     }
31     return $returnval;
34 function getInsuranceProviders() {
35     $returnval = array();
37     if (true) {
38         $sql = "select name, id from insurance_companies order by name, id";
39         $rez = sqlStatement($sql);
40         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
41             $returnval[$row['id']] = $row['name'];
42         }
43     }
45     // Please leave this here. I have a user who wants to see zip codes and PO
46     // box numbers listed along with the insurance company names, as many companies
47     // have different billing addresses for different plans.  -- Rod Roark
48     //
49     else {
50         $sql = "select insurance_companies.name, insurance_companies.id, " .
51           "addresses.zip, addresses.line1 " .
52           "from insurance_companies, addresses " .
53           "where addresses.foreign_id = insurance_companies.id " .
54           "order by insurance_companies.name, addresses.zip";
56         $rez = sqlStatement($sql);
58         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
59             preg_match("/\d+/", $row['line1'], $matches);
60             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
61               "," . $matches[0] . ")";
62         }
63     }
65     return $returnval;
68 function getProviders() {
69     $returnval = array("");
70     $sql = "select fname, lname from users where authorized = 1 and " .
71         "active = 1 and username != ''";
72     $rez = sqlStatement($sql);
73     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
74         if (($row["fname"] != "") && ($row["lname"] != "")) {
75             array_push($returnval, $row["fname"] . " " . $row["lname"]);
76         }
77     }
78     return $returnval;
81 // ----------------------------------------------------------------------------
82 // Get one facility row.  If the ID is not specified, then get either the
83 // "main" (billing) facility, or the default facility of the currently
84 // logged-in user.  This was created to support genFacilityTitle() but
85 // may find additional uses.
87 function getFacility($facid=0) {
88   if ($facid > 0) {
89     $query = "SELECT * FROM facility WHERE id = '$facid'";
90   }
91   else if ($facid == 0) {
92     $query = "SELECT * FROM facility ORDER BY " .
93       "billing_location DESC, service_location, id LIMIT 1";
94   }
95   else {
96     $query = "SELECT facility.* FROM users, facility WHERE " .
97       "users.id = '" . $_SESSION['authUserID'] . "' AND " .
98       "facility.id = users.facility_id";
99   }
100   return sqlQuery($query);
103 // Generate a report title including report name and facility name, address
104 // and phone.
106 function genFacilityTitle($repname='', $facid=0) {
107   $s = '';
108   $s .= "<table class='ftitletable'>\n";
109   $s .= " <tr>\n";
110   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
111   $s .= "  <td class='ftitlecell2'>\n";
112   $r = getFacility($facid);
113   if (!empty($r)) {
114     $s .= "<b>" . $r['name'] . "</b>\n";
115     if ($r['street']) $s .= "<br />" . $r['street'] . "\n";
116     if ($r['city'] || $r['state'] || $r['postal_code']) {
117       $s .= "<br />";
118       if ($r['city']) $s .= $r['city'];
119       if ($r['state']) {
120         if ($r['city']) $s .= ", \n";
121         $s .= $r['state'];
122       }
123       if ($r['postal_code']) $s .= " " . $r['postal_code'];
124       $s .= "\n";
125     }
126     if ($r['country_code']) $s .= "<br />" . $r['country_code'] . "\n";
127     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . $r['phone'] . "\n";
128   }
129   $s .= "  </td>\n";
130   $s .= " </tr>\n";
131   $s .= "</table>\n";
132   return $s;
136 GET FACILITIES
138 returns all facilities or just the id for the first one
139 (FACILITY FILTERING (lemonsoftware))
141 @param string - if 'first' return first facility ordered by id
142 @return array | int for 'first' case
144 function getFacilities($first = '') {
145     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
146     $ret = array();
147     while ( $row = sqlFetchArray($r) ) {
148        $ret[] = $row;
151         if ( $first == 'first') {
152             return $ret[0]['id'];
153         } else {
154             return $ret;
155         }
159 GET SERVICE FACILITIES
161 returns all service_location facilities or just the id for the first one
162 (FACILITY FILTERING (CHEMED))
164 @param string - if 'first' return first facility ordered by id
165 @return array | int for 'first' case
167 function getServiceFacilities($first = '') {
168     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
169     $ret = array();
170     while ( $row = sqlFetchArray($r) ) {
171        $ret[] = $row;
174         if ( $first == 'first') {
175             return $ret[0]['id'];
176         } else {
177             return $ret;
178         }
181 //(CHEMED) facility filter
182 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
183     $param1 = "";
184     if ($providers_only) {
185       // $param1 = " AND authorized=1 AND ( info IS NULL OR info NOT LIKE '%Nocalendar%' ) ";
186       $param1 = " AND authorized = 1 AND calendar = 1 ";
187     }
189     //--------------------------------
190     //(CHEMED) facility filter
191     $param2 = "";
192     if ($facility) {
193       if ($GLOBALS['restrict_user_facility']) {
194         $param2 = " AND (facility_id = $facility 
195           OR  $facility IN
196                 (select facility_id 
197                 from users_facility
198                 where tablename = 'users'
199                 and table_id = id)
200                 )
201           ";
202       }
203       else {
204         $param2 = " AND facility_id = $facility ";
205       }
206     }
207     //--------------------------------
209     $command = "=";
210     if ($providerID == "%") {
211         $command = "like";
212     }
213     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
214         "from users where username != '' and active = 1 and id $command '" .
215         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
216     // sort by last name -- JRM June 2008
217     $query .= " ORDER BY lname, fname ";
218     $rez = sqlStatement($query);
219     for($iter=0; $row=sqlFetchArray($rez); $iter++)
220         $returnval[$iter]=$row;
222     //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
223     //accessible from $resultval['key']
225     if($iter==1) {
226         $akeys = array_keys($returnval[0]);
227         foreach($akeys as $key) {
228             $returnval[0][$key] = $returnval[0][$key];
229         }
230     }
231     return $returnval;
234 //same as above but does not reduce if only 1 row returned
235 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
236     $param1 = "";
237     if ($providers_only) {
238         $param1 = "AND authorized=1";
239     }
240     $command = "=";
241     if ($providerID == "%") {
242         $command = "like";
243     }
244     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
245         "from users where active = 1 and username != '' and id $command '" .
246         mysql_real_escape_string($providerID) . "' " . $param1;
248     $rez = sqlStatement($query);
249     for($iter=0; $row=sqlFetchArray($rez); $iter++)
250         $returnval[$iter]=$row;
252     return $returnval;
255 function getProviderName($providerID) {
256     $pi = getProviderInfo($providerID);
257     if (strlen($pi[0]["lname"]) > 0) {
258         return $pi[0]['fname'] . " " . $pi[0]['lname'];
259     }
260     return "";
263 function getProviderId($providerName) {
264     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
265     $rez = sqlStatement($query);
266     for($iter=0; $row=sqlFetchArray($rez); $iter++)
267         $returnval[$iter]=$row;
268     return $returnval;
271 function getEthnoRacials() {
272     $returnval = array("");
273     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
274     $rez = sqlStatement($sql);
275     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
276         if (($row["ethnoracial"] != "")) {
277             array_push($returnval, $row["ethnoracial"]);
278         }
279     }
280     return $returnval;
283 function getHistoryData($pid, $given = "*")
285     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
286     return sqlQuery($sql);
289 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
290 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
292   $sql = "select $given from insurance_data as insd " .
293     "left join insurance_companies as ic on ic.id = insd.provider " .
294     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
295   return sqlQuery($sql);
298 function getInsuranceDataByDate($pid, $date, $type,
299   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
300 { // this must take the date in the following manner: YYYY-MM-DD
301   // this function recalls the insurance value that was most recently enterred from the
302   // given date. it will call up most recent records up to and on the date given,
303   // but not records enterred after the given date
304   $sql = "select $given from insurance_data as insd " .
305     "left join insurance_companies as ic on ic.id = provider " .
306     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
307     "type='$type' order by date DESC limit 1";
308   return sqlQuery($sql);
311 function getEmployerData($pid, $given = "*")
313     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
314     return sqlQuery($sql);
317 function _set_patient_inc_count($limit, $count, $where) {
318   // When the limit is exceeded, find out what the unlimited count would be.
319   $GLOBALS['PATIENT_INC_COUNT'] = $count;
320   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
321   if ($limit != "all") {
322     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
323     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
324   }
327 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")
329     // Allow the last name to be followed by a comma and some part of a first name.
330     // New behavior for searches:
331     // Allows comma alone followed by some part of a first name
332     // If the first letter of either name is capital, searches for name starting
333     // with given substring (the expected behavior).  If it is lower case, it
334     // it searches for the substring anywhere in the name.  This applies to either
335     // last name or first name or both.  The arbitrary limit of 100 results is set
336     // in the sql query below. --Mark Leeds
337     $lname = trim($lname);
338     $fname = '';
339      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
340          $lname = trim($matches[1]);
341          $fname = trim($matches[2]);
342     }
343     $search_for_pieces1 = '';
344     $search_for_pieces2 = '';
345     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
346     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
348     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
349         "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
350         if (!empty($GLOBALS['pt_restrict_field'])) {
351                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
352                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
353                 }
354         }
356     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
357     if ($limit != "all") $sql .= " LIMIT $start, $limit";
359     $rez = sqlStatement($sql);
361     for($iter=0; $row=sqlFetchArray($rez); $iter++)
362         $returnval[$iter] = $row;
364     _set_patient_inc_count($limit, count($returnval), $where);
365     return $returnval;
368 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")
370     
371     $where = "pubpid LIKE '$pid%' ";
372         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
373                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
374                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
375                 }
376         }
378     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
379     if ($limit != "all") $sql .= " limit $start, $limit";
380     $rez = sqlStatement($sql);
381     for($iter=0; $row=sqlFetchArray($rez); $iter++)
382         $returnval[$iter]=$row;
384     _set_patient_inc_count($limit, count($returnval), $where);
385     return $returnval;
388 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")
390   $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
392   $where = "";
393   for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
394     if ( $iter > 0 ) {
395       $where .= " or ";
396     }
397     $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
398   }
400   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
401   if ($limit != "all") $sql .= " limit $start, $limit";
402   $rez = sqlStatement($sql);
403   for($iter=0; $row=sqlFetchArray($rez); $iter++)
404     $returnval[$iter]=$row;
405   _set_patient_inc_count($limit, count($returnval), $where);
406   return $returnval;
409 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" )
411         $layoutCols = split( '~', $searchFields );
412   $where = "";
413   $i = 0;
414   foreach ($layoutCols as $val ) {
415                 if ( $i > 0 ) {
416                    $where .= " or ";
417                 }
418     if ($val == 'pid') {
419                 $where .= " $val = '$searchTerm' ";
420     }
421     else {
422                 $where .= " $val like '$searchTerm%' ";
423     }
424                 $i++;
425         }
426   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
427   if ($limit != "all") $sql .= " limit $start, $limit";
428   $rez = sqlStatement($sql);
429   for($iter=0; $row=sqlFetchArray($rez); $iter++)
430       $returnval[$iter]=$row;
431   _set_patient_inc_count($limit, count($returnval), $where);
432   return $returnval;
435 // return a collection of Patient PIDs
436 // new arg style by JRM March 2008
437 // 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")
438 function getPatientPID($args)
440     $pid = "%";
441     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
442     $orderby = "lname ASC, fname ASC";
443     $limit="all";
444     $start="0";
446     // alter default values if defined in the passed in args
447     if (isset($args['pid'])) { $pid = $args['pid']; }
448     if (isset($args['given'])) { $given = $args['given']; }
449     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
450     if (isset($args['limit'])) { $limit = $args['limit']; }
451     if (isset($args['start'])) { $start = $args['start']; }
453     $command = "=";
454     if ($pid == -1) $pid = "%";
455     elseif (empty($pid)) $pid = "NULL";
457     if (strstr($pid,"%")) $command = "like";
459     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
460     if ($limit != "all") $sql .= " limit $start, $limit";
462     $rez = sqlStatement($sql);
463     for($iter=0; $row=sqlFetchArray($rez); $iter++)
464         $returnval[$iter]=$row;
466     return $returnval;
469 /* return a patient's name in the format LAST, FIRST */
470 function getPatientName($pid) {
471     if (empty($pid)) return "";
472     $patientData = getPatientPID(array("pid"=>$pid));
473     if (empty($patientData[0]['lname'])) return "";
474     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
475     return $patientName;
478 /* find patient data by DOB */
479 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
481     $DOB = fixDate($DOB, $DOB);
482     $where = "DOB like '$DOB%' ";
483         if (!empty($GLOBALS['pt_restrict_field'])) {
484                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
485                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
486                 }
487         }
489     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
491     if ($limit != "all") $sql .= " LIMIT $start, $limit";
493     $rez = sqlStatement($sql);
494     for($iter=0; $row=sqlFetchArray($rez); $iter++)
495         $returnval[$iter]=$row;
497     _set_patient_inc_count($limit, count($returnval), $where);
498     return $returnval;
501 /* find patient data by SSN */
502 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
504     $where = "ss LIKE '$ss%'";
505     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
506     if ($limit != "all") $sql .= " LIMIT $start, $limit";
508     $rez = sqlStatement($sql);
509     for($iter=0; $row=sqlFetchArray($rez); $iter++)
510         $returnval[$iter]=$row;
512     _set_patient_inc_count($limit, count($returnval), $where);
513     return $returnval;
516 //(CHEMED) Search by phone number
517 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
519     $phone = ereg_replace( "[[:punct:]]","", $phone );
520     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
521     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
522     if ($limit != "all") $sql .= " LIMIT $start, $limit";
524     $rez = sqlStatement($sql);
525     for($iter=0; $row=sqlFetchArray($rez); $iter++)
526         $returnval[$iter]=$row;
528     _set_patient_inc_count($limit, count($returnval), $where);
529     return $returnval;
532 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
534     $sql="select $given from patient_data order by $orderby";
536     if ($limit != "all")
537         $sql .= " limit $start, $limit";
539     $rez = sqlStatement($sql);
540     for($iter=0; $row=sqlFetchArray($rez); $iter++)
541         $returnval[$iter]=$row;
543     return $returnval;
546 //----------------------input functions
547 function newPatientData(    $db_id="",
548                 $title = "",
549                 $fname = "",
550                 $lname = "",
551                 $mname = "",
552                 $sex = "",
553                 $DOB = "",
554                 $street = "",
555                 $postal_code = "",
556                 $city = "",
557                 $state = "",
558                 $country_code = "",
559                 $ss = "",
560                 $occupation = "",
561                 $phone_home = "",
562                 $phone_biz = "",
563                 $phone_contact = "",
564                 $status = "",
565                 $contact_relationship = "",
566                 $referrer = "",
567                 $referrerID = "",
568                 $email = "",
569                 $language = "",
570                 $ethnoracial = "",
571                 $interpretter = "",
572                 $migrantseasonal = "",
573                 $family_size = "",
574                 $monthly_income = "",
575                 $homeless = "",
576                 $financial_review = "",
577                 $pubpid = "",
578                 $pid = "MAX(pid)+1",
579                 $providerID = "",
580                 $genericname1 = "",
581                 $genericval1 = "",
582                 $genericname2 = "",
583                 $genericval2 = "",
584                 $phone_cell = "",
585                 $hipaa_mail = "",
586                 $hipaa_voice = "",
587                 $squad = 0,
588                 $pharmacy_id = 0,
589                 $drivers_license = "",
590                 $hipaa_notice = "",
591                 $hipaa_message = "",
592                 $regdate = ""
593             )
595     $DOB = fixDate($DOB);
596     $regdate = fixDate($regdate);
598     $fitness = 0;
599     $referral_source = '';
600     if ($pid) {
601         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
602         // Check for brain damage:
603         if ($db_id != $rez['id']) {
604             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
605               $rez['id'] . "' to '$db_id' for pid '$pid'";
606             die($errmsg);
607         }
608         $fitness = $rez['fitness'];
609         $referral_source = $rez['referral_source'];
610     }
612     // Get the default price level.
613     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
614       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
615     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
617     $query = ("replace into patient_data set
618         id='$db_id',
619         title='$title',
620         fname='$fname',
621         lname='$lname',
622         mname='$mname',
623         sex='$sex',
624         DOB='$DOB',
625         street='$street',
626         postal_code='$postal_code',
627         city='$city',
628         state='$state',
629         country_code='$country_code',
630         drivers_license='$drivers_license',
631         ss='$ss',
632         occupation='$occupation',
633         phone_home='$phone_home',
634         phone_biz='$phone_biz',
635         phone_contact='$phone_contact',
636         status='$status',
637         contact_relationship='$contact_relationship',
638         referrer='$referrer',
639         referrerID='$referrerID',
640         email='$email',
641         language='$language',
642         ethnoracial='$ethnoracial',
643         interpretter='$interpretter',
644         migrantseasonal='$migrantseasonal',
645         family_size='$family_size',
646         monthly_income='$monthly_income',
647         homeless='$homeless',
648         financial_review='$financial_review',
649         pubpid='$pubpid',
650         pid = $pid,
651         providerID = '$providerID',
652         genericname1 = '$genericname1',
653         genericval1 = '$genericval1',
654         genericname2 = '$genericname2',
655         genericval2 = '$genericval2',
656         phone_cell = '$phone_cell',
657         pharmacy_id = '$pharmacy_id',
658         hipaa_mail = '$hipaa_mail',
659         hipaa_voice = '$hipaa_voice',
660         hipaa_notice = '$hipaa_notice',
661         hipaa_message = '$hipaa_message',
662         squad = '$squad',
663         fitness='$fitness',
664         referral_source='$referral_source',
665         regdate='$regdate',
666         pricelevel='$pricelevel',
667         date=NOW()");
669     $id = sqlInsert($query);
671     if ( !$db_id ) {
672       // find the last inserted id for new patient case
673       $db_id = mysql_insert_id();
674     }
676     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
678     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
679                 $phone_biz,$phone_cell,$email,$pid);
681     return $foo['pid'];
684 // Supported input date formats are:
685 //   mm/dd/yyyy
686 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
687 //   yyyy/mm/dd
688 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
690 function fixDate($date, $default="0000-00-00") {
691     $fixed_date = $default;
692     $date = trim($date);
693     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
694         $dmy = preg_split("'[/.-]'", $date);
695         if ($dmy[0] > 99) {
696             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
697         } else {
698             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
699               if ($dmy[2] < 1000) $dmy[2] += 1900;
700               if ($dmy[2] < 1910) $dmy[2] += 100;
701             }
702             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
703         }
704     }
706     return $fixed_date;
709 // Create or update patient data from an array.
711 function updatePatientData($pid, $new, $create=false)
713   /*******************************************************************
714     $real = getPatientData($pid);
715     $new['DOB'] = fixDate($new['DOB']);
716     while(list($key, $value) = each ($new))
717         $real[$key] = $value;
718     $real['date'] = "'+NOW()+'";
719     $real['id'] = "";
720     $sql = "insert into patient_data set ";
721     while(list($key, $value) = each($real))
722         $sql .= $key." = '$value', ";
723     $sql = substr($sql, 0, -2);
724     return sqlInsert($sql);
725   *******************************************************************/
727   // The above was broken, though seems intent to insert a new patient_data
728   // row for each update.  A good idea, but nothing is doing that yet so
729   // the code below does not yet attempt it.
731   $new['DOB'] = fixDate($new['DOB']);
733   if ($create) {
734     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
735     foreach ($new as $key => $value) {
736       if ($key == 'id') continue;
737       $sql .= ", `$key` = '$value'";
738     }
739     $db_id = sqlInsert($sql);
740   }
741   else {
742     $db_id = $new['id'];
743     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
744     // Check for brain damage:
745     if ($pid != $rez['pid']) {
746       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
747         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
748       die($errmsg);
749     }
750     $sql = "UPDATE patient_data SET date = NOW()";
751     foreach ($new as $key => $value) {
752       $sql .= ", `$key` = '$value'";
753     }
754     $sql .= " WHERE id = '$db_id'";
755     sqlStatement($sql);
756   }
758   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
759   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
760     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
761     $rez['phone_cell'],$rez['email'],$rez['pid']);
763   return $db_id;
766 function newEmployerData(    $pid,
767                 $name = "",
768                 $street = "",
769                 $postal_code = "",
770                 $city = "",
771                 $state = "",
772                 $country = ""
773             )
775     return sqlInsert("insert into employer_data set
776         name='$name',
777         street='$street',
778         postal_code='$postal_code',
779         city='$city',
780         state='$state',
781         country='$country',
782         pid='$pid',
783         date=NOW()
784         ");
787 // Create or update employer data from an array.
789 function updateEmployerData($pid, $new, $create=false)
791   $colnames = array('name','street','city','state','postal_code','country');
793   if ($create) {
794     $set .= "pid = '$pid', date = NOW()";
795     foreach ($colnames as $key) {
796       $value = isset($new[$key]) ? $new[$key] : '';
797       $set .= ", `$key` = '$value'";
798     }
799     return sqlInsert("INSERT INTO employer_data SET $set");
800   }
801   else {
802     $set = '';
803     $old = getEmployerData($pid);
804     $modified = false;
805     foreach ($colnames as $key) {
806       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
807       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
808         $value = $new[$key];
809         $modified = true;
810       }
811       $set .= "`$key` = '$value', ";
812     }
813     if ($modified) {
814       $set .= "pid = '$pid', date = NOW()";
815       return sqlInsert("INSERT INTO employer_data SET $set");
816     }
817     return $old['id'];
818   }
821 // This updates or adds the given insurance data info, while retaining any
822 // previously added insurance_data rows that should be preserved.
823 // This does not directly support the maintenance of non-current insurance.
825 function newInsuranceData(
826   $pid,
827   $type = "",
828   $provider = "",
829   $policy_number = "",
830   $group_number = "",
831   $plan_name = "",
832   $subscriber_lname = "",
833   $subscriber_mname = "",
834   $subscriber_fname = "",
835   $subscriber_relationship = "",
836   $subscriber_ss = "",
837   $subscriber_DOB = "",
838   $subscriber_street = "",
839   $subscriber_postal_code = "",
840   $subscriber_city = "",
841   $subscriber_state = "",
842   $subscriber_country = "",
843   $subscriber_phone = "",
844   $subscriber_employer = "",
845   $subscriber_employer_street = "",
846   $subscriber_employer_city = "",
847   $subscriber_employer_postal_code = "",
848   $subscriber_employer_state = "",
849   $subscriber_employer_country = "",
850   $copay = "",
851   $subscriber_sex = "",
852   $effective_date = "0000-00-00",
853   $accept_assignment = "TRUE")
855   if (strlen($type) <= 0) return FALSE;
857   // If a bad date was passed, err on the side of caution.
858   $effective_date = fixDate($effective_date, date('Y-m-d'));
860   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
861     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
862   $idrow = sqlFetchArray($idres);
864   // Replace the most recent entry in any of the following cases:
865   // * Its effective date is >= this effective date.
866   // * It is the first entry and it has no (insurance) provider.
867   // * There is no encounter that is earlier than the new effective date but
868   //   on or after the old effective date.
869   // Otherwise insert a new entry.
871   $replace = false;
872   if ($idrow) {
873     if (strcmp($idrow['date'], $effective_date) > 0) {
874       $replace = true;
875     }
876     else {
877       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
878         $replace = true;
879       }
880       else {
881         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
882           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
883           "date >= '" . $idrow['date'] . " 00:00:00'");
884         if ($ferow['count'] == 0) $replace = true;
885       }
886     }
887   }
889   if ($replace) {
891     // TBD: This is a bit dangerous in that a typo in entering the effective
892     // date can wipe out previous insurance history.  So we want some data
893     // entry validation somewhere.
894     sqlStatement("DELETE FROM insurance_data WHERE " .
895       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
896       "id != " . $idrow['id']);
898     $data = array();
899     $data['type'] = $type;
900     $data['provider'] = $provider;
901     $data['policy_number'] = $policy_number;
902     $data['group_number'] = $group_number;
903     $data['plan_name'] = $plan_name;
904     $data['subscriber_lname'] = $subscriber_lname;
905     $data['subscriber_mname'] = $subscriber_mname;
906     $data['subscriber_fname'] = $subscriber_fname;
907     $data['subscriber_relationship'] = $subscriber_relationship;
908     $data['subscriber_ss'] = $subscriber_ss;
909     $data['subscriber_DOB'] = $subscriber_DOB;
910     $data['subscriber_street'] = $subscriber_street;
911     $data['subscriber_postal_code'] = $subscriber_postal_code;
912     $data['subscriber_city'] = $subscriber_city;
913     $data['subscriber_state'] = $subscriber_state;
914     $data['subscriber_country'] = $subscriber_country;
915     $data['subscriber_phone'] = $subscriber_phone;
916     $data['subscriber_employer'] = $subscriber_employer;
917     $data['subscriber_employer_city'] = $subscriber_employer_city;
918     $data['subscriber_employer_street'] = $subscriber_employer_street;
919     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
920     $data['subscriber_employer_state'] = $subscriber_employer_state;
921     $data['subscriber_employer_country'] = $subscriber_employer_country;
922     $data['copay'] = $copay;
923     $data['subscriber_sex'] = $subscriber_sex;
924     $data['pid'] = $pid;
925     $data['date'] = $effective_date;
926     $data['accept_assignment'] = $accept_assignment;
927     updateInsuranceData($idrow['id'], $data);
928     return $idrow['id'];
929   }
930   else {
931     return sqlInsert("INSERT INTO insurance_data SET
932       type = '$type',
933       provider = '$provider',
934       policy_number = '$policy_number',
935       group_number = '$group_number',
936       plan_name = '$plan_name',
937       subscriber_lname = '$subscriber_lname',
938       subscriber_mname = '$subscriber_mname',
939       subscriber_fname = '$subscriber_fname',
940       subscriber_relationship = '$subscriber_relationship',
941       subscriber_ss = '$subscriber_ss',
942       subscriber_DOB = '$subscriber_DOB',
943       subscriber_street = '$subscriber_street',
944       subscriber_postal_code = '$subscriber_postal_code',
945       subscriber_city = '$subscriber_city',
946       subscriber_state = '$subscriber_state',
947       subscriber_country = '$subscriber_country',
948       subscriber_phone = '$subscriber_phone',
949       subscriber_employer = '$subscriber_employer',
950       subscriber_employer_city = '$subscriber_employer_city',
951       subscriber_employer_street = '$subscriber_employer_street',
952       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
953       subscriber_employer_state = '$subscriber_employer_state',
954       subscriber_employer_country = '$subscriber_employer_country',
955       copay = '$copay',
956       subscriber_sex = '$subscriber_sex',
957       pid = '$pid',
958       date = '$effective_date',
959       accept_assignment = '$accept_assignment'
960     ");
961   }
964 // This is used internally only.
965 function updateInsuranceData($id, $new)
967   $fields = sqlListFields("insurance_data");
968   $use = array();
970   while(list($key, $value) = each ($new)) {
971     if (in_array($key, $fields)) {
972       $use[$key] = $value;
973     }
974   }
976   $sql = "UPDATE insurance_data SET ";
977   while(list($key, $value) = each($use))
978     $sql .= "`$key` = '$value', ";
979   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
981   sqlStatement($sql);
984 function newHistoryData($pid, $new=false) {
985   $sql = "insert into history_data set pid = '$pid', date = NOW()";
986   if ($new) {
987     while(list($key, $value) = each($new)) {
988       if (!get_magic_quotes_gpc()) $value = addslashes($value);
989       $sql .= ", `$key` = '$value'";
990     }
991   }
992   return sqlInsert($sql);
995 function updateHistoryData($pid,$new)
997         $real = getHistoryData($pid);
998         while(list($key, $value) = each ($new))
999                 $real[$key] = $value;
1000         $real['date'] = "'+NOW()+'";
1001         $real['id'] = "";
1003         $sql = "insert into history_data set ";
1004         while(list($key, $value) = each($real))
1005                 $sql .= "`$key` = '$value', ";
1006         $sql = substr($sql, 0, -2);
1008         return sqlInsert($sql);
1011 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1012                 $phone_biz,$phone_cell,$email,$pid="")
1014     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1015     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1017     $db = $GLOBALS['adodb']['db'];
1018     $customer_info = array();
1020     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1021     $result = $db->Execute($sql);
1022     if ($result && !$result->EOF) {
1023         $customer_info['foreign_update'] = true;
1024         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1025         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1026     }
1028     ///xml rpc code to connect to accounting package and add user to it
1029     $customer_info['firstname'] = $fname;
1030     $customer_info['lastname'] = $lname;
1031     $customer_info['address'] = $street;
1032     $customer_info['suburb'] = $city;
1033     $customer_info['state'] = $state;
1034     $customer_info['postcode'] = $postal_code;
1036     //ezybiz wants state as a code rather than abbreviation
1037     $customer_info['geo_zone_id'] = "";
1038     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1039     $db = $GLOBALS['adodb']['db'];
1040     $result = $db->Execute($sql);
1041     if ($result && !$result->EOF) {
1042         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1043     }
1045     //ezybiz wants country as a code rather than abbreviation
1046     $customer_info['geo_country_id'] = "";
1047     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1048     $db = $GLOBALS['adodb']['db'];
1049     $result = $db->Execute($sql);
1050     if ($result && !$result->EOF) {
1051         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1052     }
1054     $customer_info['phone1'] = $phone_home;
1055     $customer_info['phone1comment'] = "Home Phone";
1056     $customer_info['phone2'] = $phone_biz;
1057     $customer_info['phone2comment'] = "Business Phone";
1058     $customer_info['phone3'] = $phone_cell;
1059     $customer_info['phone3comment'] = "Cell Phone";
1060     $customer_info['email'] = $email;
1061     $customer_info['customernumber'] = $pid;
1063     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1064     $ws = new WSWrapper($function);
1066     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1067     if (is_numeric($ws->value)) {
1068         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1069         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1070     }
1073 // Returns Age 
1074 //   in months if < 2 years old
1075 //   in years  if > 2 years old
1076 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1077 // (optional) nowYMD is a date in YYYYMMDD format
1078 function getPatientAge($dobYMD, $nowYMD=null)
1080     // strip any dashes from the DOB
1081     $dobYMD = preg_replace("/-/", "", $dobYMD);
1082     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1083     
1084     // set the 'now' date values
1085     if ($nowYMD == null) {
1086         $nowDay = date("d");
1087         $nowMonth = date("m");
1088         $nowYear = date("Y");
1089     }
1090     else {
1091         $nowDay = substr($nowYMD,6,2);
1092         $nowMonth = substr($nowYMD,4,2);
1093         $nowYear = substr($nowYMD,0,4);
1094     }
1096     $dayDiff = $nowDay - $dobDay;
1097     $monthDiff = $nowMonth - $dobMonth;
1098     $yearDiff = $nowYear - $dobYear;
1100     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1102     if ( $ageInMonths > 24 ) {
1103         $age = $yearDiff;
1104         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1105         else if ($monthDiff < 0) { $age -= 1; }
1106     }
1107     else  {
1108         $age = "$ageInMonths month"; 
1109     }
1111     return $age;
1115 // Returns Age in days
1116 //   in months if < 2 years old
1117 //   in years  if > 2 years old
1118 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1119 // (optional) nowYMD is a date in YYYYMMDD format
1120 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1121     $age = -1;
1123     // strip any dashes from the DOB
1124     $dobYMD = preg_replace("/-/", "", $dobYMD);
1125     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1126     
1127     // set the 'now' date values
1128     if ($nowYMD == null) {
1129         $nowDay = date("d");
1130         $nowMonth = date("m");
1131         $nowYear = date("Y");
1132     }
1133     else {
1134         $nowDay = substr($nowYMD,6,2);
1135         $nowMonth = substr($nowYMD,4,2);
1136         $nowYear = substr($nowYMD,0,4);
1137     }
1139     // do the date math
1140     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1141     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1142     $timediff = $nowtime - $dobtime;
1143     $age = $timediff / 86400;
1145     return $age;
1148 function dateToDB ($date)
1150     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1151     return $date;
1155 // ----------------------------------------------------------------------------
1157  * DROPDOWN FOR COUNTRIES
1158  * 
1159  * build a dropdown with all countries from geo_country_reference
1160  * 
1161  * @param int $selected - id for selected record
1162  * @param string $name - the name/id for select form
1163  * @return void - just echo the html encoded string
1164  */
1165 function dropdown_countries($selected = 0, $name = 'country_code') {
1166     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1168     $string = "<select name='$name' id='$name'>";
1169     while ( $row = sqlFetchArray($r) ) {
1170         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1171         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1172     }
1174     $string .= '</select>';
1175     echo $string;
1179 // ----------------------------------------------------------------------------
1181  * DROPDOWN FOR YES/NO
1182  * 
1183  * build a dropdown with two options (yes - 1, no - 0)
1184  * 
1185  * @param int $selected - id for selected record
1186  * @param string $name - the name/id for select form
1187  * @return void - just echo the html encoded string 
1188  */
1189 function dropdown_yesno($selected = 0, $name = 'yesno') {
1190     $string = "<select name='$name' id='$name'>";
1192     $selected = (int)$selected;
1193     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1194     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1196     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1197     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1198     $string .= '</select>';
1200     echo $string;
1203 // ----------------------------------------------------------------------------
1205  * DROPDOWN FOR MALE/FEMALE options
1206  * 
1207  * build a dropdown with three options (unselected/male/female)
1208  * 
1209  * @param int $selected - id for selected record
1210  * @param string $name - the name/id for select form
1211  * @return void - just echo the html encoded string
1212  */
1213 function dropdown_sex($selected = 0, $name = 'sex') {
1214     $string = "<select name='$name' id='$name'>";
1216     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1217     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1218     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1220     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1221     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1222     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1223     $string .= '</select>';
1225     echo $string;
1228 // ----------------------------------------------------------------------------
1230  * DROPDOWN FOR MARITAL STATUS
1231  * 
1232  * build a dropdown with marital status
1233  * 
1234  * @param int $selected - id for selected record
1235  * @param string $name - the name/id for select form
1236  * @return void - just echo the html encoded string
1237  */
1238 function dropdown_marital($selected = 0, $name = 'status') {
1239     $string = "<select name='$name' id='$name'>";
1241     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1243     foreach ( $statii as $st ) {
1244         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1245         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1246     }
1248     $string .= '</select>';
1250     echo $string;
1253 // ----------------------------------------------------------------------------
1255  * DROPDOWN FOR PROVIDERS
1256  * 
1257  * build a dropdown with all providers
1258  * 
1259  * @param int $selected - id for selected record
1260  * @param string $name - the name/id for select form
1261  * @return void - just echo the html encoded string
1262  */
1263 function dropdown_providers($selected = 0, $name = 'status') {
1264     $provideri = getProviderInfo();
1266     $string = "<select name='$name' id='$name'>";
1267     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1268     foreach ( $provideri as $s ) {
1269         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1270         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1271     }
1273     $string .= '</select>';
1275     echo $string;
1278 // ----------------------------------------------------------------------------
1280  * DROPDOWN FOR INSURANCE COMPANIES
1281  * 
1282  * build a dropdown with all insurers
1283  * 
1284  * @param int $selected - id for selected record
1285  * @param string $name - the name/id for select form
1286  * @return void - just echo the html encoded string
1287  */
1288 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1289     $insurancei = getInsuranceProviders();
1291     $string = "<select name='$name' id='$name'>";
1292     $string .= '<option value="0">Onbekend</option>';
1293     foreach ( $insurancei as $iid => $iname ) {
1294         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1295         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1296     }
1298     $string .= '</select>';
1300     echo $string;
1304 // ----------------------------------------------------------------------------
1306  * COUNTRY CODE
1307  * 
1308  * return the name or the country code, function of arguments
1309  * 
1310  * @param int $country_code
1311  * @param string $country_name
1312  * @return string | int - name or code
1313  */
1314 function country_code($country_code = 0, $country_name = '') {
1315     $strint = '';
1316     if ( $country_code ) {
1317         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1318     } else {
1319         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1320     }
1322     $db = $GLOBALS['adodb']['db'];
1323     $result = $db->Execute($sql);
1324     if ($result && !$result->EOF) {
1325         $strint = $result->fields['res'];
1326     }
1328     return $strint;
1331 function DBToDate ($date)
1333     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1334     return $date;
1337 function get_patient_balance($pid) {
1338   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1339     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1340       "pid = '$pid' AND activity = 1");
1341     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1342       "pid = '$pid'");
1343     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1344       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1345       "pid = '$pid'");
1346     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1347       - $drow['payments'] - $drow['adjustments']);
1348   }
1349   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1350     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1351     $conn = $GLOBALS['adodb']['db'];
1352     $customer_info['id'] = 0;
1353     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1354       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1355       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1356       "im.foreign_table = 'customer'";
1357     $result = $conn->Execute($sql);
1358     if($result && !$result->EOF) {
1359       $customer_info['id'] = $result->fields['foreign_id'];
1360     }
1361     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1362     $ws = new WSWrapper($function);
1363     if(is_numeric($ws->value)) {
1364       return sprintf('%01.2f', $ws->value);
1365     }
1366   }
1367   return '';