Internationalization: some more documentation fixes
[openemr.git] / library / patient.inc
blob3901f25c2c0ab3396697323abad34facf3652e0a
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once("{$GLOBALS['srcdir']}/sql.inc");
8 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
9 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
11 // These are for sports team use:
12 $PLAYER_FITNESSES = array(
13   xl('Full Play'),
14   xl('Full Training'),
15   xl('Restricted Training'),
16   xl('Injured Out'),
17   xl('Rehabilitation'),
18   xl('Illness'),
19   xl('International Duty')
21 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
23 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
24     $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
25     return sqlQuery($sql, array($pid) );
28 function getLanguages() {
29     $returnval = array('','english');
30     $sql = "select distinct lower(language) as language from patient_data";
31     $rez = sqlStatement($sql);
32     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
33         if (($row["language"] != "english") && ($row["language"] != "")) {
34             array_push($returnval, $row["language"]);
35         }
36     }
37     return $returnval;
40 function getInsuranceProvider($ins_id) {
41     
42     $sql = "select name from insurance_companies where id=?";
43     $row = sqlQuery($sql,array($ins_id));
44     return $row['name'];
45     
48 function getInsuranceProviders() {
49     $returnval = array();
51     if (true) {
52         $sql = "select name, id from insurance_companies order by name, id";
53         $rez = sqlStatement($sql);
54         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
55             $returnval[$row['id']] = $row['name'];
56         }
57     }
59     // Please leave this here. I have a user who wants to see zip codes and PO
60     // box numbers listed along with the insurance company names, as many companies
61     // have different billing addresses for different plans.  -- Rod Roark
62     //
63     else {
64         $sql = "select insurance_companies.name, insurance_companies.id, " .
65           "addresses.zip, addresses.line1 " .
66           "from insurance_companies, addresses " .
67           "where addresses.foreign_id = insurance_companies.id " .
68           "order by insurance_companies.name, addresses.zip";
70         $rez = sqlStatement($sql);
72         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
73             preg_match("/\d+/", $row['line1'], $matches);
74             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
75               "," . $matches[0] . ")";
76         }
77     }
79     return $returnval;
82 function getProviders() {
83     $returnval = array("");
84     $sql = "select fname, lname from users where authorized = 1 and " .
85         "active = 1 and username != ''";
86     $rez = sqlStatement($sql);
87     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
88         if (($row["fname"] != "") && ($row["lname"] != "")) {
89             array_push($returnval, $row["fname"] . " " . $row["lname"]);
90         }
91     }
92     return $returnval;
95 // ----------------------------------------------------------------------------
96 // Get one facility row.  If the ID is not specified, then get either the
97 // "main" (billing) facility, or the default facility of the currently
98 // logged-in user.  This was created to support genFacilityTitle() but
99 // may find additional uses.
101 function getFacility($facid=0) {
103   //create a sql binding array
104   $sqlBindArray = array();
105   
106   if ($facid > 0) {
107     $query = "SELECT * FROM facility WHERE id = ?";
108     array_push($sqlBindArray,$facid);
109   }
110   else if ($facid == 0) {
111     $query = "SELECT * FROM facility ORDER BY " .
112       "billing_location DESC, service_location, id LIMIT 1";
113   }
114   else {
115     $query = "SELECT facility.* FROM users, facility WHERE " .
116       "users.id = ? AND " .
117       "facility.id = users.facility_id";
118     array_push($sqlBindArray,$_SESSION['authUserID']);
119   }
120   return sqlQuery($query,$sqlBindArray);
123 // Generate a report title including report name and facility name, address
124 // and phone.
126 function genFacilityTitle($repname='', $facid=0) {
127   $s = '';
128   $s .= "<table class='ftitletable'>\n";
129   $s .= " <tr>\n";
130   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
131   $s .= "  <td class='ftitlecell2'>\n";
132   $r = getFacility($facid);
133   if (!empty($r)) {
134     $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
135     if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
136     if ($r['city'] || $r['state'] || $r['postal_code']) {
137       $s .= "<br />";
138       if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
139       if ($r['state']) {
140         if ($r['city']) $s .= ", \n";
141         $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
142       }
143       if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
144       $s .= "\n";
145     }
146     if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
147     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
148   }
149   $s .= "  </td>\n";
150   $s .= " </tr>\n";
151   $s .= "</table>\n";
152   return $s;
156 GET FACILITIES
158 returns all facilities or just the id for the first one
159 (FACILITY FILTERING (lemonsoftware))
161 @param string - if 'first' return first facility ordered by id
162 @return array | int for 'first' case
164 function getFacilities($first = '') {
165     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
166     $ret = array();
167     while ( $row = sqlFetchArray($r) ) {
168        $ret[] = $row;
171         if ( $first == 'first') {
172             return $ret[0]['id'];
173         } else {
174             return $ret;
175         }
179 GET SERVICE FACILITIES
181 returns all service_location facilities or just the id for the first one
182 (FACILITY FILTERING (CHEMED))
184 @param string - if 'first' return first facility ordered by id
185 @return array | int for 'first' case
187 function getServiceFacilities($first = '') {
188     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
189     $ret = array();
190     while ( $row = sqlFetchArray($r) ) {
191        $ret[] = $row;
194         if ( $first == 'first') {
195             return $ret[0]['id'];
196         } else {
197             return $ret;
198         }
201 //(CHEMED) facility filter
202 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
203     $param1 = "";
204     if ($providers_only === 'any') {
205       $param1 = " AND authorized = 1 AND active = 1 ";
206     }
207     else if ($providers_only) {
208       $param1 = " AND authorized = 1 AND calendar = 1 ";
209     }
211     //--------------------------------
212     //(CHEMED) facility filter
213     $param2 = "";
214     if ($facility) {
215       if ($GLOBALS['restrict_user_facility']) {
216         $param2 = " AND (facility_id = $facility 
217           OR  $facility IN
218                 (select facility_id 
219                 from users_facility
220                 where tablename = 'users'
221                 and table_id = id)
222                 )
223           ";
224       }
225       else {
226         $param2 = " AND facility_id = $facility ";
227       }
228     }
229     //--------------------------------
231     $command = "=";
232     if ($providerID == "%") {
233         $command = "like";
234     }
235     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
236         "from users where username != '' and active = 1 and id $command '" .
237         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
238     // sort by last name -- JRM June 2008
239     $query .= " ORDER BY lname, fname ";
240     $rez = sqlStatement($query);
241     for($iter=0; $row=sqlFetchArray($rez); $iter++)
242         $returnval[$iter]=$row;
244     //if only one result returned take the key/value pairs in array [0] and merge them down the the base array so that $resultval[0]['key'] is also
245     //accessible from $resultval['key']
247     if($iter==1) {
248         $akeys = array_keys($returnval[0]);
249         foreach($akeys as $key) {
250             $returnval[0][$key] = $returnval[0][$key];
251         }
252     }
253     return $returnval;
256 //same as above but does not reduce if only 1 row returned
257 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
258     $param1 = "";
259     if ($providers_only) {
260         $param1 = "AND authorized=1";
261     }
262     $command = "=";
263     if ($providerID == "%") {
264         $command = "like";
265     }
266     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
267         "from users where active = 1 and username != '' and id $command '" .
268         mysql_real_escape_string($providerID) . "' " . $param1;
270     $rez = sqlStatement($query);
271     for($iter=0; $row=sqlFetchArray($rez); $iter++)
272         $returnval[$iter]=$row;
274     return $returnval;
277 function getProviderName($providerID) {
278     $pi = getProviderInfo($providerID, 'any');
279     if (strlen($pi[0]["lname"]) > 0) {
280         return $pi[0]['fname'] . " " . $pi[0]['lname'];
281     }
282     return "";
285 function getProviderId($providerName) {
286     $query = "select id from users where username = ?";
287     $rez = sqlStatement($query, array($providerName) );
288     for($iter=0; $row=sqlFetchArray($rez); $iter++)
289         $returnval[$iter]=$row;
290     return $returnval;
293 function getEthnoRacials() {
294     $returnval = array("");
295     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
296     $rez = sqlStatement($sql);
297     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
298         if (($row["ethnoracial"] != "")) {
299             array_push($returnval, $row["ethnoracial"]);
300         }
301     }
302     return $returnval;
305 function getHistoryData($pid, $given = "*")
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 = "%",
443   $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
444   $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
446         $layoutCols = split( '~', $searchFields );
447   $sqlBindArray = array();
448   $where = "";
449   $i = 0;
450   foreach ($layoutCols as $val) {
451     if (empty($val)) continue;
452                 if ( $i > 0 ) {
453                    $where .= " or ";
454                 }
455     if ($val == 'pid') {
456                 $where .= " ".add_escape_custom($val)." = ? ";
457                 array_push($sqlBindArray, $searchTerm);
458     }
459     else {
460                 $where .= " ".add_escape_custom($val)." like ? ";
461                 array_push($sqlBindArray, $searchTerm."%");
462     }
463                 $i++;
464         }
466   // If no search terms, ensure valid syntax.
467   if ($i == 0) $where = "1 = 1";
469   // If a non-empty service code was given, then restrict to patients who
470   // have been provided that service.  Since the code is used in a LIKE
471   // clause, % and _ wildcards are supported.
472   if ($search_service_code) {
473     $where = "( $where ) AND " .
474       "( SELECT COUNT(*) FROM billing AS b WHERE " .
475       "b.pid = patient_data.pid AND " .
476       "b.activity = 1 AND " .
477       "b.code_type != 'COPAY' AND " .
478       "b.code LIKE ? " .
479       ") > 0";
480     array_push($sqlBindArray, $search_service_code);
481   }
483   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
484   if ($limit != "all") $sql .= " limit $start, $limit";
485   $rez = sqlStatement($sql, $sqlBindArray);
486   for($iter=0; $row=sqlFetchArray($rez); $iter++)
487       $returnval[$iter]=$row;
488   _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
489   return $returnval;
492 // return a collection of Patient PIDs
493 // new arg style by JRM March 2008
494 // 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")
495 function getPatientPID($args)
497     $pid = "%";
498     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
499     $orderby = "lname ASC, fname ASC";
500     $limit="all";
501     $start="0";
503     // alter default values if defined in the passed in args
504     if (isset($args['pid'])) { $pid = $args['pid']; }
505     if (isset($args['given'])) { $given = $args['given']; }
506     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
507     if (isset($args['limit'])) { $limit = $args['limit']; }
508     if (isset($args['start'])) { $start = $args['start']; }
510     $command = "=";
511     if ($pid == -1) $pid = "%";
512     elseif (empty($pid)) $pid = "NULL";
514     if (strstr($pid,"%")) $command = "like";
516     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
517     if ($limit != "all") $sql .= " limit $start, $limit";
519     $rez = sqlStatement($sql);
520     for($iter=0; $row=sqlFetchArray($rez); $iter++)
521         $returnval[$iter]=$row;
523     return $returnval;
526 /* return a patient's name in the format LAST, FIRST */
527 function getPatientName($pid) {
528     if (empty($pid)) return "";
529     $patientData = getPatientPID(array("pid"=>$pid));
530     if (empty($patientData[0]['lname'])) return "";
531     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
532     return $patientName;
535 /* find patient data by DOB */
536 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
538     $DOB = fixDate($DOB, $DOB);
539     $sqlBindArray = array();
540     $where = "DOB like ? ";
541     array_push($sqlBindArray, $DOB."%");
542         if (!empty($GLOBALS['pt_restrict_field'])) {
543                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
544                         $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
545                                 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
546                                 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
547                         array_push($sqlBindArray, $_SESSION{"authUser"});
548                 }
549         }
551     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
553     if ($limit != "all") $sql .= " LIMIT $start, $limit";
555     $rez = sqlStatement($sql, $sqlBindArray);
556     for($iter=0; $row=sqlFetchArray($rez); $iter++)
557         $returnval[$iter]=$row;
559     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
560     return $returnval;
563 /* find patient data by SSN */
564 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
566     $sqlBindArray = array();
567     $where = "ss LIKE ?";
568     array_push($sqlBindArray, $ss."%");
569     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
570     if ($limit != "all") $sql .= " LIMIT $start, $limit";
572     $rez = sqlStatement($sql, $sqlBindArray);
573     for($iter=0; $row=sqlFetchArray($rez); $iter++)
574         $returnval[$iter]=$row;
576     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
577     return $returnval;
580 //(CHEMED) Search by phone number
581 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
583     $phone = ereg_replace( "[[:punct:]]","", $phone );
584     $sqlBindArray = array();
585     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
586     array_push($sqlBindArray, $phone);
587     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
588     if ($limit != "all") $sql .= " LIMIT $start, $limit";
590     $rez = sqlStatement($sql, $sqlBindArray);
591     for($iter=0; $row=sqlFetchArray($rez); $iter++)
592         $returnval[$iter]=$row;
594     _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
595     return $returnval;
598 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
600     $sql="select $given from patient_data order by $orderby";
602     if ($limit != "all")
603         $sql .= " limit $start, $limit";
605     $rez = sqlStatement($sql);
606     for($iter=0; $row=sqlFetchArray($rez); $iter++)
607         $returnval[$iter]=$row;
609     return $returnval;
612 //----------------------input functions
613 function newPatientData(    $db_id="",
614                 $title = "",
615                 $fname = "",
616                 $lname = "",
617                 $mname = "",
618                 $sex = "",
619                 $DOB = "",
620                 $street = "",
621                 $postal_code = "",
622                 $city = "",
623                 $state = "",
624                 $country_code = "",
625                 $ss = "",
626                 $occupation = "",
627                 $phone_home = "",
628                 $phone_biz = "",
629                 $phone_contact = "",
630                 $status = "",
631                 $contact_relationship = "",
632                 $referrer = "",
633                 $referrerID = "",
634                 $email = "",
635                 $language = "",
636                 $ethnoracial = "",
637                 $interpretter = "",
638                 $migrantseasonal = "",
639                 $family_size = "",
640                 $monthly_income = "",
641                 $homeless = "",
642                 $financial_review = "",
643                 $pubpid = "",
644                 $pid = "MAX(pid)+1",
645                 $providerID = "",
646                 $genericname1 = "",
647                 $genericval1 = "",
648                 $genericname2 = "",
649                 $genericval2 = "",
650                 $phone_cell = "",
651                 $hipaa_mail = "",
652                 $hipaa_voice = "",
653                 $squad = 0,
654                 $pharmacy_id = 0,
655                 $drivers_license = "",
656                 $hipaa_notice = "",
657                 $hipaa_message = "",
658                 $regdate = ""
659             )
661     $DOB = fixDate($DOB);
662     $regdate = fixDate($regdate);
664     $fitness = 0;
665     $referral_source = '';
666     if ($pid) {
667         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
668         // Check for brain damage:
669         if ($db_id != $rez['id']) {
670             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
671               $rez['id'] . "' to '$db_id' for pid '$pid'";
672             die($errmsg);
673         }
674         $fitness = $rez['fitness'];
675         $referral_source = $rez['referral_source'];
676     }
678     // Get the default price level.
679     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
680       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
681     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
683     $query = ("replace into patient_data set
684         id='$db_id',
685         title='$title',
686         fname='$fname',
687         lname='$lname',
688         mname='$mname',
689         sex='$sex',
690         DOB='$DOB',
691         street='$street',
692         postal_code='$postal_code',
693         city='$city',
694         state='$state',
695         country_code='$country_code',
696         drivers_license='$drivers_license',
697         ss='$ss',
698         occupation='$occupation',
699         phone_home='$phone_home',
700         phone_biz='$phone_biz',
701         phone_contact='$phone_contact',
702         status='$status',
703         contact_relationship='$contact_relationship',
704         referrer='$referrer',
705         referrerID='$referrerID',
706         email='$email',
707         language='$language',
708         ethnoracial='$ethnoracial',
709         interpretter='$interpretter',
710         migrantseasonal='$migrantseasonal',
711         family_size='$family_size',
712         monthly_income='$monthly_income',
713         homeless='$homeless',
714         financial_review='$financial_review',
715         pubpid='$pubpid',
716         pid = $pid,
717         providerID = '$providerID',
718         genericname1 = '$genericname1',
719         genericval1 = '$genericval1',
720         genericname2 = '$genericname2',
721         genericval2 = '$genericval2',
722         phone_cell = '$phone_cell',
723         pharmacy_id = '$pharmacy_id',
724         hipaa_mail = '$hipaa_mail',
725         hipaa_voice = '$hipaa_voice',
726         hipaa_notice = '$hipaa_notice',
727         hipaa_message = '$hipaa_message',
728         squad = '$squad',
729         fitness='$fitness',
730         referral_source='$referral_source',
731         regdate='$regdate',
732         pricelevel='$pricelevel',
733         date=NOW()");
735     $id = sqlInsert($query);
737     if ( !$db_id ) {
738       // find the last inserted id for new patient case
739       $db_id = mysql_insert_id();
740     }
742     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
744     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
745                 $phone_biz,$phone_cell,$email,$pid);
747     return $foo['pid'];
750 // Supported input date formats are:
751 //   mm/dd/yyyy
752 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
753 //   yyyy/mm/dd
754 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
756 function fixDate($date, $default="0000-00-00") {
757     $fixed_date = $default;
758     $date = trim($date);
759     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
760         $dmy = preg_split("'[/.-]'", $date);
761         if ($dmy[0] > 99) {
762             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
763         } else {
764             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
765               if ($dmy[2] < 1000) $dmy[2] += 1900;
766               if ($dmy[2] < 1910) $dmy[2] += 100;
767             }
768             // phone_country_code indicates format of ambiguous input dates.
769             if ($GLOBALS['phone_country_code'] == 1)
770               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
771             else
772               $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
773         }
774     }
776     return $fixed_date;
779 function pdValueOrNull($key, $value) {
780   if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
781     substr($key, 0, 8) == 'userdate') &&
782     (empty($value) || $value == '0000-00-00'))
783   {
784     return "NULL";
785   }
786   else {
787     return "'$value'";
788   }
791 // Create or update patient data from an array.
793 function updatePatientData($pid, $new, $create=false)
795   /*******************************************************************
796     $real = getPatientData($pid);
797     $new['DOB'] = fixDate($new['DOB']);
798     while(list($key, $value) = each ($new))
799         $real[$key] = $value;
800     $real['date'] = "'+NOW()+'";
801     $real['id'] = "";
802     $sql = "insert into patient_data set ";
803     while(list($key, $value) = each($real))
804         $sql .= $key." = '$value', ";
805     $sql = substr($sql, 0, -2);
806     return sqlInsert($sql);
807   *******************************************************************/
809   // The above was broken, though seems intent to insert a new patient_data
810   // row for each update.  A good idea, but nothing is doing that yet so
811   // the code below does not yet attempt it.
813   $new['DOB'] = fixDate($new['DOB']);
815   if ($create) {
816     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
817     foreach ($new as $key => $value) {
818       if ($key == 'id') continue;
819       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
820     }
821     $db_id = sqlInsert($sql);
822   }
823   else {
824     $db_id = $new['id'];
825     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
826     // Check for brain damage:
827     if ($pid != $rez['pid']) {
828       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
829         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
830       die($errmsg);
831     }
832     $sql = "UPDATE patient_data SET date = NOW()";
833     foreach ($new as $key => $value) {
834       $sql .= ", `$key` = " . pdValueOrNull($key, $value);
835     }
836     $sql .= " WHERE id = '$db_id'";
837     sqlStatement($sql);
838   }
840   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
841   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
842     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
843     $rez['phone_cell'],$rez['email'],$rez['pid']);
845   return $db_id;
848 function newEmployerData(    $pid,
849                 $name = "",
850                 $street = "",
851                 $postal_code = "",
852                 $city = "",
853                 $state = "",
854                 $country = ""
855             )
857     return sqlInsert("insert into employer_data set
858         name='$name',
859         street='$street',
860         postal_code='$postal_code',
861         city='$city',
862         state='$state',
863         country='$country',
864         pid='$pid',
865         date=NOW()
866         ");
869 // Create or update employer data from an array.
871 function updateEmployerData($pid, $new, $create=false)
873   $colnames = array('name','street','city','state','postal_code','country');
875   if ($create) {
876     $set .= "pid = '$pid', date = NOW()";
877     foreach ($colnames as $key) {
878       $value = isset($new[$key]) ? $new[$key] : '';
879       $set .= ", `$key` = '$value'";
880     }
881     return sqlInsert("INSERT INTO employer_data SET $set");
882   }
883   else {
884     $set = '';
885     $old = getEmployerData($pid);
886     $modified = false;
887     foreach ($colnames as $key) {
888       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
889       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
890         $value = $new[$key];
891         $modified = true;
892       }
893       $set .= "`$key` = '$value', ";
894     }
895     if ($modified) {
896       $set .= "pid = '$pid', date = NOW()";
897       return sqlInsert("INSERT INTO employer_data SET $set");
898     }
899     return $old['id'];
900   }
903 // This updates or adds the given insurance data info, while retaining any
904 // previously added insurance_data rows that should be preserved.
905 // This does not directly support the maintenance of non-current insurance.
907 function newInsuranceData(
908   $pid,
909   $type = "",
910   $provider = "",
911   $policy_number = "",
912   $group_number = "",
913   $plan_name = "",
914   $subscriber_lname = "",
915   $subscriber_mname = "",
916   $subscriber_fname = "",
917   $subscriber_relationship = "",
918   $subscriber_ss = "",
919   $subscriber_DOB = "",
920   $subscriber_street = "",
921   $subscriber_postal_code = "",
922   $subscriber_city = "",
923   $subscriber_state = "",
924   $subscriber_country = "",
925   $subscriber_phone = "",
926   $subscriber_employer = "",
927   $subscriber_employer_street = "",
928   $subscriber_employer_city = "",
929   $subscriber_employer_postal_code = "",
930   $subscriber_employer_state = "",
931   $subscriber_employer_country = "",
932   $copay = "",
933   $subscriber_sex = "",
934   $effective_date = "0000-00-00",
935   $accept_assignment = "TRUE")
937   if (strlen($type) <= 0) return FALSE;
939   // If a bad date was passed, err on the side of caution.
940   $effective_date = fixDate($effective_date, date('Y-m-d'));
942   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
943     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
944   $idrow = sqlFetchArray($idres);
946   // Replace the most recent entry in any of the following cases:
947   // * Its effective date is >= this effective date.
948   // * It is the first entry and it has no (insurance) provider.
949   // * There is no encounter that is earlier than the new effective date but
950   //   on or after the old effective date.
951   // Otherwise insert a new entry.
953   $replace = false;
954   if ($idrow) {
955     if (strcmp($idrow['date'], $effective_date) > 0) {
956       $replace = true;
957     }
958     else {
959       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
960         $replace = true;
961       }
962       else {
963         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
964           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
965           "date >= '" . $idrow['date'] . " 00:00:00'");
966         if ($ferow['count'] == 0) $replace = true;
967       }
968     }
969   }
971   if ($replace) {
973     // TBD: This is a bit dangerous in that a typo in entering the effective
974     // date can wipe out previous insurance history.  So we want some data
975     // entry validation somewhere.
976     sqlStatement("DELETE FROM insurance_data WHERE " .
977       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
978       "id != " . $idrow['id']);
980     $data = array();
981     $data['type'] = $type;
982     $data['provider'] = $provider;
983     $data['policy_number'] = $policy_number;
984     $data['group_number'] = $group_number;
985     $data['plan_name'] = $plan_name;
986     $data['subscriber_lname'] = $subscriber_lname;
987     $data['subscriber_mname'] = $subscriber_mname;
988     $data['subscriber_fname'] = $subscriber_fname;
989     $data['subscriber_relationship'] = $subscriber_relationship;
990     $data['subscriber_ss'] = $subscriber_ss;
991     $data['subscriber_DOB'] = $subscriber_DOB;
992     $data['subscriber_street'] = $subscriber_street;
993     $data['subscriber_postal_code'] = $subscriber_postal_code;
994     $data['subscriber_city'] = $subscriber_city;
995     $data['subscriber_state'] = $subscriber_state;
996     $data['subscriber_country'] = $subscriber_country;
997     $data['subscriber_phone'] = $subscriber_phone;
998     $data['subscriber_employer'] = $subscriber_employer;
999     $data['subscriber_employer_city'] = $subscriber_employer_city;
1000     $data['subscriber_employer_street'] = $subscriber_employer_street;
1001     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1002     $data['subscriber_employer_state'] = $subscriber_employer_state;
1003     $data['subscriber_employer_country'] = $subscriber_employer_country;
1004     $data['copay'] = $copay;
1005     $data['subscriber_sex'] = $subscriber_sex;
1006     $data['pid'] = $pid;
1007     $data['date'] = $effective_date;
1008     $data['accept_assignment'] = $accept_assignment;
1009     updateInsuranceData($idrow['id'], $data);
1010     return $idrow['id'];
1011   }
1012   else {
1013     return sqlInsert("INSERT INTO insurance_data SET
1014       type = '$type',
1015       provider = '$provider',
1016       policy_number = '$policy_number',
1017       group_number = '$group_number',
1018       plan_name = '$plan_name',
1019       subscriber_lname = '$subscriber_lname',
1020       subscriber_mname = '$subscriber_mname',
1021       subscriber_fname = '$subscriber_fname',
1022       subscriber_relationship = '$subscriber_relationship',
1023       subscriber_ss = '$subscriber_ss',
1024       subscriber_DOB = '$subscriber_DOB',
1025       subscriber_street = '$subscriber_street',
1026       subscriber_postal_code = '$subscriber_postal_code',
1027       subscriber_city = '$subscriber_city',
1028       subscriber_state = '$subscriber_state',
1029       subscriber_country = '$subscriber_country',
1030       subscriber_phone = '$subscriber_phone',
1031       subscriber_employer = '$subscriber_employer',
1032       subscriber_employer_city = '$subscriber_employer_city',
1033       subscriber_employer_street = '$subscriber_employer_street',
1034       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1035       subscriber_employer_state = '$subscriber_employer_state',
1036       subscriber_employer_country = '$subscriber_employer_country',
1037       copay = '$copay',
1038       subscriber_sex = '$subscriber_sex',
1039       pid = '$pid',
1040       date = '$effective_date',
1041       accept_assignment = '$accept_assignment'
1042     ");
1043   }
1046 // This is used internally only.
1047 function updateInsuranceData($id, $new)
1049   $fields = sqlListFields("insurance_data");
1050   $use = array();
1052   while(list($key, $value) = each ($new)) {
1053     if (in_array($key, $fields)) {
1054       $use[$key] = $value;
1055     }
1056   }
1058   $sql = "UPDATE insurance_data SET ";
1059   while(list($key, $value) = each($use))
1060     $sql .= "`$key` = '$value', ";
1061   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1063   sqlStatement($sql);
1066 function newHistoryData($pid, $new=false) {
1067   $arraySqlBind = array();
1068   $sql = "insert into history_data set pid = ?, date = NOW()";
1069   array_push($arraySqlBind,$pid);
1070   if ($new) {
1071     while(list($key, $value) = each($new)) {
1072       array_push($arraySqlBind,$value);
1073       $sql .= ", `$key` = ?";
1074     }
1075   }
1076   return sqlInsert($sql, $arraySqlBind );
1079 function updateHistoryData($pid,$new)
1081         $real = getHistoryData($pid);
1082         while(list($key, $value) = each ($new))
1083                 $real[$key] = $value;
1084         $real['id'] = "";
1085         // need to unset date, so can reset it below
1086         unset($real['date']);
1088         $arraySqlBind = array();
1089         $sql = "insert into history_data set `date` = NOW(), ";
1090         while(list($key, $value) = each($real)) {
1091                 array_push($arraySqlBind,$value);
1092                 $sql .= "`$key` = ?, ";
1093         }
1094         $sql = substr($sql, 0, -2);
1096         return sqlInsert($sql, $arraySqlBind );
1099 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1100                 $phone_biz,$phone_cell,$email,$pid="")
1102     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1103     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1105     $db = $GLOBALS['adodb']['db'];
1106     $customer_info = array();
1108     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1109     $result = $db->Execute($sql);
1110     if ($result && !$result->EOF) {
1111         $customer_info['foreign_update'] = true;
1112         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1113         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1114     }
1116     ///xml rpc code to connect to accounting package and add user to it
1117     $customer_info['firstname'] = $fname;
1118     $customer_info['lastname'] = $lname;
1119     $customer_info['address'] = $street;
1120     $customer_info['suburb'] = $city;
1121     $customer_info['state'] = $state;
1122     $customer_info['postcode'] = $postal_code;
1124     //ezybiz wants state as a code rather than abbreviation
1125     $customer_info['geo_zone_id'] = "";
1126     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1127     $db = $GLOBALS['adodb']['db'];
1128     $result = $db->Execute($sql);
1129     if ($result && !$result->EOF) {
1130         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1131     }
1133     //ezybiz wants country as a code rather than abbreviation
1134     $customer_info['geo_country_id'] = "";
1135     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1136     $db = $GLOBALS['adodb']['db'];
1137     $result = $db->Execute($sql);
1138     if ($result && !$result->EOF) {
1139         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1140     }
1142     $customer_info['phone1'] = $phone_home;
1143     $customer_info['phone1comment'] = "Home Phone";
1144     $customer_info['phone2'] = $phone_biz;
1145     $customer_info['phone2comment'] = "Business Phone";
1146     $customer_info['phone3'] = $phone_cell;
1147     $customer_info['phone3comment'] = "Cell Phone";
1148     $customer_info['email'] = $email;
1149     $customer_info['customernumber'] = $pid;
1151     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1152     $ws = new WSWrapper($function);
1154     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1155     if (is_numeric($ws->value)) {
1156         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1157         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1158     }
1161 // Returns Age 
1162 //   in months if < 2 years old
1163 //   in years  if > 2 years old
1164 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1165 // (optional) nowYMD is a date in YYYYMMDD format
1166 function getPatientAge($dobYMD, $nowYMD=null)
1168     // strip any dashes from the DOB
1169     $dobYMD = preg_replace("/-/", "", $dobYMD);
1170     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1171     
1172     // set the 'now' date values
1173     if ($nowYMD == null) {
1174         $nowDay = date("d");
1175         $nowMonth = date("m");
1176         $nowYear = date("Y");
1177     }
1178     else {
1179         $nowDay = substr($nowYMD,6,2);
1180         $nowMonth = substr($nowYMD,4,2);
1181         $nowYear = substr($nowYMD,0,4);
1182     }
1184     $dayDiff = $nowDay - $dobDay;
1185     $monthDiff = $nowMonth - $dobMonth;
1186     $yearDiff = $nowYear - $dobYear;
1188     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1190     if ( $ageInMonths > 24 ) {
1191         $age = $yearDiff;
1192         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1193         else if ($monthDiff < 0) { $age -= 1; }
1194     }
1195     else  {
1196         $age = "$ageInMonths month"; 
1197     }
1199     return $age;
1203 // Returns Age in days
1204 //   in months if < 2 years old
1205 //   in years  if > 2 years old
1206 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1207 // (optional) nowYMD is a date in YYYYMMDD format
1208 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1209     $age = -1;
1211     // strip any dashes from the DOB
1212     $dobYMD = preg_replace("/-/", "", $dobYMD);
1213     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1214     
1215     // set the 'now' date values
1216     if ($nowYMD == null) {
1217         $nowDay = date("d");
1218         $nowMonth = date("m");
1219         $nowYear = date("Y");
1220     }
1221     else {
1222         $nowDay = substr($nowYMD,6,2);
1223         $nowMonth = substr($nowYMD,4,2);
1224         $nowYear = substr($nowYMD,0,4);
1225     }
1227     // do the date math
1228     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1229     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1230     $timediff = $nowtime - $dobtime;
1231     $age = $timediff / 86400;
1233     return $age;
1236 function dateToDB ($date)
1238     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1239     return $date;
1243 // ----------------------------------------------------------------------------
1245  * DROPDOWN FOR COUNTRIES
1246  * 
1247  * build a dropdown with all countries from geo_country_reference
1248  * 
1249  * @param int $selected - id for selected record
1250  * @param string $name - the name/id for select form
1251  * @return void - just echo the html encoded string
1252  */
1253 function dropdown_countries($selected = 0, $name = 'country_code') {
1254     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1256     $string = "<select name='$name' id='$name'>";
1257     while ( $row = sqlFetchArray($r) ) {
1258         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1259         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1260     }
1262     $string .= '</select>';
1263     echo $string;
1267 // ----------------------------------------------------------------------------
1269  * DROPDOWN FOR YES/NO
1270  * 
1271  * build a dropdown with two options (yes - 1, no - 0)
1272  * 
1273  * @param int $selected - id for selected record
1274  * @param string $name - the name/id for select form
1275  * @return void - just echo the html encoded string 
1276  */
1277 function dropdown_yesno($selected = 0, $name = 'yesno') {
1278     $string = "<select name='$name' id='$name'>";
1280     $selected = (int)$selected;
1281     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1282     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1284     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1285     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1286     $string .= '</select>';
1288     echo $string;
1291 // ----------------------------------------------------------------------------
1293  * DROPDOWN FOR MALE/FEMALE options
1294  * 
1295  * build a dropdown with three options (unselected/male/female)
1296  * 
1297  * @param int $selected - id for selected record
1298  * @param string $name - the name/id for select form
1299  * @return void - just echo the html encoded string
1300  */
1301 function dropdown_sex($selected = 0, $name = 'sex') {
1302     $string = "<select name='$name' id='$name'>";
1304     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1305     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1306     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1308     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1309     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1310     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1311     $string .= '</select>';
1313     echo $string;
1316 // ----------------------------------------------------------------------------
1318  * DROPDOWN FOR MARITAL STATUS
1319  * 
1320  * build a dropdown with marital status
1321  * 
1322  * @param int $selected - id for selected record
1323  * @param string $name - the name/id for select form
1324  * @return void - just echo the html encoded string
1325  */
1326 function dropdown_marital($selected = 0, $name = 'status') {
1327     $string = "<select name='$name' id='$name'>";
1329     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1331     foreach ( $statii as $st ) {
1332         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1333         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1334     }
1336     $string .= '</select>';
1338     echo $string;
1341 // ----------------------------------------------------------------------------
1343  * DROPDOWN FOR PROVIDERS
1344  * 
1345  * build a dropdown with all providers
1346  * 
1347  * @param int $selected - id for selected record
1348  * @param string $name - the name/id for select form
1349  * @return void - just echo the html encoded string
1350  */
1351 function dropdown_providers($selected = 0, $name = 'status') {
1352     $provideri = getProviderInfo();
1354     $string = "<select name='$name' id='$name'>";
1355     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1356     foreach ( $provideri as $s ) {
1357         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1358         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1359     }
1361     $string .= '</select>';
1363     echo $string;
1366 // ----------------------------------------------------------------------------
1368  * DROPDOWN FOR INSURANCE COMPANIES
1369  * 
1370  * build a dropdown with all insurers
1371  * 
1372  * @param int $selected - id for selected record
1373  * @param string $name - the name/id for select form
1374  * @return void - just echo the html encoded string
1375  */
1376 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1377     $insurancei = getInsuranceProviders();
1379     $string = "<select name='$name' id='$name'>";
1380     $string .= '<option value="0">Onbekend</option>';
1381     foreach ( $insurancei as $iid => $iname ) {
1382         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1383         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1384     }
1386     $string .= '</select>';
1388     echo $string;
1392 // ----------------------------------------------------------------------------
1394  * COUNTRY CODE
1395  * 
1396  * return the name or the country code, function of arguments
1397  * 
1398  * @param int $country_code
1399  * @param string $country_name
1400  * @return string | int - name or code
1401  */
1402 function country_code($country_code = 0, $country_name = '') {
1403     $strint = '';
1404     if ( $country_code ) {
1405         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1406     } else {
1407         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1408     }
1410     $db = $GLOBALS['adodb']['db'];
1411     $result = $db->Execute($sql);
1412     if ($result && !$result->EOF) {
1413         $strint = $result->fields['res'];
1414     }
1416     return $strint;
1419 function DBToDate ($date)
1421     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1422     return $date;
1425 function get_patient_balance($pid) {
1426   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1427     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1428       "pid = ? AND activity = 1", array($pid) );
1429     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1430       "pid = ?", array($pid) );
1431     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1432       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1433       "pid = ?", array($pid) );
1434     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1435       - $drow['payments'] - $drow['adjustments']);
1436   }
1437   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1438     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1439     $conn = $GLOBALS['adodb']['db'];
1440     $customer_info['id'] = 0;
1441     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1442       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1443       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1444       "im.foreign_table = 'customer'";
1445     $result = $conn->Execute($sql);
1446     if($result && !$result->EOF) {
1447       $customer_info['id'] = $result->fields['foreign_id'];
1448     }
1449     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1450     $ws = new WSWrapper($function);
1451     if(is_numeric($ws->value)) {
1452       return sprintf('%01.2f', $ws->value);
1453     }
1454   }
1455   return '';